As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
I have written a crontab deploy tool in python: https://github.com/monklof/deploycron
pip install deploycron
Install your crontab is very easy, this will merge the crontab into the system's existing crontab.
from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
0
and 7
both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.
Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON
, THU
, etc:
0 - Sun Sunday
1 - Mon Monday
2 - Tue Tuesday
3 - Wed Wednesday
4 - Thu Thursday
5 - Fri Friday
6 - Sat Saturday
7 - Sun Sunday
Graphically:
+---------- minute (0 - 59)
¦ +-------- hour (0 - 23)
¦ ¦ +------ day of month (1 - 31)
¦ ¦ ¦ +---- month (1 - 12)
¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
¦ ¦ ¦ ¦ ¦ 1 - 7 => Monday - Sunday)
? ? ? ? ?
* * * * * command to be executed
Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU
will exectute the command only on sundays, mondays on thursdays.
You can read further details in Wikipedia's article about Cron.
This should do it
shell_exec("crontab -l | { cat; echo '*/1 * * * * command'; } |crontab -");
Change Minute parameter to 0.
You can set the cron for every three hours as:
0 */3 * * * your command here ..
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
Create a .pgpass
file in the home directory of the account that pg_dump
will run as.
The format is:
hostname:port:database:username:password
Then, set the file's mode to 0600
. Otherwise, it will be ignored.
chmod 600 ~/.pgpass
See the Postgresql documentation libpq-pgpass for more details.
Personally, I have create a file.sh (right 755) in the root directory, file who do this job, on order of the crontab.
Crontab code:
10 2 * * * root /root/backupautomatique.sh
File.sh code:
rm -f /home/mordb-148-251-89-66.sql.gz #(To erase the old one)
mysqldump mor | gzip > /home/mordb-148-251-89-66.sql.gz (what you have done)
scp -P2222 /home/mordb-148-251-89-66.sql.gz root@otherip:/home/mordbexternes/mordb-148-251-89-66.sql.gz
(to send a copy somewhere else if the sending server crashes, because too old, like me ;-))
For me I had to specify path in my NodeJS file.
// did not work!!!!!
require('dotenv').config()
instead
// DID WORK!!
require('dotenv').config({ path: '/full/custom/path/to/your/.env' })
Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH
An easy way to write cron is to use the online cron generator It will generate the line for you. One thing to note is that if you wish to run it each day (not just weekdays) you need to highlight all the days.
I think you would like this interactive website, which often helps me build complex Crontab directives: https://crontab.guru/
Applied the instructions from this answer and it worked
Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:
cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
set package_name=cygrunsrv cron
setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%
Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...
Now in cmd promt:
C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D
or whatever full file path you might have to the cygrunsrv.exe and start the cron as windows service in the cmd prompt
net start cron
Now in bash terminal run crontab -e
set up you cron entry an example bellow:
#sync my gdrive each 10th minute
*/10 * * * * /home/Yordan/sync_gdrive.sh
# * * * * * command to be executed
# - - - - -
# | | | | |
# | | | | +- - - - day of week (0 - 6) (Sunday=0)
# | | | +- - - - - month (1 - 12)
# | | +- - - - - - day of month (1 - 31)
# | +- - - - - - - hour (0 - 23)
# +--------------- minute
You can also try using runuser
(as root) to run a command as a different user
*/1 * * * * runuser php5 \
--command="/var/www/web/includes/crontab/queue_process.php \
>> /var/www/web/includes/crontab/queue.log 2>&1"
See also: man runuser
Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Example::Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.
Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/yourname/full-backup
In your case, for 2.30PM
,
30 14 * * * YOURCMD
To know more about cron, visit this website.
Paste this function in your Module and use it as like formula
Public Function format_date(t As String)
format_date = Format(t, "YYYY-MM-DD")
End Function
for example in Cell A1 apply this formula
=format_date(now())
it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.
Another way to get the EF version you are using is to open the Package Manager Console (PMC) in Visual Studio and type Get-Package at the prompt. The first line with be for EntityFramework and list the version the project has installed.
PM> Get-Package
Id Version Description/Release Notes
-- ------- -------------------------
EntityFramework 5.0.0 Entity Framework is Microsoft's recommended data access technology for new applications.
jQuery 1.7.1.1 jQuery is a new kind of JavaScript Library.... `enter code here`
It displays much more and you may have to scroll back up to find the EF line, but this is the easiest way I know of to find out.
You cannot directly create a table stored as a sequence file and insert text into it. You must do this:
Example:
CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;
CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;
DROP TABLE test_txt;
In case anyone else ends up here using Jupyter Notebooks, you just need
%matplotlib inline
Make sure git-upload-pack
is on the path from a non-login shell. (On my machine it's in /usr/bin
).
To see what your path looks like on the remote machine from a non-login shell, try this:
ssh you@remotemachine echo \$PATH
(That works in Bash, Zsh, and tcsh, and probably other shells too.)
If the path it gives back doesn't include the directory that has git-upload-pack
, you need to fix it by setting it in .bashrc
(for Bash), .zshenv
(for Zsh), .cshrc
(for tcsh) or equivalent for your shell.
You will need to make this change on the remote machine.
If you're not sure which path you need to add to your remote PATH
, you can find it with this command (you need to run this on the remote machine):
which git-upload-pack
On my machine that prints /usr/bin/git-upload-pack
. So in this case, /usr/bin
is the path you need to make sure is in your remote non-login shell PATH
.
If you hate numpy, get out RPy and your local copy of R, and use it instead.
(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)
You can scale up the fonts in your call to sns.set()
.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))
sns.set(font_scale=5) # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))
If you're looking for a particular string, put quotes around it:
awk '$1 == "findtext" {print $3}'
Otherwise, awk will assume it's a variable name.
$this->db->where('(a = 1 or a = 2)');
Either run in SQL:
ALTER TABLE tableName
ADD PRIMARY KEY (id) ---or Drugid, whichever you want it to be PK
or use the PHPMyAdmin interface (Table Structure)
There are two cases:
const reference --good idea, sometimes, especially for heavy objects or proxy classes, compiler optimization
non-const reference --bad idea, sometimes, breaks encapsulations
Both share same issue -- can potentially point to destroyed object...
I would recommend using smart pointers for many situations where you require to return a reference/pointer.
Also, note the following:
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
yum list installed | grep mysql
Then if it's not installed you can do (as root)
yum install mysql -y
From the Android documentation:
The
CookieSyncManager
is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.To use the
CookieSyncManager
, the host application has to call the following when the application starts:CookieSyncManager.createInstance(context)
To set up for sync, the host application has to call
CookieSyncManager.getInstance().startSync()
in Activity.onResume(), and call
CookieSyncManager.getInstance().stopSync()
in Activity.onPause().
To get instant sync instead of waiting for the timer to trigger, the host can call
CookieSyncManager.getInstance().sync()
The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.
Finally something like this should work:
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
webview.loadUrl([MY URL]);
Start GDB on your project.
Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:
gdb projectExecutablename
This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)
Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:
(gdb) b main
Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:
(gdb) r mulder/xfiles
Hope this helps.
Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.
I met the same problem as you.
I push two tables
result
into t1
object and group t1
.
from p in Products
join bp in BaseProducts on p.BaseProductId equals bp.Id
select new {
p,
bp
} into t1
group t1 by t1.p.SomeId into g
select new ProductPriceMinMax {
SomeId = g.FirstOrDefault().p.SomeId,
CountryCode = g.FirstOrDefault().p.CountryCode,
MinPrice = g.Min(m => m.bp.Price),
MaxPrice = g.Max(m => m.bp.Price),
BaseProductName = g.FirstOrDefault().bp.Name
};
What I understand from your words is that you want to create a link just to run JavaScript code.
Then you should consider that there are people who blocks JavaScript out there in their browsers.
So if you are really going to use that link only for running a JavaScript function then you should add it dynamically so it won't be even seen if the users didn't enable their JavaScript in the browser and you are using that link just to trigger a JavaScript function which makes no sense to use a link like that when JavaScript is disabled in the browser.
For that reason neither of them is good when JavaScript is disabled.
Aand if JavaScript is enabled and you only want to use that link to invoke a JavaScript function then
<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>
is far better way than using
<a href="#" onclick="myJsFunc();">Link</a>
because href="#" is going to cause the page to do actions that are not needed.
Also, another reason why <a href="javascript:void(0)" onclick="myJsFunc();">Link</a>
is better than <a href="#" onclick="myJsFunc();">Link</a>
is that JavaScript is used as the default scripting language for most of the browsers. As an example Internet Explorer, uses an onclick attribute to define the type of scripting language that would be used. Unless another good scripting language pops up, JavaScript will be used by Internet Explorer as the default too, but if another scripting language used javascript:
, it would let Internet Explorer to understand which scripting language is being used.
Considering this, I would prefer using and exercising on
<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>
enough to make it a habit and to be more user friendly please add that kind of links within the JavaScript code:
$(document).ready(function(){
$(".blabla").append('<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>')
});
PHPEclipse is as close to Eclipse java power as it could get. Eclipse PDT is much weaker (last time I checked).
If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.
I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.
It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.
If you're using Amazon EC2, and you're having this problem on the instance, then you only need to do:
sudo yum install mysql-server
sudo service mysqld restart
Amazon EC2 doesn't have a server installed (only the client is installed), so in case of that you need to install that on your instance, and after that try
mysql -u root -p
to check if that worked.
There are five ways to output text to the console:
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.
WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.
StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.
Be aware that it only updates the first company it found with company id 1. For multiple
(from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";
For Multiple updates
from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name"; return c;}
This just works on React & React Native
const data = require('./data/photos.json');
console.log('[-- typeof data --]', typeof data); // object
const fotos = data.xs.map(item => {
return { uri: item };
});
This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl
our $foo = "BAR";
print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";
Output:
BAR
BAZ
This won't work if you change 'our' to 'my'.
Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).
# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)
cursor = conn.cursor()
# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
print('Table exists. I can do my custom stuff here now.... ')
pass
else:
# then table doesn't exist.
custRET = myCustFunc(foo,bar) # replace this with your custom logic
data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:
http://ejohn.org/blog/html-5-data-attributes/
You can create a data attribute by prefixing data-
to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id
or in this case data-reactid
Should declare logger like this:
private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());
so if you refactor your class name it follows.
I wrote an article about java logger with examples here.
Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API
//Define a constant so that the API KEY can be used globally across the application
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
function youtube_video_statistics($video_id) {
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return $views;
}
//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.
If you not in a loop, you can use ng-init else you can use
{{var=foo;""}}
the "" alows not display your var
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
*{font-family:Algerian;}
better solution below Applying a single font to an entire website with CSS
This error can also occur when you try to connect to http while the server is on https.
It was a bit confusing because my get-requests were OK, the problem was only present with post-requests.
The top answer is terse but it doesn't handle all edge cases. For anyone needing a more robust utility, without any external dependencies:
function camelCase(str) {
return (str.slice(0, 1).toLowerCase() + str.slice(1))
.replace(/([-_ ]){1,}/g, ' ')
.split(/[-_ ]/)
.reduce((cur, acc) => {
return cur + acc[0].toUpperCase() + acc.substring(1);
});
}
function sepCase(str, sep = '-') {
return str
.replace(/[A-Z]/g, (letter, index) => {
const lcLet = letter.toLowerCase();
return index ? sep + lcLet : lcLet;
})
.replace(/([-_ ]){1,}/g, sep)
}
// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))
// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));
// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));
Demo here: https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
Yes the second syntax is fine.
Have you tried using the SPF wizard? https://www.spfwizard.net/
It can quickly generate basic and complex SPF records.
I'm using VB 2010 .NET 4.0 and use the following:
Private Sub tbSecurity_KeyPress(sender As System.Object, e As System.EventArgs) Handles tbSecurity.KeyPress
Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
If tmp.KeyChar = ChrW(Keys.Enter) Then
MessageBox.Show("Enter key")
Else
MessageBox.Show(tmp.KeyChar)
End If
End Sub
Works like a charm!
I solved this by doing the following:
<body class="container-fluid">
<div class="row">
<div class="span6" style="float: none; margin: 0 auto;">
....
</div>
</div>
</body>
If instead of flag = True
we can do an import instead, then I think this meets the criteria:
>>> from itertools import count
>>> a = ['hello', '', 'world', '', '', '', 'bob']
>>> filter(lambda L, j=count(): L or not next(j), a)
['hello', '', 'world', 'bob']
Or maybe the filter is better written as:
>>> filter(lambda L, blank_count=count(1): L or next(blank_count) == 1, a)
Or, just for a simple boolean, without any imports:
filter(lambda L, use_blank=iter([True]): L or next(use_blank, False), a)
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
The question is a bit old, but let me add a different approach. In addition to the above hot-key approaches, there are default preference settings that can be toggled.
As of Eclipse Galileo (and definitely in my Eclipse Version: Indigo Service Release 2 Build id: 20120216-1857) language specific preferences can open up new files to edit which are already collapsed or expanded.
Here is a link to Eclipse Galileo online docs showing the feature for C/C++: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_c_editor_folding.htm .
In my Eclipse Indigo I can open the Folding Preferences window via : menu/ Window/ Preferences/ Java/ Editor/ Folding
and set all options on so I can open files by default that are completely collapsed.
One remark about "just use the subset of C++ you want to use": the problem with this idea is that it has a cost to enforce that everybody in the project uses the same subset. My own opinion is that those costs are quite high for loosely coupled projects (e.g. open source ones), and also that C++ totally failed at being a better C, in the sense that you cannot use C++ wherever you used C.
You need to transform your data to long format and shouldn't use $
inside aes
:
DF <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
library(reshape2)
DF1 <- melt(DF, id.var="Rank")
library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
You are triggering the event before the event is even bound.
Just move the triggering
of the event to after attaching the event.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
I needed to adjust the width of some tooltips. But not an overall setting. So I ended up doing this:
CSS
.large-tooltip .tooltip-inner {
max-width: 300px;
}
@media screen and (max-width: 300px) {
.large-tooltip .tooltip-inner {
max-width: 100%;
}
}
JQuery
$('[data-toggle="tooltip"]')
.tooltip()
.on('shown.bs.tooltip', function(e) {
/**
* If the item that triggered the event has class 'large-tooltip'
* then also add it to the currently open tooltip
*/
if ($(this).hasClass('large-tooltip')) {
$('body').find('.tooltip[role="tooltip"].show').addClass('large-tooltip');
}
});
Html
<img src="/theimage.jpg" class="large-tooltip" data-toggle="tooltip" data-html="true" title="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." />
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
The thing here is that you're using a for loop outside of your conditional statement.
After the conditions in your IF statement are met you probably navigate to another page, thus when the for loop attempts to iterate once more, you get the stale element error because you're on a different page.
You can add a break at the end of your if statement, this worked for me.
sp_addlinkedserver('servername')
so its should go like this -
select * from table1
unionall
select * from [server1].[database].[dbo].[table1]
A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".
The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.
Example (of unchecked warning in conjunction with raw types):
TreeSet set = new TreeSet();
set.add("abc"); // unchecked warning
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet
set.add("abc");
^
When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.
"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.
Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):
class Wrapper<T> {
private T wrapped ;
public Wrapper (T arg) {wrapped = arg;}
...
public Wrapper <T> clone() {
Wrapper<T> clon = null;
try {
clon = (Wrapper<T>) super.clone(); // unchecked warning
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
try {
Class<?> clzz = this.wrapped.getClass();
Method meth = clzz.getMethod("clone", new Class[0]);
Object dupl = meth.invoke(this.wrapped, new Object[0]);
clon.wrapped = (T) dupl; // unchecked warning
} catch (Exception e) {}
return clon;
}
}
warning: [unchecked] unchecked cast
found : java.lang.Object
required: Wrapper <T>
clon = ( Wrapper <T>)super.clone();
^
warning: [unchecked] unchecked cast
found : java.lang.Object
required: T
clon. wrapped = (T)dupl;
A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.
In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.
In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.
Please refer: What is an "unchecked" warning?
test[,sort(names(test))]
sort on names of columns can work easily.
I got a similar problem with sql server , I have tried every thing but does not connect to database engine & it shows error:26.
IF the database engine is not running, simply uninstall sql
server / format your system if possible and then download sql
server 2012 and management studio. from
https://www.microsoft.com/en-ca/download/details.aspx?id=29062
Install server first, make sure to add server on installation phase
by clicking add server and then install management studio.
Use typings to access node functions from TypeScript:
typings install env~node --global
If you don't have typings install it:
npm install typings --global
$(document).ready(function() {_x000D_
var ckbox = $("input[name='ips']");_x000D_
var chkId = '';_x000D_
$('input').on('click', function() {_x000D_
_x000D_
if (ckbox.is(':checked')) {_x000D_
$("input[name='ips']:checked").each ( function() {_x000D_
chkId = $(this).val() + ",";_x000D_
chkId = chkId.slice(0, -1);_x000D_
});_x000D_
_x000D_
alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
alert(chkId); // return value of checkbox checked_x000D_
} _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
The limit is not 2g or 3gb its 4gb for 32bit.
The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.
Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.
4Gig not 3 not 2 got it?
Might be a late response but here is a way to do it in one line without using any libraries:
new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(YOUR_TIMESTAMP))
Start From the material design update, it support app:strokeColor
and also app:strokeWidth
. see more
to use material design update. add following code to build.gradle
(:app)
dependencies {
// ...
implementation 'com.google.android.material:material:1.0.0'
// ...
}
and Change CardView
to MaterialCardView
tried all proposed solutions, all seem to have issues of their own.
If you actually look into the Orchestrator source, particularly the .start()
implementation you will see that if the last parameter is a function it will treat it as a callback.
I wrote this snippet for my own tasks:
gulp.task( 'task1', () => console.log(a) )
gulp.task( 'task2', () => console.log(a) )
gulp.task( 'task3', () => console.log(a) )
gulp.task( 'task4', () => console.log(a) )
gulp.task( 'task5', () => console.log(a) )
function runSequential( tasks ) {
if( !tasks || tasks.length <= 0 ) return;
const task = tasks[0];
gulp.start( task, () => {
console.log( `${task} finished` );
runSequential( tasks.slice(1) );
} );
}
gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));
<%= Html.Partial("PartialName", Model) %>
An official list of mime types can be found at The Internet Assigned Numbers Authority (IANA) . According to their list Content-Type
header for zip
is application/zip
.
The media type for rar
files is not officially registered at IANA but the unofficial commonly used mime-type value is application/x-rar-compressed
.
application/octet-stream
means as much as: "I send you a file stream and the content of this stream is not specified" (so it is true that it can be a zip
or rar
file as well). The server is supposed to detect what the actual content of the stream is.
Note: For upload it is not safe to rely on the mime type set in the Content-Type
header. The header is set on the client and can be set to any random value. Instead you can use the php file info functions to detect the file mime-type on the server.
If you want to download a zip
file and nothing else you should only set one single Accept
header value. Any additional values set will be used as a fallback in case the server cannot satisfy your in the Accept
header requested mime-type.
According to the WC3 specifications this:
application/zip, application/octet-stream
will be intrepreted as: "I prefer a application/zip
mime-type, but if you cannot deliver this an application/octet-stream
(a file stream) is also fine".
So only a single:
application/zip
Will guarantee you a zip
file (or a 406 - Not Acceptable
response in case the server is unable to satisfy your request).
According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*)
.
PY_SSIZE_T_MAX
is defined in pyport.h to be ((size_t) -1)>>1
On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.
Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.
As long as the number of elements you have is equal or below this, all list functions should operate correctly.
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');
Also note that if the src
of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.
@Matteo Gobbi's answer is perfect, but in my case, the scrollview can't scroll, i remove "align center Y" and add "height >=1", the scrollview will became scrollable
you can use ps
.
e.g. having python process with two busy threads on dual core CPU:
$ ps -p 29492 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
29492 29492 1 0.0
29492 29493 1 48.7
29492 29494 1 51.9
(PSR is CPU id the thread is currently assigned to)
you see that the threads are running on the same cpu core (because of GIL)
running the same python script in jython, we see, that the script is utilizing both cores (and there are many other service or whatever threads, which are almost idle):
$ ps -p 28671 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
28671 28671 1 0.0
28671 28672 0 4.4
28671 28673 0 0.6
28671 28674 0 0.5
28671 28675 0 2.3
28671 28676 0 0.0
28671 28677 1 0.0
28671 28678 1 0.0
28671 28679 0 4.6
28671 28680 0 4.4
28671 28681 1 0.0
28671 28682 1 0.0
28671 28721 1 0.0
28671 28729 0 88.6
28671 28730 1 88.5
you can process the output and calculate the total CPU for each CPU core.
Unfortunately, this approach does not seem to be 100% reliable, sometimes i see that in the first case, the two working threads are reported to be separated to each CPU core, or in the latter case, the two threads are reported to be on the same core..
For Windows Server 2016
Server Manager
formManage
-> Add Roles and Features
Features
pageWCF Services
feature with all subfeaturesNext
and Install
The accepted answer using button.tag
as information carrier which button has actually been pressed is solid and widely accepted but rather limited since a tag can only hold Int
s.
You can make use of Swift's awesome closure-capabilities to have greater flexibility and cleaner code.
I recommend this article: How to properly do buttons in table view cells using Swift closures by Jure Zove.
Applied to your problem:
Declare a variable that can hold a closure in your tableview cell like
var buttonTappedAction : ((UITableViewCell) -> Void)?
Add an action when the button is pressed that only executes the closure. You did it programmatically with cell.yes.targetForAction("connected", withSender: self)
but I would prefer an @IBAction
outlet :-)
@IBAction func buttonTap(sender: AnyObject) {
tapAction?(self)
}
func connected(sender: UIButton!) { ... }
as a closure to cell.tapAction = {<closure content here...>}
. Please refer to the article for a more precise explanation and please don't forget to break reference cycles when capturing variables from the environment.I came up with another implementation documented at, http://blog.sangupta.com/2010/05/encodeuricomponent-and.html. The implementation can also handle Unicode bytes.
Here is the Link for similar answers : http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:
template <class X>
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x
X& operator *( );
const X& operator*( ) const;
X* operator->() const;
smart_pointer(const smart_pointer <X> &);
const smart_pointer <X> & operator =(const smart_pointer<X>&);
~smart_pointer();
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
smart_pointer <employee> p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p;
p->raise_salary(0.5);
In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use logging.Logger.manager.loggerDict
to get a dictionary of all of the logger objects. The returned names can then be used as the argument to logging.getLogger
:
import requests
import logging
for key in logging.Logger.manager.loggerDict:
print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# PYREADLINE
# requests
# requests.packages.urllib3.poolmanager
logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)
Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
I'm sticking with DbVisualizer Free until something better comes along.
EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
hg status will show you all the new files, and then you can just rm them.
Normally I want to get rid of ignored and unversioned files, so:
hg status -iu # to show
hg status -iun0 | xargs -r0 rm # to destroy
And then follow that with:
hg update -C -r xxxxx
which puts all the versioned files in the right state for revision xxxx
To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.
The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.
You can di this:
#axs[1].plot(clust_data[:,0],clust_data[:,1]) # Remove this if you don't need it
axs[1].axis("off") # This will leave the table alone in the window
"Copy on write" means more or less what it sounds like: everyone has a single shared copy of the same data until it's written, and then a copy is made. Usually, copy-on-write is used to resolve concurrency sorts of problems. In ZFS, for example, data blocks on disk are allocated copy-on-write; as long as there are no changes, you keep the original blocks; a change changed only the affected blocks. This means the minimum number of new blocks are allocated.
These changes are also usually implemented to be transactional, ie, they have the ACID properties. This eliminates some concurrency issues, because then you're guaranteed that all updates are atomic.
Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.
Your Arduino library folder should look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
My Documents\Arduino\libraries\ArduinoParty\examples
....
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
Documents/Arduino/libraries/ArduinoParty/examples
The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.
If you use this, check man sudo
too:
#!/bin/bash
sudo echo "Hi, I'm root"
sudo -u nobody echo "I'm nobody"
sudo -u 1000 touch /test_user
The t
indicates text mode, meaning that \n
characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.
Other than U
, those mode flags come directly from the standard C library's fopen()
function, a fact that is documented in the sixth paragraph of the python2 documentation for open()
.
As far as I know, t
is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
var regex = /\d+/g;_x000D_
var string = "you can enter maximum 500 choices";_x000D_
var matches = string.match(regex); // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
References:
http://www.regular-expressions.info/javascript.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
This should work:
System.currentTimeMillis();
There are a lot of answers here. And it's old, but this is for anyone coming here via google. In jQuery each function
return false;
is like break
.
just
return;
is like continue
These will emulate the behavior of break and continue.
If customer primary contact medium is email, if email is null then phonenumber, and if phonenumber is also null then address. It would be written using COALESCE as
coalesce(email,phonenumber,address)
while the same in hive can be achieved by chaining together nvl as
nvl(email,nvl(phonenumber,nvl(address,'n/a')))
This function works for MM:SS as well:
const convertTime = (hms) => {_x000D_
if (hms.length <3){_x000D_
return hms_x000D_
} else if (hms.length <6){_x000D_
const a = hms.split(':')_x000D_
return hms = (+a[0]) * 60 + (+a[1])_x000D_
} else {_x000D_
const a = hms.split(':')_x000D_
return hms = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])_x000D_
}_x000D_
}
_x000D_
One possible solution:
import java.lang.StringBuilder;
class Test {
private static final int sizeOfIntInHalfBytes = 8;
private static final int numberOfBitsInAHalfByte = 4;
private static final int halfByte = 0x0F;
private static final char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
public static String decToHex(int dec) {
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
{
int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
return hexBuilder.toString();
}
public static void main(String[] args) {
int dec = 305445566;
String hex = decToHex(dec);
System.out.println(hex);
}
}
Output:
1234BABE
Anyway, there is a library method for this:
String hex = Integer.toHexString(dec);
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
I recommend GPick:
sudo apt-get install gpick
Applications -> Graphics -> GPick
It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.
If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.
It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.
The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:
Note that firewalls and port or IP blocking may be in place by your ISP
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket is not correct and will not give a good impression on the interviewer .
If key is null , then Null keys always map to hash 0, thus index 0.
If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks like
int hash = hash(hashValue)
and now ,it applies returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.
Now final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex)
Option 1: Use a nullable DateTime?
Option 2: Use DateTime.MinValue
Personally, I'd prefer option 1.
change does only work on input form elements.
you could just trigger a function after your XML / XSL transformation or make a listener:
var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
For people using swift [2.2] on Linux i.e. Ubuntu, the import is different!
The correct way to do this is to use Glibc. This is because on OS X and iOS, the basic Unix-like API's are in Darwin but in linux, these are located in Glibc. Importing Foundation won't help you here because it doesn't make the distinction by itself. To do this, you have to explicitly import it yourself:
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
You can follow the development of the Foundation framework here to learn more
As pointed out by @Cœur, starting from swift 3.0 some math functions are now part of the types themselves. For example, Double now has a squareRoot function. Similarly, ceil
, floor
, round
, can all be achieved with Double.rounded(FloatingPointRoundingRule) -> Double
.
Furthermore, I just downloaded and installed the latest stable version of swift on Ubuntu 18.04, and it looks like Foundation
framework is all you need to import to have access to the math functions now. I tried finding documentation for this, but nothing came up.
? swift
Welcome to Swift version 4.2.1 (swift-4.2.1-RELEASE). Type :help for assistance.
1> sqrt(9)
error: repl.swift:1:1: error: use of unresolved identifier 'sqrt'
sqrt(9)
^~~~
1> import Foundation
2> sqrt(9)
$R0: Double = 3
3> floor(9.3)
$R1: Double = 9
4> ceil(9.3)
$R2: Double = 10
Of course you can use the StringTokenizer
class to split the String with '.' or '/', and check if the last word is "work".
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact
userForm: FormGroup;
public contactList: FormArray;
// returns all form groups under contacts
get contactFormGroup() {
return this.userForm.get('funds') as FormArray;
}
ngOnInit() {
this.submitUser();
}
constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
// contact formgroup
createContact(): FormGroup {
return this.fb.group({
fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
allocation: [null, Validators.compose([Validators.required])]
});
}
// triggered to change validation of value field type
changedFieldType(index) {
let validators = null;
validators = Validators.compose([
Validators.required,
Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
]);
this.getContactsFormGroup(index).controls['allocation'].setValidators(
validators
);
this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
}
// get the formgroup under contacts form array
getContactsFormGroup(index): FormGroup {
// this.contactList = this.form.get('contacts') as FormArray;
const formGroup = this.contactList.controls[index] as FormGroup;
return formGroup;
}
submitUser() {
this.userForm = this.fb.group({
first_name: ['', [Validators.required]],
last_name: [''],
email: ['', [Validators.required]],
company_name: ['', [Validators.required]],
license_start_date: ['', [Validators.required]],
license_end_date: ['', [Validators.required]],
gender: ['Male'],
funds: this.fb.array([this.createContact()])
})
this.contactList = this.userForm.get('funds') as FormArray;
}
addContact() {
this.contactList.push(this.createContact());
}
removeContact(index) {
this.contactList.removeAt(index);
}
You need to use the public properties from Main
, and not try to directly change the internal variables.
On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.
function user() {
parent::Model();
}
=> class name is User, construct name is User.
function User() {
parent::Model();
}
The problem I found was even sillier than what other folks have mentioned.
Our makefiles get passed lists of things to build. Someone added TheOtherLibrary
to one of the lists, as shown below.
LIBRARYDIRS = src/Library
LIBRARYDIRS = src/TheOtherLibrary
They should have done this:
LIBRARYDIRS = src/Library
LIBRARYDIRS += src/TheOtherLibrary
Had they done it the second way, they would not have wiped out the Library
build. The plus in +=
is very important.
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater
gives the opposite ordering to the default less
, meaning that the queue will give you the lowest value rather than the highest.
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
Something like this:
setUsers = function (data) {
for (k in data) {
user[k] = data[k];
}
}
Make sure the JSON output is in a <pre>
tag.
pow() doesn't work with int
, hence the error "error C2668:'pow': ambiguous call to overloaded function"
http://www.cplusplus.com/reference/clibrary/cmath/pow/
Write your own power function for int
s:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
I really needed this in C# and found Center MessageBox C#
Here's a nicely formatted version
using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
public class MessageBoxEx
{
private static IWin32Window _owner;
private static HookProc _hookProc;
private static IntPtr _hHook;
public static DialogResult Show(string text)
{
Initialize();
return MessageBox.Show(text);
}
public static DialogResult Show(string text, string caption)
{
Initialize();
return MessageBox.Show(text, caption);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
{
Initialize();
return MessageBox.Show(text, caption, buttons);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton, options);
}
public static DialogResult Show(IWin32Window owner, string text)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text);
}
public static DialogResult Show(IWin32Window owner, string text, string caption)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton, options);
}
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
public const int WH_CALLWNDPROCRET = 12;
public enum CbtHookAction : int
{
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
} ;
static MessageBoxEx()
{
_hookProc = new HookProc(MessageBoxHookProc);
_hHook = IntPtr.Zero;
}
private static void Initialize()
{
if (_hHook != IntPtr.Zero)
{
throw new NotSupportedException("multiple calls are not supported");
}
if (_owner != null)
{
_hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(_hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = _hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(_hHook);
_hHook = IntPtr.Zero;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(_owner.Handle, ref recParent);
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
From the documentation page for the random module:
Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.
random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.
>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'
Instead of string.digits
, range
could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.
Solution 1 : You can do like this :
List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();
But in some cases may this solution not work. if it is not work you can use my second solution .
Solution 2 :
List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
we pretend that list1 is your main list and list2 is your secondry list and you want to get items of list1 without items of list2.
var result = list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();
Windows environment, local machine. I had an error
[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException:
Error connecting to 127.0.0.1:27017 :: caused by ::
No connection could be made because the target machine actively refused it. :
After some back and forth attempts I decided
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestPOC</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
this is a java version for permutation
public class Permutation {
static void permute(String str) {
permute(str.toCharArray(), 0, str.length());
}
static void permute(char [] str, int low, int high) {
if (low == high) {
System.out.println(str);
return;
}
for (int i=low; i<high; i++) {
swap(str, i, low);
permute(str, low+1, high);
swap(str, low, i);
}
}
static void swap(char [] array, int i, int j) {
char t = array[i];
array[i] = array[j];
array[j] = t;
}
}
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
Both are correct. Oracle allows the use of both.
I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.
$(".currencyMask").change(function () {
if (!$.isNumeric($(this).val()))
$(this).val('0').trigger('change');
$(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
});
Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" />
and it will format it perfectly in any browser.
If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.
Example with pure javascript:
<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var name = document.getElementById('name').value;
var location = document.getElementById('location').value;
var queryString = "?name=" + name + "&location=" + location;
ajaxRequest.open("POST", "some.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
You can have one file with functions called for example functions.php
functions.php
<?php
myFunction($Name, $Location) {
// etc...
}
myFunction2() {
}
// ... many functions
?>
some.php
<?php include("functions.php");
$Name = $_POST['name'];
$Location = $_POST['location'];
myFunction($Name, $Location);
// make what you want with these variables...?>
https://developer.mozilla.org/en/CSS/vertical-align
<table style="height: 275px; width: 188px">
<tr>
<td style="width: 259px; vertical-align:top">
main page
</td>
</tr>
</table>
?
I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.
If you use Moment, your code would be as simple as this:
var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to
// the next month at this point, because `add` mutates in-place
You can find MomentJS here: http://momentjs.com/
UPDATE:
In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.
If you're using SQL Server it would be something like this:
DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90
Well you can achieve this using Color State Resource. If you notice inside your NavigationView
you're using
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
Here instead of using @color/black
or @color/primary_test
, use a Color State List Resource
. For that, first create a new xml
(e.g drawer_item.xml) inside color
directory (which should be inside res
directory.) If you don't have a directory named color
already, create one.
Now inside drawer_item.xml
do something like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked state color" android:state_checked="true" />
<item android:color="your default color" />
</selector>
Final step would be to change your NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/drawer_item" // notice here
app:itemTextColor="@color/drawer_item" // and here
app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
app:menu="@menu/menu_drawer">
Like this you can use separate Color State List Resources for IconTint
, ItemTextColor
, ItemBackground
.
Now when you set an item as checked (either in xml
or programmatically), the particular item will have different color than the unchecked ones.
You have it right. The stack pointer points to the top item on the stack and the base pointer points to the "previous" top of the stack before the function was called.
When you call a function, any local variable will be stored on the stack and the stack pointer will be incremented. When you return from the function, all the local variables on the stack go out of scope. You do this by setting the stack pointer back to the base pointer (which was the "previous" top before the function call).
Doing memory allocation this way is very, very fast and efficient.
For posterity, I have a few NullBooleanField
s and here's what I do:
To check if it's True
:
{% if variable %}True{% endif %}
To check if it's False
(note this works because there's only 3 values -- True/False/None):
{% if variable != None %}False{% endif %}
To check if it's None
:
{% if variable == None %}None{% endif %}
I'm not sure why, but I can't do variable == False
, but I can do variable == None
.
Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:
serve("ws").with(MyWSServlet.class,
new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});
Anything <0 is infinite idle time I believe.
If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.
path = 'C:\\Users\\Username\\Path\\To\\File'
with open(path, 'w') as f:
f.write(data)
Edit:
Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.
import os
cur_path = os.path.dirname(__file__)
new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
f.write(data)
Edit 2: One quick note about __file__
, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.
Installation of Maven doesn't create the settings.xml
file. You have to create it on your own. Just put it in your .m2
directory where you expected it, see http://maven.apache.org/settings.html for reference. The m2eclipse plugin will use the same settings file as the command line.
You are after implicit make rules.
Another simple way :)
public IQueryable<Product> GetProducts(int categoryID)
{
var productList = db.Products
.Where(p => p.CategoryID == categoryID)
.Select(item =>
new Product
{
Name = item.Name
})
.ToList()
.AsQueryable(); // actually it's not useful after "ToList()" :D
return productList;
}
You have to first convert it into datetime, then to date.
Try this, it might be helpful:
Select Convert(DATETIME, LEFT(20130101, 8))
then convert to date.
You have to add another list:
list[:0]=['foo']
You can also add items in code:
cboWhatever.Items.Add("SomeItem");
Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:
Key Value Pair Combobox in WPF
Sum-up code would be something like this:
ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
Try:
select concat(first_name,last_name) as "Name" from test.student
or, better:
select concat(first_name," ",last_name) as "Name" from test.student
If you just want to output the first 5 elements, you should write something like:
<?php
if (!empty ( $an_array ) ) {
$min = min ( count ( $an_array ), 5 );
$i = 0;
foreach ($value in $an_array) {
echo $value;
$i++;
if ($i == $min) break;
}
}
?>
If you want to write a function which returns part of the array, you should use array_slice:
<?php
function GetElements( $an_array, $elements ) {
return array_slice( $an_array, 0, $elements );
}
?>
http://localhost:80
type above line in your browser you realize IIS installed or not
You can't cause a .Net application to elevate its own rights. It's simply not allowed. The best you can do is to specify elevated rights when you spawn another process. In this case you would have a two-stage application launch.
Stage 1 does nothing but prepare an elevated spawn using the System.Diagnostics.ProcessStartInfo object and the Start() call.
Stage 2 is the application running in an elevated state.
As mentioned above, though, you very rarely want to do this. And you certainly don't want to do it just so you can write temporary files into %programfiles%. Use this method only when you need to perform administrative actions like service start/stop, etc. Write your temporary files into a better place, as indicated in other answers here.
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617
The approach with:
<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>
and with
<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>
Only works if the person who clicked on your link have your number on their contact list.
Since not everybody will have it, the other solution is to use Whatsapp API like this:
<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>
More details on this API here: https://www.whatsapp.com/faq/en/general/26000030
And observations on how to use it here: https://stackoverflow.com/a/43357241/3958617
def invertDictionary(d):
myDict = {}
for i in d:
value = d.get(i)
myDict.setdefault(value,[]).append(i)
return myDict
print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})
This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}
For giggles, here's solution in fish-shell:
for i in *.avi; ffmpeg -i "$i" (string split -r -m1 . $i)[1]".mp4"; end
well I wouldn't have expected it, but Halim's SELECT distinct TOP 10 MyId FROM sometable
is functionally identical to Vaishnavi Kumar's select top 10 p.id from(select distinct p.id from tablename)tablename
create table #names ([name] varchar(10))
insert into #names ([name]) values ('jim')
insert into #names ([name]) values ('jim')
insert into #names ([name]) values ('bob')
insert into #names ([name]) values ('mary')
insert into #names ([name]) values ('bob')
insert into #names ([name]) values ('mary')
insert into #names ([name]) values ('john')
insert into #names ([name]) values ('mark')
insert into #names ([name]) values ('matthew')
insert into #names ([name]) values ('luke')
insert into #names ([name]) values ('peter')
select distinct top 5 [name] from #names
select top 5 * from (select distinct [name] from #names) subquery
drop table #names
produces the same results for both selects:
name
1 bob
2 jim
3 john
4 luke
5 mark
it's curious that select top 5 distinct is not valid, but select distinct top 5 is and works as you might expect select top 5 distinct to work.
Refering to Andrie's answer, suggesting to use plyr::rbind.fill()
:
Combined with t()
you have something like cbind.fill()
(which is not part of plyr
) that will construct your data frame with consideration of identical case numbers.
# Problem: Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
Here's one way to set c3
that doesn't involve sets:
c3 = []
for sublist in c2:
c3.append([val for val in c1 if val in sublist])
But if you prefer to use just one line, you can do this:
c3 = [[val for val in c1 if val in sublist] for sublist in c2]
It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.
Have you tried adding a configsection
handler to your app.config? e.g.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
If your menu height is variable (for responsiveness or because it's loaded dynamically), you can set the top margin to where the fixed div ends. For example:
CSS
.fixed-header {
width: 100%;
margin: 0 auto;
position: fixed;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
z-index: 999;
}
Javascript
$(document).ready(function() {
var contentPlacement = $('#header').position().top + $('#header').height();
$('#content').css('margin-top',contentPlacement);
});
HTML
...
<div id="header" class="fixed-header"></div>
<div id="content">...</div>
...
Here's a fiddle (https://jsfiddle.net/632k9xkv/5/) that goes a little beyond this with both a fixed nav menu and header in an attempt to hopefully make this a useful sample.
I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:
while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
I needed to add an additional Maven dependency:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
Check box-sizing
css property of your td
elements. I had problem with css template which sets it to border-box
value. You need set box-sizing: content-box
.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.
String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());
System.out.println(file.getAbsolutePath());
Note : Here the sample.txt file should be placed under src/test/resources folder.
For more details refer options_to_load_test_resources
You can go without the loop:
find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \;
HTH
Roger's answer was very helpful.
I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with
certutil -addstore Root Demo_CA.cer
which Roger's answer didn't quite cover.
Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).
REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.
PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64
makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature ^
-sv Demo_CA.pvk Demo_CA.cer
makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
-sky signature ^
-ic Demo_CA.cer -iv Demo_CA.pvk ^
-sv Demo_SPC.pvk Demo_SPC.cer
pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
-pfx Demo_SPC.pfx ^
-po x
inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v
signtool sign /d "description" /du "www.yoyodyne.com" ^
/f Demo_SPC.pfx ^
/p x ^
/v driver\demoprinter.cat
certutil -addstore Root Demo_CA.cer
rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
certutil -delstore Root Demo_CA
I've just tested, and this works for me using Chrome Version 28.0.1500.95.
I was needing to download a file and read the file name. The file name is in the header so I did the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
success(xhr.response); // the function to proccess the response
console.log("++++++ reading headers ++++++++");
var headers = xhr.getAllResponseHeaders();
console.log(headers);
console.log("++++++ reading headers end ++++++++");
}
};
Output:
Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream
Even easier...
ASP.NET
<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...
CSS
.FormatRadioButtonList label
{
margin-right: 15px;
}
Put this bean in your configuration class.
@Bean
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
and then You can use
<T> BindingResult validate(T t) {
DataBinder binder = new DataBinder(t);
binder.setValidator(validator);
binder.validate();
return binder.getBindingResult();
}
for validating a bean manually. Then You will get all result in BindingResult and you can retrieve from there.
I struggled with this error for weeks (using RStudio). I tried moving the plot window bigger and smaller, but that did not consistently help. When I moved (dragged) the application to my bigger monitor, the problem disappeared! I was stunned... so many wasted hours... I knew my code was correct...
it seems that the OP meant to find out whether the string 'Mel' exists in a particular column, not contained in a column, therefore the use of contains is not needed, and is not efficient. A simple equals-to is enough:
(a['Names']=='Mel').any()
Just use the command: runas /noprofile /user:administrator cmd
in order to know the phone resolution simply create a image with label mdpi, hdpi, xhdpi and xxhdpi. put these images in respective folder like mdpi, hdpi, xhdpi and xxhdpi. create a image view in layout and load this image. the phone will load the respective image from a specific folder. by this you will get the phone resolution or *dpi it is using.
To list only the containers SHA1:
docker ps -aq --no-trunc
That way, you can use the list of all containers for other commands (which accept multiple container ids as parameters).
For example, to list only the name of all containers (since docker ps
list only their names with other information):
docker inspect --format='{{.Name}}' $(sudo docker ps -aq --no-trunc)
I found the answer!
I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).
The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS
#ActionBox {
position: relative;
float: right;
}
Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)
I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.
var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");
INPUT = "https://stackoverflow.com/questions/";
OUTPUT = "https://stackoverflow.com/";
Interesting blog post here:
http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
It mentions subscribing to Dispatcher.ShutdownStarted to dispose of your resources.
I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>
Then add this to your HTML tag:
xmlns:fb="http://ogp.me/ns/fb#"
"blue_box"
is null -- are you positive whatever it is with "id='blue'"
exists when this is being run?
try console.log(document.getElementById("blue"))
in chrome or FF with firebug. Your script might be running before the 'blue'
element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload
).
Put the command inside a batch file, and call that with the parameters.
Also, did you try this yet? (Move end quote to encapsulate parameters)
start "c:\program files\Microsoft Virtual PC\Virtual PC.exe -pc MY-PC -launch"
I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>
I believe that there isn't a way to make a cookie last forever, but you just need to set it to expire far into the future, such as the year 2100.
Process.Start("explorer.exe" , @"C:\Users");
I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.
Use the Git GUI in the Git plugin.
Clone your online repository with the URL which you have.
After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.
Fetch from the remote (to check if anything is updated while you are working).
If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.
Push your changes to the upstream remote repository by making a push operation.
onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).
Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.
In your onCreate:
yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
yourSeekBar.setOnSeekBarChangeListener(new yourListener());
Your listener:
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log the progress
Log.d("DEBUG", "Progress is: "+progress);
//set textView's text
yourTextView.setText(""+progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
Please share some code and the Log results for furter help.
KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
Another way to do this in PHP 5.6+ would be to use the ...
token
$a = array('a', 'b');
$b = array('c', 'd');
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
This will also work with any Traversable
$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
A warning though:
$b
is an empty array or not traversable e.g. not an array$b
is not traversable First, implement the MyData.equals(Object o)
and MyData.hashCode()
methods.
Once you implemented the equals
method, you can iterate over the lists as follows:
if(ListA == null && ListB == null)
return false;
if(ListA == null && ListB != null)
return true;
if(ListA != null && ListB == null)
return true;
int max = ListA.size() > ListB.size() ? ListA.size() : ListB.size();
for(int i = 0; i < max; i++) {
myData1 = ListA.get(i);
myData2 = ListB.get(i);
if(!myData1.equals(myData2)) {
return true;
}
}
return false;
Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.
However if you want to be sure of what just happened, just type
git status
and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.
Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book
There is a commercial product with an interesting logo which lets you see all kind of traffic between server and client named charles.
Another open source tools include: Live HttpHeaders, Wireshark or Firebug.
select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'
For those who are interested, here's a C# Xamarin.Android port of Micah's lovely solution:
public delegate void EllipsizeEvent(bool ellipsized);
public class EllipsizingTextView : TextView
{
private const string Ellipsis = "...";
public event EllipsizeEvent EllipsizeStateChanged;
private bool isEllipsized;
private bool isStale;
private bool programmaticChange;
private string fullText;
private int maxLines = -1;
private float lineSpacingMultiplier = 1.0f;
private float lineAdditionalVerticalPadding;
public EllipsizingTextView(Context context) : base(context)
{
}
public EllipsizingTextView(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public EllipsizingTextView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
}
public EllipsizingTextView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public bool IsEllipsized
{
get { return isEllipsized; }
}
public override void SetMaxLines(int maxLines) {
base.SetMaxLines(maxLines);
this.maxLines = maxLines;
isStale = true;
}
public int GetMaxLines()
{
return maxLines;
}
public override void SetLineSpacing(float add, float mult)
{
lineAdditionalVerticalPadding = add;
lineSpacingMultiplier = mult;
base.SetLineSpacing(add, mult);
}
protected override void OnTextChanged(ICharSequence text, int start, int before, int after)
{
base.OnTextChanged(text, start, before, after);
if (!programmaticChange)
{
fullText = text.ToString();
isStale = true;
}
}
protected override void OnDraw(Canvas canvas)
{
if (isStale)
{
base.Ellipsize = null;
ResetText();
}
base.OnDraw(canvas);
}
private void ResetText()
{
int maxLines = GetMaxLines();
string workingText = fullText;
bool ellipsized = false;
if (maxLines != -1)
{
Layout layout = CreateWorkingLayout(workingText);
if (layout.LineCount > maxLines)
{
workingText = fullText.Substring(0, layout.GetLineEnd(maxLines - 1)).Trim();
while (CreateWorkingLayout(workingText + Ellipsis).LineCount > maxLines)
{
int lastSpace = workingText.LastIndexOf(' ');
if (lastSpace == -1)
{
break;
}
workingText = workingText.Substring(0, lastSpace);
}
workingText = workingText + Ellipsis;
ellipsized = true;
}
}
if (workingText != Text)
{
programmaticChange = true;
try
{
Text = workingText;
}
finally
{
programmaticChange = false;
}
}
isStale = false;
if (ellipsized != isEllipsized)
{
isEllipsized = ellipsized;
if (EllipsizeStateChanged != null)
EllipsizeStateChanged(ellipsized);
}
}
private Layout CreateWorkingLayout(string workingText)
{
return new StaticLayout(workingText, Paint, Width - PaddingLeft - PaddingRight, Layout.Alignment.AlignNormal, lineSpacingMultiplier, lineAdditionalVerticalPadding, false);
}
public override TextUtils.TruncateAt Ellipsize
{
get
{
return base.Ellipsize;
}
set
{
}
}
}
Try setting contentPadding
ListTile(
contentPadding: EdgeInsets.all(0.0),
...
)
A context manager for python3:
import sys
from io import StringIO
class RedirectedStdout:
def __init__(self):
self._stdout = None
self._string_io = None
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._string_io = StringIO()
return self
def __exit__(self, type, value, traceback):
sys.stdout = self._stdout
def __str__(self):
return self._string_io.getvalue()
use like this:
>>> with RedirectedStdout() as out:
>>> print('asdf')
>>> s = str(out)
>>> print('bsdf')
>>> print(s, out)
'asdf\n' 'asdf\nbsdf\n'
ng-model
ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.
ng-bind
ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.
This example would help you to understand.
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault A1
Header append Cache-Control must-revalidate
</FilesMatch>
If you're using .NET 4.0, you could use string.Concat
together with Enumerable.Repeat
.
int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));
Otherwise I'd go with something like Adam's answer.
The reason I generally wouldn't advise using Andrey's answer is simply that the ToArray()
call introduces superfluous overhead that is avoided with the StringBuilder
approach suggested by Adam. That said, at least it works without requiring .NET 4.0; and it's quick and easy (and isn't going to kill you if efficiency isn't too much of a concern).
Try
<?php
//gives you the IP address of the visitors
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];}
else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
//return the country code
$url = "http://api.wipmania.com/$ip";
$country = file_get_contents($url);
echo $country;
?>
You could use a regex to find out if the String contains a number. Take a look at the matches()
method.
In case if there are some characters possible between digits (e.g. thousands separators), you may try following:
declare @table table (DirtyCol varchar(100))
insert into @table values
('AB ABCDE # 123')
,('ABCDE# 123')
,('AB: ABC# 123')
,('AB#')
,('AB # 1 000 000')
,('AB # 1`234`567')
,('AB # (9)(876)(543)')
;with tally as (select top (100) N=row_number() over (order by @@spid) from sys.all_columns),
data as (
select DirtyCol, Col
from @table
cross apply (
select (select C + ''
from (select N, substring(DirtyCol, N, 1) C from tally where N<=datalength(DirtyCol)) [1]
where C between '0' and '9'
order by N
for xml path(''))
) p (Col)
where p.Col is not NULL
)
select DirtyCol, cast(Col as int) IntCol
from data
Output is:
DirtyCol IntCol
--------------------- -------
AB ABCDE # 123 123
ABCDE# 123 123
AB: ABC# 123 123
AB # 1 000 000 1000000
AB # 1`234`567 1234567
AB # (9)(876)(543) 9876543
For update, add ColToUpdate
to select list of the data
cte:
;with num as (...),
data as (
select ColToUpdate, /*DirtyCol, */Col
from ...
)
update data
set ColToUpdate = cast(Col as int)
I would do something like this:
$.each(temp,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
JSON structure would be appreciated. At first you can experiment with find('element')
- it depends on JSON.
NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
While LIKE
is suitable for this case, a more general purpose solution is to use instr
, which doesn't require characters in the search string to be escaped. Note: instr
is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE
is case-insensitive, whereas instr
is case-sensitive.
.m2 directory on linux box usually would be $HOME/.m2
you could get the $HOME :
echo $HOME
or simply:
cd <enter>
to go to your home directory.
other information from maven site: http://maven.apache.org/download.html#Installation
Since Horse
is a subclass of Animal
, you can just change
print(Animal.SIZES[1])
with
print(self.SIZES[1])
Still, you need to remember that SIZES[1]
means "big", so probably you could improve your code by doing something like:
class Animal:
SIZE_HUGE="Huge"
SIZE_BIG="Big"
SIZE_MEDIUM="Medium"
SIZE_SMALL="Small"
class Horse(Animal):
def printSize(self):
print(self.SIZE_BIG)
Alternatively, you could create intermediate classes: HugeAnimal
, BigAnimal
, and so on. That would be especially helpful if each animal class will contain different logic.
For Windows 7 and up, scheduled tasks are not run by cmd.exe
, but rather by MMC
(Microsoft Management Console). %SystemRoot%\Tasks
should work on any other Windows version though.
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
The other answers didn't work for me so here I share my solution in case it might help somebody else:
My problem was that I was configuring the Podfile of my XCode-Project for the wrong platform. Changing "platform :ios" at the beginning of my Podfile to "platform :macos" worked for me to get rid of the error.
You can do this:
var getValue = function (input, defaultValue) {
return input.value || defaultValue;
};