Here I present what I believe to be a cross-platform (Linux and macOS at least) solution to the answer that is working well for me currently.
crosspath()
{
local ref="$1"
if [ -x "$(which realpath)" ]; then
path="$(realpath "$ref")"
else
path="$(readlink -f "$ref" 2> /dev/null)"
if [ $? -gt 0 ]; then
if [ -x "$(which readlink)" ]; then
if [ ! -z "$(readlink "$ref")" ]; then
ref="$(readlink "$ref")"
fi
else
echo "realpath and readlink not available. The following may not be the final path." 1>&2
fi
if [ -d "$ref" ]; then
path="$(cd "$ref"; pwd -P)"
else
path="$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
fi
fi
fi
echo "$path"
}
Here is a macOS (only?) solution. Possibly better suited to the original question.
mac_realpath()
{
local ref="$1"
if [[ ! -z "$(readlink "$ref")" ]]; then
ref="$(readlink "$1")"
fi
if [[ -d "$ref" ]]; then
echo "$(cd "$ref"; pwd -P)"
else
echo "$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
fi
}
To create a new symlink (will fail if symlink exists already):
ln -s /path/to/file /path/to/symlink
To create or update a symlink:
ln -sf /path/to/file /path/to/symlink
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
What I did to add to get the files within a symlink into Git (I didn't use a symlink but):
sudo mount --bind SOURCEDIRECTORY TARGETDIRECTORY
Do this command in the Git-managed directory. TARGETDIRECTORY
has to be created before the SOURCEDIRECTORY
is mounted into it.
It works fine on Linux, but not on OS X! That trick helped me with Subversion too. I use it to include files from an Dropbox account, where a webdesigner does his/her stuff.
Wouldn't unlinking it and creating the new one do the same thing in the end anyway?
Short answer: They are now supported nicely, if you can enable developer mode.
From https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/
Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
What drove this change? The availability and use of symlinks is a big deal to modern developers:
Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.
Easy to overlook with all the other announcements of the "Creator's update", but if you enable Developer Mode, you can create symlinks without elevated privileges. You might have to re-install git and make sure symlink support is enabled, as it's not by default.
# this works:
rm foo
# versus this, which doesn't:
rm foo/
Basically, you need to tell it to delete a file, not delete a directory. I believe the difference between rm
and rmdir
exists because of differences in the way the C library treats each.
At any rate, the first should work, while the second should complain about foo being a directory.
If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.
With the option FollowSymLinks enabled:
$ rg "FollowSymLinks" /etc/httpd/
/etc/httpd/conf/httpd.conf
269: Options Indexes FollowSymLinks
you need all the directories in symlink to be executable by the user httpd is using.
so for this general use case:
cd /path/to/your/web
sudo ln -s $PWD /srv/http/
You can check owner an permissions with namei:
$ namei -m /srv/http/web
f: /srv/http/web
drwxr-xr-x /
drwxr-xr-x srv
drwxr-xr-x http
lrwxrwxrwx web -> /path/to/your/web
drwxr-xr-x /
drwxr-xr-x path
drwx------ to
drwxr-xr-x your
drwxr-xr-x web
In my case to
directory was only executable for my user:
Enable execution by others solve it:
chmod o+x /path/to
See the non executable directory could be different, or you need to affect groups instead others, that depends on your case.
My site configuration file is example.conf in sites-available folder So you can create a symbolic link as
ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.
How about using readlink
?
# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
test "$(readlink "${1}")";
}
FILE=/usr/mda
if simlink? "${FILE}"; then
echo $FILE is a symlink
else
echo $FILE is not a symlink
fi
This will recursively traverse the /path/to/folder
directory and list only the symbolic links:
ls -lR /path/to/folder | grep ^l
If your intention is to follow the symbolic links too, you should use your find
command but you should include the -L
option; in fact the find
man page says:
-L Follow symbolic links. When find examines or prints information
about files, the information used shall be taken from the prop-
erties of the file to which the link points, not from the link
itself (unless it is a broken symbolic link or find is unable to
examine the file to which the link points). Use of this option
implies -noleaf. If you later use the -P option, -noleaf will
still be in effect. If -L is in effect and find discovers a
symbolic link to a subdirectory during its search, the subdirec-
tory pointed to by the symbolic link will be searched.
When the -L option is in effect, the -type predicate will always
match against the type of the file that a symbolic link points
to rather than the link itself (unless the symbolic link is bro-
ken). Using -L causes the -lname and -ilname predicates always
to return false.
Then try this:
find -L /var/www/ -type l
This will probably work: I found in the find
man page this diamond: if you are using the -type
option you have to change it to the -xtype
option:
l symbolic link; this is never true if the -L option or the
-follow option is in effect, unless the symbolic link is
broken. If you want to search for symbolic links when -L
is in effect, use -xtype.
Then:
find -L /var/www/ -xtype l
You can use this utility:
c:\Windows\system32\fsutil.exe create hardlink
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
Another way to see information is stat
command that will show more information. Command stat ~/.ssh
on my machine display
File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
Size: 34 Blocks: 0 IO Block: 4096 symbolic link
Device: 801h/2049d Inode: 25297409 Links: 1
Access: (0777/lrwxrwxrwx) Uid: ( 1000/ sumon) Gid: ( 1000/ sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
Birth: -
Hope this may help someone.
import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
'Age':[23,12,34,44,28,40]})
# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)
# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)
# df1
# Age Name
# 0 23 John
# 1 45 Mike
# 2 12 Smith
# 3 34 Wale
# 4 27 Marry
# 5 44 Tom
# 6 28 Menda
# 7 39 Bolt
# 8 40 Yuswa
# df2
# Age Name
# 0 23 John
# 1 12 Smith
# 2 34 Wale
# 3 44 Tom
# 4 28 Menda
# 5 40 Yuswa
# df_1notin2
# Age Name
# 0 45 Mike
# 1 27 Marry
# 2 39 Bolt
ascii
is a package on linux you could download.
for example
sudo apt-get install ascii
ascii
Usage: ascii [-dxohv] [-t] [char-alias...]
-t = one-line output -d = Decimal table -o = octal table -x = hex table
-h = This help screen -v = version information
Prints all aliases of an ASCII character. Args may be chars, C \-escapes,
English names, ^-escapes, ASCII mnemonics, or numerics in decimal/octal/hex.`
This code can help you with C/C++ escape codes like \x0A
The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:
You can assign the object to a constant of type any, then call the 'non-existing' property.
const newObj: any = oldObj;
return newObj.someProperty;
You can also cast it as any
:
return (oldObj as any).someProperty;
This fails to provide any type safety though, which is the point of TypeScript.
Another thing you may consider, if you're unable to modify the original type, is extending the type like so:
interface NewType extends OldType {
someProperty: string;
}
Now you can cast your variable as this NewType
instead of any
. Still not ideal but less permissive than any
, giving you more type safety.
return (oldObj as NewType).someProperty;
If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc
file type
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
If you need to do the filteration on multiple types, use the below command.
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
Now $fileNames
variable act as an array from which you can loop and apply your business logic.
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>
You can do it for center transparent progress indicator
Future<Null> _submitDialog(BuildContext context) async {
return await showDialog<Null>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return SimpleDialog(
elevation: 0.0,
backgroundColor: Colors.transparent,
children: <Widget>[
Center(
child: CircularProgressIndicator(),
)
],
);
});
}
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
The mm
is minutes you want MM
CODE
public class Test {
public static void main(String[] args) throws ParseException {
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse("2012-07-10 14:58:00.000000");
System.out.println(temp);
}
}
Prints:
Tue Jul 10 14:58:00 EDT 2012
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
According the W3Schools you might use JavaScript for disabled checkbox.
<!-- Checkbox who determine if the other checkbox must be disabled -->
<input type="checkbox" id="checkboxDetermine">
<!-- The other checkbox conditionned by the first checkbox -->
<input type="checkbox" id="checkboxConditioned">
<!-- JS Script -->
<script type="text/javascript">
// Get your checkbox who determine the condition
var determine = document.getElementById("checkboxDetermine");
// Make a function who disabled or enabled your conditioned checkbox
var disableCheckboxConditioned = function () {
if(determine.checked) {
document.getElementById("checkboxConditioned").disabled = true;
}
else {
document.getElementById("checkboxConditioned").disabled = false;
}
}
// On click active your function
determine.onclick = disableCheckboxConditioned;
disableCheckboxConditioned();
</script>
You can see the demo working here : http://jsfiddle.net/antoinesubit/vptk0nh6/
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
) into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS
) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util
type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:
OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);
A simpler way to do the same case is:
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
newDateFormat.parse(newDateFormat.format(
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
.parse(rs.getString("originalRevisionDate", "")))));
If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.
If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript (using jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
It works like this:
Top15['Citable docs per Capita']=np.float64(Top15['Citable docs per Capita'])
Top15['Energy Supply per Capita']=np.float64(Top15['Energy Supply per Capita'])
Top15['Energy Supply per Capita'].corr(Top15['Citable docs per Capita'])
EUREKA I found it!
With the current Studio 1.3 each project has a local.properties
file where you can edit the SDK!
If none of the other answers on this page for you work, here's what I ran into after hours of floundering around.
I used user-specific configurations, with Sites
specified as my UserDir
in /private/etc/apache2/extra/httpd-userdir.conf
. However, I was forbidden access to the endpoint http://localhost/~jwork/
.
I could see in /var/log/apache2/error_log
that access to /Users/jwork/Sites/
was being blocked. However, I was permitted to access the DocumentRoot, via http://localhost/
. This suggested that I didn't have rights to view the ~jwork
user. But as far as I could tell by ps aux | egrep '(apache|httpd)'
and lsof -i :80
, Apache was running for the jwork
user, so something was clearly not write with my user configuration.
Given a user named jwork
, here was my config file:
/private/etc/apache2/users/jwork.conf
<Directory "/Users/jwork/Sites/">
Require all granted
</Directory>
This config is perfectly valid. However, I found that my user config wasn't being included:
/private/etc/apache2/extra/httpd-userdir.conf
## Note how it's commented out by default.
## Just remove the comment to enable your user conf.
#Include /private/etc/apache2/users/*.conf
Note that this is the default path to the userdir conf file, but as you'll see below, it's configurable in httpd.conf
. Ensure that the following lines are enabled:
/private/etc/apache2/httpd.conf
Include /private/etc/apache2/extra/httpd-userdir.conf
# ...
LoadModule userdir_module libexec/apache2/mod_userdir.so
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:
#container {_x000D_
position: relative;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
#block {_x000D_
background: #CCC;_x000D_
filter: alpha(opacity=60);_x000D_
/* IE */_x000D_
-moz-opacity: 0.6;_x000D_
/* Mozilla */_x000D_
opacity: 0.6;_x000D_
/* CSS3 */_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
#text {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="block"></div>_x000D_
<div id="text">Test</div>_x000D_
</div>
_x000D_
The values are determined by the bit of the image. 8 bit 0 to 255
16 bit...some ridiculous number..0 to 65,000 approx.
32 bit are 0 to 1
I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255
For simplicity sake here is what I did.
cd /etc/apt
mkdir test
cp sources.lst test
cd test
sed -i -- 's/us.archive/old-releases/g' *
sed -i -- 's/security/old-releases/g' *
cp sources.lst ../
sudo apt-get update
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shreemad
DB_USERNAME=root
DB_PASSWORD=
Change the DB_PASSWORD field to
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shreemad
DB_USERNAME=root
DB_PASSWORD=" "
In my case it works
There recently was a discussion about this kicked off in usenet: Why no VLAs in C++0x.
I agree with those people that seem to agree that having to create a potential large array on the stack, which usually has only little space available, isn't good. The argument is, if you know the size beforehand, you can use a static array. And if you don't know the size beforehand, you will write unsafe code.
C99 VLAs could provide a small benefit of being able to create small arrays without wasting space or calling constructors for unused elements, but they will introduce rather large changes to the type system (you need to be able to specify types depending on runtime values - this does not yet exist in current C++, except for new
operator type-specifiers, but they are treated specially, so that the runtime-ness doesn't escape the scope of the new
operator).
You can use std::vector
, but it is not quite the same, as it uses dynamic memory, and making it use one's own stack-allocator isn't exactly easy (alignment is an issue, too). It also doesn't solve the same problem, because a vector is a resizable container, whereas VLAs are fixed-size. The C++ Dynamic Array proposal is intended to introduce a library based solution, as alternative to a language based VLA. However, it's not going to be part of C++0x, as far as I know.
An option for DB2:
SELECT 101 AS C1, 102 AS C2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 201 AS C1, 202 AS C2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 301 AS C1, 302 AS C2 FROM SYSIBM.SYSDUMMY1
I found that the path to the image in my repo did not suffice, I had to link to the image on the raw.github.com
subdomain.
URL format https://raw.github.com/{USERNAME}/{REPOSITORY}/{BRANCH}/{PATH}
Markdown example ![Settings Window](https://raw.github.com/ryanmaxwell/iArrived/master/Screenshots/Settings.png)
The best way to work with args for your winforms app is to use
string[] args = Environment.GetCommandLineArgs();
You can probably couple this with the use of an enum to solidify the use of the array througout your code base.
"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."
Found at:HERE
Guys remember that you can use the try catch end event
Dim Green as integer
Try
Green = InputBox("Please enter a value for green")
Catch ex as Exception
MsgBox("Green must be a valid integer!")
End Try
Try the below query
CREATE TABLE card_types (
card_type_id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL default '',
PRIMARY KEY (card_type_id),
) ENGINE = MyISAM ;
Jason Bunting's last index of does not work. Mine is not optimal, but it works.
//Jason Bunting's
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
String.prototype.regexLastIndexOf = function(regex, startpos) {
var lastIndex = -1;
var index = this.regexIndexOf( regex );
startpos = startpos === undefined ? this.length : startpos;
while ( index >= 0 && index < startpos )
{
lastIndex = index;
index = this.regexIndexOf( regex, index + 1 );
}
return lastIndex;
}
Does it re-import every time the function is run?
No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1
Does it import once at the beginning whether or not the function is run?
No, it is only imported if and when the function is executed. 2, 3
As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f
for those cases.)
In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.
In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create
call.
mainDir <- "~"
subDir <- "outputDirectory"
if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
cat("subDir exists in mainDir but is a file")
# you will probably want to handle this separately
} else {
cat("subDir does not exist in mainDir - creating")
dir.create(file.path(mainDir, subDir))
}
if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
# By this point, the directory either existed or has been successfully created
setwd(file.path(mainDir, subDir))
} else {
cat("subDir does not exist")
# Handle this error as appropriate
}
Also be aware that if ~/foo
doesn't exist then a call to dir.create('~/foo/bar')
will fail unless you specify recursive = TRUE
.
How about something like:
\documentclass{article}
\usepackage{amssymb,amsmath}
\begin{document}
\begin{equation}\label{A_Label}
\begin{split}
w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
\end{split}
\end{equation}
\end{document}
which produces:
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
Here is an efficient way to solve this question using For loops in Java
public static void main(String[] args) {
int [] numbers = { 1, 2, 3, 4 };
int size = numbers.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
System.out.println(sum);
}
If you want to open multiple workspaces and you are not a terminal guy, just locate the Unix executable file in your eclipse folder and click it.
The path to the said file is
Eclipse(folder) -> eclipse(right click) -> Show package Contents -> Contents -> MacOs -> eclipse(unix executable file)
Clicking on this executable will open a separate instance of eclipse.
For beginners: To create your .bash_profile
file in your home directory on MacOS, run:
nano ~/.bash_profile
Then you can paste in the following:
https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054
As you can see, it includes some example aliases and an environment variable at the bottom.
One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O
) and Exit (Ctrl-X
). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
You can use HTTP URLs as if they were local files, thanks to PHP's wrappers
You can get the contents from an URL via file_get_contents() and then echo it, or even read it directly using readfile()
$file = file_get_contents('http://example.com/rss');
echo $file;
or
readfile('http://example.com/rss');
Don't forget to set the correct MIME type before outputing anything, though.
header('Content-type: text/xml');
no fancy linq, not adding all the chars by hand, just plain and simple:
var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);
As has been said, using unset is different with arrays as well
$ foo=(4 5 6)
$ foo[2]=
$ echo ${#foo[*]}
3
$ unset foo[2]
$ echo ${#foo[*]}
2
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
SELECT train, dest, time FROM (
SELECT train, dest, time,
RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
FROM traintable
) where dest_rank = 1
All the other answers will work on Angular version < 6.1. But if you've got the latest version then you won't need to do these ugly hacks as Angular has fixed the issue.
All you'd need to do is set scrollOffset
with the option of the second argument ofRouterModule.forRoot
method.
@NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
scrollOffset: [0, 64] // [x, y]
})
],
exports: [RouterModule]
})
export class AppRoutingModule {}
All the answers above couldn't solve the problem in my case. My ImageView
was placed in a customized UITableViewCell
. Therefore I had also call the layoutIfNeeded()
method from here. Example:
class NameTableViewCell:UITableViewCell,UITextFieldDelegate { ...
override func awakeFromNib() {
self.layoutIfNeeded()
profileImageView.layoutIfNeeded()
profileImageView.isUserInteractionEnabled = true
let square = profileImageView.frame.size.width < profileImageView.frame.height ? CGSize(width: profileImageView.frame.size.width, height: profileImageView.frame.size.width) : CGSize(width: profileImageView.frame.size.height, height: profileImageView.frame.size.height)
profileImageView.addGestureRecognizer(tapGesture)
profileImageView.layer.cornerRadius = square.width/2
profileImageView.clipsToBounds = true;
}
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
However, I would not suggest the above method. You should really be using a List<String>
. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item
sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php
and set:
$cfg['Lang'] = 'en-utf-8';
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
A simple way to find this out in Windows is to run SQLPlus from your Oracle homes's bin directory and then check Task Manager. If it is a 32-bit version of SQLPlus, you'll see a process on the Processes tab that looks like this:
sqlplus.exe *32
If it is 64-bit, the process will look like this:
sqlplus.exe
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
you can add this line: word-break:break-all;
to your CSS-code
You need "src/Hankees.txt"
Your file is in the source folder which is not counted as the working directory.\
Or you can move the file up to the root directory of your project and just use "Hankees.txt"
This code work for me:
BufferedImage image = null;
try {
URL file = getClass().getResource("water.bmp");
image = ImageIO.read(file);
} catch (IOException ioex) {
System.err.println("load error: " + ioex.getMessage());
}
ImageIcon icon = new ImageIcon(image);
JButton quitButton = new JButton(icon);
It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android
I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).
Solution that worked for me:
I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)
use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)
I'll give you the query which you can run on kibana.
GET /_cat/indices?v
and the CURL version will be
CURL -XGET http://localhost:9200/_cat/indices?v
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
var address = zipcode;_x000D_
geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
if (status == google.maps.GeocoderStatus.OK) {_x000D_
var latitude = results[0].geometry.location.lat();_x000D_
var longitude = results[0].geometry.location.lng();_x000D_
alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
} else {_x000D_
alert("Request failed.")_x000D_
}_x000D_
});_x000D_
return [latitude, longitude];_x000D_
}
_x000D_
You can get the context using
getActivity().getApplicationContext();
Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.
For example, using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class LayoutEg1 extends JPanel{
private static final int ROWS = 10;
public LayoutEg1() {
setLayout(new GridBagLayout());
for (int i = 0; i < ROWS; i++) {
GridBagConstraints gbc = makeGbc(0, i);
JLabel label = new JLabel("Row Label " + (i + 1));
add(label, gbc);
JPanel panel = new JPanel();
panel.add(new JCheckBox("check box"));
panel.add(new JTextField(10));
panel.add(new JButton("Button"));
panel.setBorder(BorderFactory.createEtchedBorder());
gbc = makeGbc(1, i);
add(panel, gbc);
}
}
private GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Layout Eg1");
frame.getContentPane().add(new LayoutEg1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here's an example script which demonstrates certificate validation:
import httplib
import re
import socket
import sys
import urllib2
import ssl
class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self)
self.host = host
self.cert = cert
self.reason = reason
def __str__(self):
return ('Host %s returned an invalid certificate (%s) %s\n' %
(self.host, self.reason, self.cert))
class CertValidatingHTTPSConnection(httplib.HTTPConnection):
default_port = httplib.HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
ca_certs=None, strict=None, **kwargs):
httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
self.key_file = key_file
self.cert_file = cert_file
self.ca_certs = ca_certs
if self.ca_certs:
self.cert_reqs = ssl.CERT_REQUIRED
else:
self.cert_reqs = ssl.CERT_NONE
def _GetValidHostsForCert(self, cert):
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
sock = socket.create_connection((self.host, self.port))
self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise InvalidCertificateException(hostname, cert,
'hostname mismatch')
class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
def __init__(self, **kwargs):
urllib2.AbstractHTTPHandler.__init__(self)
self._connection_args = kwargs
def https_open(self, req):
def http_class_wrapper(host, **kwargs):
full_kwargs = dict(self._connection_args)
full_kwargs.update(kwargs)
return CertValidatingHTTPSConnection(host, **full_kwargs)
try:
return self.do_open(http_class_wrapper, req)
except urllib2.URLError, e:
if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
raise InvalidCertificateException(req.host, '',
e.reason.args[1])
raise
https_request = urllib2.HTTPSHandler.do_request_
if __name__ == "__main__":
if len(sys.argv) != 3:
print "usage: python %s CA_CERT URL" % sys.argv[0]
exit(2)
handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
opener = urllib2.build_opener(handler)
print opener.open(sys.argv[2]).read()
One of the alternatives is to write the mutliprocessing logging to a known file and register an atexit
handler to join on those processes read it back on stderr; however, you won't get a real-time flow to the output messages on stderr that way.
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
$this->method = $_SERVER['REQUEST_METHOD'];
if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$this->method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$this->method = 'PUT';
} else {
throw new Exception("Unexpected Header");
}
}
In my Apache VirtualHost config file, I have added following lines :
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
Assign to variables and display it.
time = new Date();
var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds()
document.getElementById("time").value = hh + ":" + mm + ":" + ss;
The Extensible Markup Language (XML) 1.0 only includes the block comments.
I created a ~/.wgetrc
file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):
header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off
Now I’m able to download from most (all?) file-sharing (streaming video) sites.
The solution that worked for me, is missing from the list of answers. Hence I am posting this solution here:
File[]dirs = new File("/mypath/mydir/").listFiles((FileFilter)FileFilterUtils.directoryFileFilter());
Here I have used org.apache.commons.io.filefilter.FileFilterUtils
from Apache commons-io-2.2.jar. Its documentation is available here: https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/filefilter/FileFilterUtils.html
Create a new ImageIcon
object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame
with setIconImage()
:
myFrame.setIconImage(img.getImage());
Also checkout setIconImages()
which takes a List
instead.
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
Decode and save image as PNG
header('content-type: image/png');
ob_start();
$ret = fopen($fullurl, 'r', true, $context);
$contents = stream_get_contents($ret);
$base64 = 'data:image/PNG;base64,' . base64_encode($contents);
echo "<img src=$base64 />" ;
ob_end_flush();
Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.
import { OpaqueToken } from "@angular/core";
export let APP_CONFIG = new OpaqueToken("my.config");
export interface MyAppConfig {
apiEndpoint: string;
}
export const AppConfig: MyAppConfig = {
apiEndpoint: "http://localhost:8080/api/"
};
Inject it in providers in app.module.ts
You will be able to use it across every components.
EDIT for Angular 4 :
For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.
Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject
Example Code
Angular 2 Using Opaque Tokens
const API_URL = new OpaqueToken('apiUrl'); //no Type Check
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
new Inject(API_URL) //notice the new Inject
]
}
]
Angular 4 Using Injection Tokens
const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
API_URL // no `new Inject()` needed!
]
}
]
Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
As one suggested, i went through implementation of resource bundle.. but that did not help.. as the bundle was always called under en_US locale... i tried to set my default locale to a different language and still my implementation of resource bundle control was being called with en_US... i tried to put log messages and do a step through debug and see if a different local call was being made after i change locale at run time through xhtml and JSF calls... that did not happend... then i tried to do a system set default to a utf8 for reading files by my server (tomcat server).. but that caused pronlem as all my class libraries were not compiled under utf8 and tomcat started to read then in utf8 format and server was not running properly... then i ended up with implementing a method in my java controller to be called from xhtml files.. in that method i did the following:
public String message(String key, boolean toUTF8) throws Throwable{
String result = "";
try{
FacesContext context = FacesContext.getCurrentInstance();
String message = context.getApplication().getResourceBundle(context, "messages").getString(key);
result = message==null ? "" : toUTF8 ? new String(message.getBytes("iso8859-1"), "utf-8") : message;
}catch(Throwable t){}
return result;
}
I was particularly nervous as this could slow down performance of my application... however, after implementing this, it looks like as if my application is faster now.. i think it is because, i am now directly accessing the properties instead of letting JSF parse its way into accessing properties... i specifically pass Boolean argument in this call because i know some of the properties would not be translated and do not need to be in utf8 format...
Now I have saved my properties file in UTF8 format and it is working fine as each user in my application has a referent locale preference.
Here's a full featured TimeOfDay class.
This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.
It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.
Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:
This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.
// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT
using System;
using System.Text.RegularExpressions;
namespace Cambia
{
public class TimeOfDay
{
private const int MINUTES_PER_DAY = 60 * 24;
private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
private const int SECONDS_PER_HOUR = 3600;
private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");
public TimeOfDay()
{
Init(0, 0, 0);
}
public TimeOfDay(int hour, int minute, int second = 0)
{
Init(hour, minute, second);
}
public TimeOfDay(int hhmmss)
{
Init(hhmmss);
}
public TimeOfDay(DateTime dt)
{
Init(dt);
}
public TimeOfDay(TimeOfDay td)
{
Init(td.Hour, td.Minute, td.Second);
}
public int HHMMSS
{
get
{
return Hour * 10000 + Minute * 100 + Second;
}
}
public int Hour { get; private set; }
public int Minute { get; private set; }
public int Second { get; private set; }
public double TotalDays
{
get
{
return TotalSeconds / (24d * SECONDS_PER_HOUR);
}
}
public double TotalHours
{
get
{
return TotalSeconds / (1d * SECONDS_PER_HOUR);
}
}
public double TotalMinutes
{
get
{
return TotalSeconds / 60d;
}
}
public int TotalSeconds
{
get
{
return Hour * 3600 + Minute * 60 + Second;
}
}
public bool Equals(TimeOfDay other)
{
if (other == null) { return false; }
return TotalSeconds == other.TotalSeconds;
}
public override bool Equals(object obj)
{
if (obj == null) { return false; }
TimeOfDay td = obj as TimeOfDay;
if (td == null) { return false; }
else { return Equals(td); }
}
public override int GetHashCode()
{
return TotalSeconds;
}
public DateTime ToDateTime(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
}
public override string ToString()
{
return ToString("HH:mm:ss");
}
public string ToString(string format)
{
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
return dt.ToString(format);
}
public TimeSpan ToTimeSpan()
{
return new TimeSpan(Hour, Minute, Second);
}
public DateTime ToToday()
{
var now = DateTime.Now;
return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
}
#region -- Static --
public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 - ts;
return new TimeOfDay(dt2);
}
public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds != t2.TotalSeconds;
}
}
public static bool operator !=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 != dt2;
}
public static bool operator !=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 != dt2;
}
public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 + ts;
return new TimeOfDay(dt2);
}
public static bool operator <(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds < t2.TotalSeconds;
}
}
public static bool operator <(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 < dt2;
}
public static bool operator <(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 < dt2;
}
public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
if (t1 == t2) { return true; }
return t1.TotalSeconds <= t2.TotalSeconds;
}
}
public static bool operator <=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 <= dt2;
}
public static bool operator <=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 <= dt2;
}
public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else { return t1.Equals(t2); }
}
public static bool operator ==(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 == dt2;
}
public static bool operator ==(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 == dt2;
}
public static bool operator >(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds > t2.TotalSeconds;
}
}
public static bool operator >(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 > dt2;
}
public static bool operator >(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 > dt2;
}
public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds >= t2.TotalSeconds;
}
}
public static bool operator >=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 >= dt2;
}
public static bool operator >=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 >= dt2;
}
/// <summary>
/// Input examples:
/// 14:21:17 (2pm 21min 17sec)
/// 02:15 (2am 15min 0sec)
/// 2:15 (2am 15min 0sec)
/// 2/1/2017 14:21 (2pm 21min 0sec)
/// TimeOfDay=15:13:12 (3pm 13min 12sec)
/// </summary>
public static TimeOfDay Parse(string s)
{
// We will parse any section of the text that matches this
// pattern: dd:dd or dd:dd:dd where the first doublet can
// be one or two digits for the hour. But minute and second
// must be two digits.
Match m = _TodRegex.Match(s);
string text = m.Value;
string[] fields = text.Split(':');
if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
int hour = Convert.ToInt32(fields[0]);
int min = Convert.ToInt32(fields[1]);
int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;
return new TimeOfDay(hour, min, sec);
}
#endregion
private void Init(int hour, int minute, int second)
{
if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
Hour = hour;
Minute = minute;
Second = second;
}
private void Init(int hhmmss)
{
int hour = hhmmss / 10000;
int min = (hhmmss - hour * 10000) / 100;
int sec = (hhmmss - hour * 10000 - min * 100);
Init(hour, min, sec);
}
private void Init(DateTime dt)
{
Init(dt.Hour, dt.Minute, dt.Second);
}
}
}
use js split() method to create an array
var keywords = $('#searchKeywords').val().split(",");
then loop through the array using jQuery.each() function. as the documentation says:
In the case of an array, the callback is passed an array index and a corresponding array value each time
$.each(keywords, function(i, keyword){
console.log(keyword);
});
3 Ways to Install Applications On Android Without The Market
And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly
I just wanted to add that if you don't want your application name in the root context at all, you and just put "/" (no quotes, just the forward slash) in the Eclipse --> Web Project Settings --> Context Root entry
That will deploy the webapp to just http://localhost:8080/
Of course, this will cause problems with other webapps you try to run on the server, so heads up with that.
Took me forever to piece that together... so even though this post is 8 years old, hopefully this will still help someone!
During initial testing for Membership.ValidateUser with a SqlMembershipProvider, I use a hash (SHA1) algorithm combined with a salt, and, if I changed the salt length to a length not divisible by four, I received this error.
I have not tried any of the fixes above, but if the salt is being altered, this may help someone pinpoint that as the source of this particular error.
Per the JQuery documentation, .get()
only takes the url
, data
(content), dataType
, and success
callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax()
, this is done with the beforeSend()
method. But since .get()
is a shortcut, it doesn't allow it.
It should be relatively easy to switch your .ajax()
calls to .get()
calls though. After all, .get()
is just a subset of .ajax()
, so you can probably use all the default values for .ajax()
(except, of course, for beforeSend()
).
Edit:
::Looks at Jivings' answer::
Oh yeah, forgot about the cache
parameter! While beforeSend()
is useful for adding other headers, the built-in cache
parameter is far simpler here.
In Firefox you can just add background image to option:
<select>
<option style="background-image:url(male.png);">male</option>
<option style="background-image:url(female.png);">female</option>
<option style="background-image:url(others.png);">others</option>
</select>
Better yet, you can separate HTML and CSS like that
HTML
<select id="gender">
<option>male</option>
<option>female</option>
<option>others</option>
</select>
CSS
select#gender option[value="male"] { background-image:url(male.png); }
select#gender option[value="female"] { background-image:url(female.png); }
select#gender option[value="others"] { background-image:url(others.png); }
In other browsers the only way of doing that would be using some JS widget library, like for example jQuery UI, e.g. using Selectable.
From jQuery UI 1.11, Selectmenu widget is available, which is very close to what you want.
try this method
private string removeNestedWhitespaces(char[] st)
{
StringBuilder sb = new StringBuilder();
int indx = 0, length = st.Length;
while (indx < length)
{
sb.Append(st[indx]);
indx++;
while (indx < length && st[indx] == ' ')
indx++;
if(sb.Length > 1 && sb[0] != ' ')
sb.Append(' ');
}
return sb.ToString();
}
use it like this:
string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());
You should not play with the height. Let the text field determine the height based on the font used.
If you want to control the width of the text field then you can use
textField.setColumns(...);
to let the text field determine the preferred width.
Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.
See the Swing tutorial on Layout Managers for more information.
I did solve this error by setting
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME
yes, not only $ORACLE_HOME/lib but $ORACLE_HOME too.
If you'd like to read a file from the command line or from stdin, you can also use the fileinput
module:
# reader.py
import fileinput
content = []
for line in fileinput.input():
content.append(line.strip())
fileinput.close()
Pass files to it like so:
$ python reader.py textfile.txt
Read more here: http://docs.python.org/2/library/fileinput.html
I've had a similar error for react-native-youtube & react-native-orientation.
Figured out, that the build.gradle of those Project use compileSdkVersion 23
but the Feature: android:keyboardNavigationCluster was added since api 26
(android 8).
So how to fix?
One way to fix this easily is to edit your /android/build.gradle ( !!! NOT /android/app/build.gradle) and add those code at the bottom of the file.
This allow you to force the SDK and BuildTool-Version your submodules use:
subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 27
buildToolsVersion "27.0.2"
}
}
}
}
User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})
Post.find({ where: { ...}, include: [User]})
Which will give you
SELECT
`posts`.*,
`users`.`username` AS `users.username`, `users`.`email` AS `users.email`,
`users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,
`users`.`day_birth` AS `users.day_birth`,
`users`.`month_birth` AS `users.month_birth`,
`users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,
`users`.`createdAt` AS `users.createdAt`,
`users`.`updatedAt` AS `users.updatedAt`
FROM `posts`
LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;
The query above might look a bit complicated compared to what you posted, but what it does is basically just aliasing all columns of the users table to make sure they are placed into the correct model when returned and not mixed up with the posts model
Other than that you'll notice that it does a JOIN instead of selecting from two tables, but the result should be the same
Further reading:
Save yourself the headache of trying to find a "built-in" solution.
There isn't a good answer, and the hugely upvoted answer in this thread is wrong.
npm install is-number
In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:
console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+' '); //=> 0
console.log(typeof NaN); //=> 'number'
Putting plot.tight_layout()
after all changes on the graph, just before show()
or savefig()
will solve the problem.
Before messing with Nginx config, try to disable ChromePHP first.
chromephp:
type: chromephp
level: info
ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
Excuse me, but this all seems like a great deal of elaborate syntax to hide a few lines of code.
Why not this:
/**
Read line from a CSV file
@param[in] fp file pointer to open file
@param[in] vls reference to vector of strings to hold next line
*/
void readCSV( FILE *fp, std::vector<std::string>& vls )
{
vls.clear();
if( ! fp )
return;
char buf[10000];
if( ! fgets( buf,999,fp) )
return;
std::string s = buf;
int p,q;
q = -1;
// loop over columns
while( 1 ) {
p = q;
q = s.find_first_of(",\n",p+1);
if( q == -1 )
break;
vls.push_back( s.substr(p+1,q-p-1) );
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::string> vls;
FILE * fp = fopen( argv[1], "r" );
if( ! fp )
return 1;
readCSV( fp, vls );
readCSV( fp, vls );
readCSV( fp, vls );
std::cout << "row 3, col 4 is " << vls[3].c_str() << "\n";
return 0;
}
Or just convert a DataTable Row collection to a list:
foreach(DataRow dr in dtPerson.Rows.ToList())
{
if(dr["name"].ToString()=="Joe")
dr.Delete();
}
SELECT Q.FK
,ISNULL(T1.Field1, T2.Field2) AS Field
FROM (SELECT FK FROM Table1
UNION
SELECT FK FROM Table2) AS Q
LEFT JOIN Table1 AS T1 ON T1.FK = Q.FK
LEFT JOIN Table2 AS T2 ON T2.FK = Q.FK
If there is one table, write Table1 instead of Table2
As far as the actual loading image, check out this site for a bunch of options.
As far as displaying a DIV with this image when a request begins, you have a few choices:
A) Manually show and hide the image:
$('#form').submit(function() {
$('#wait').show();
$.post('/whatever.php', function() {
$('#wait').hide();
});
return false;
});
B) Use ajaxStart and ajaxComplete:
$('#wait').ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
Using this the element will show/hide for any request. Could be good or bad, depending on the need.
C) Use individual callbacks for a particular request:
$('#form').submit(function() {
$.ajax({
url: '/whatever.php',
beforeSend: function() { $('#wait').show(); },
complete: function() { $('#wait').hide(); }
});
return false;
});
How could I get the value of lang (where lang=eng in book title), for the first element?
Use:
/*/book[1]/title/@lang
This means:
Select the lang
attribute of the title element that is a child of the first book
child of the top element of the XML document.
To get just the string value of this attribute use the standard XPath function string()
:
string(/*/book[1]/title/@lang)
This would work too:
document.getElementsByTagName('p')[0].id
(If element where the 1st paragraph in your document)
Note the plural in this method:
document.getElementsByName()
That returns an array of elements, so use [0] to get the first occurence, e.g.
document.getElementsByName()[0]
You can now link to an external site using React Link by providing an object to to
with the pathname
key:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
If you find that you need to use JS to generate the link in a callback, you can use window.location.replace()
or window.location.assign()
.
Over using window.location.replace()
, as other good answers suggest, try using window.location.assign()
.
window.location.replace()
will replace the location history without preserving the current page.
window.location.assign()
will transition to the url specified, but will save the previous page in the browser history, allowing proper back-button functionality.
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
Also, if you are using a window.location = url
method as mentioned in other answers, I highly suggest switching to window.location.href = url
.
There is a heavy argument about it, where many users seem to adamantly want to revert the newer object
type window.location
to its original implementation as string
merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location
object.
Check out this convo. It's terrible. Javascript: Setting location.href versus location
Enable this option in VS: Just My Code option
Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".
I know it's a bit silly, but I hope this helps.
You can try joda-time.
it can also be achieved with below code
import re
text = 'how are u? umberella u! u. U. U@ U# u '
print (re.sub (r'[uU] ( [^a-z] )', r' you\1 ', text))
or
print (re.sub (r'[uU] ( [\s!,.?@#] )', r' you\1 ', text))
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
Reload the current document:
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>
My first answer!
This will set the safemode switch:
bcdedit /set {current} safeboot minimal
with networking:
bcdedit /set {current} safeboot network
then reboot the machine with
shutdown /r
to put back in normal mode via dos:
bcdedit /deletevalue {current} safeboot
New way I've just stumbled upon: css calc()
:
.calculated-width {
width: -webkit-calc(100% - 100px);
width: -moz-calc(100% - 100px);
width: calc(100% - 100px);
}?
Source: css width 100% minus 100px
Dim found As Integer
found = 0
Dim vTest As Variant
vTest = Application.VLookup(TextBox1.Value, _
Worksheets("Sheet3").Range("A2:A55"), 1, False)
If IsError(vTest) Then
found = 0
MsgBox ("Type Mismatch")
TextBox1.SetFocus
Cancel = True
Exit Sub
Else
TextBox2.Value = Application.VLookup(TextBox1.Value, _
Worksheets("Sheet3").Range("A2:B55"), 2, False)
found = 1
End If
Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:
function_pool.h
#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>
class Function_pool
{
private:
std::queue<std::function<void()>> m_function_queue;
std::mutex m_lock;
std::condition_variable m_data_condition;
std::atomic<bool> m_accept_functions;
public:
Function_pool();
~Function_pool();
void push(std::function<void()> func);
void done();
void infinite_loop_func();
};
function_pool.cpp
#include "function_pool.h"
Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}
Function_pool::~Function_pool()
{
}
void Function_pool::push(std::function<void()> func)
{
std::unique_lock<std::mutex> lock(m_lock);
m_function_queue.push(func);
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
lock.unlock();
m_data_condition.notify_one();
}
void Function_pool::done()
{
std::unique_lock<std::mutex> lock(m_lock);
m_accept_functions = false;
lock.unlock();
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
m_data_condition.notify_all();
//notify all waiting threads.
}
void Function_pool::infinite_loop_func()
{
std::function<void()> func;
while (true)
{
{
std::unique_lock<std::mutex> lock(m_lock);
m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
if (!m_accept_functions && m_function_queue.empty())
{
//lock will be release automatically.
//finish the thread loop and let it join in the main thread.
return;
}
func = m_function_queue.front();
m_function_queue.pop();
//release the lock
}
func();
}
}
main.cpp
#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>
Function_pool func_pool;
class quit_worker_exception : public std::exception {};
void example_function()
{
std::cout << "bla" << std::endl;
}
int main()
{
std::cout << "stating operation" << std::endl;
int num_threads = std::thread::hardware_concurrency();
std::cout << "number of threads = " << num_threads << std::endl;
std::vector<std::thread> thread_pool;
for (int i = 0; i < num_threads; i++)
{
thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
}
//here we should send our functions
for (int i = 0; i < 50; i++)
{
func_pool.push(example_function);
}
func_pool.done();
for (unsigned int i = 0; i < thread_pool.size(); i++)
{
thread_pool.at(i).join();
}
}
You can parse urls using modern JS:
var my_url = new URL('http://www.google.sk/foo?boo=123#baz');
my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
?my_url.protocol; // "http:"
?my_url.search; // outputs "?doo=123"
urls with no hash will return empty string.
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
check two things
pip2 --version
and
pip3 --version
because the default pip may be anyone of this so it is always better to check both.
@echo off
:Start # seting a ponter
title timer #name the cmd window to "Timer"
echo Type in an amount of time (Seconds)
set /p A= #wating for input from user
set B=1
cls
:loop
ping localhost -n 2 >nul #pinging your self for 1 second
set /A A=A-B #sets the value A - 1
echo %A% # printing A
if %A% EQU 0 goto Timesup #if A = 0 go to ponter Timesup eles loop it
goto loop
:Timesup #ponter Timesup
cls #clear the screen
MSG * /v "time Is Up!" #makes a pop up saying "time Is Up!"
goto Exit #go to exit
:Exit
In bootstrap-3.3.7.js you will see the following code.
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
So the bootstrap is going to replace the remote content into <div class="modal-content">
element. This is the default behavior by framework. So the problem is in your remote content itself, it should contain <div class="modal-header">
, <div class="modal-body">
, <div class="modal-footer">
by design.
Even if there are tools that allow you to mock your database in one way or another (e.g. jOOQ's MockConnection
, which can be seen in this answer - disclaimer, I work for jOOQ's vendor), I would advise not to mock larger databases with complex queries.
Even if you just want to integration-test your ORM, beware that an ORM issues a very complex series of queries to your database, that may vary in
Mocking all that to produce sensible dummy data is quite hard, unless you're actually building a little database inside your mock, which interprets the transmitted SQL statements. Having said so, use a well-known integration-test database that you can easily reset with well-known data, against which you can run your integration tests.
You could use Jsel - https://github.com/dragonworx/jsel (for full disclosure, I am the owner of this library).
It uses a real XPath engine and is highly customizable. Runs in both Node.js and the browser.
Given your original question, you'd find the people by name with:
// include or require jsel library (npm or browser)
var dom = jsel({
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
});
var person = dom.select("//person/*[@name='Peter']");
person.age === 43; // true
If you you were always working with the same JSON schema you could create your own schema with jsel, and be able to use shorter expressions like:
dom.select("//person[@name='Peter']")
This hack 100% work only for safari 5.1-6.0. I've just tested it with success.
@media only screen and (-webkit-min-device-pixel-ratio: 1) {
::i-block-chrome, .yourcssrule {
your css property
}
}
Using a classmethod
with __members__
:
class RoleNames(str, Enum):
AGENT = "agent"
USER = "user"
PRIMARY_USER = "primary_user"
SUPER_USER = "super_user"
@classmethod
def list_roles(cls):
role_names = [member.value for role, member in cls.__members__.items()]
return role_names
>>> role_names = RoleNames.list_roles()
>>> print(role_names)
or if you have multiple Enum
classes and want to abstract the classmethod
:
class BaseEnum(Enum):
@classmethod
def list_roles(cls):
role_names = [member.value for role, member in cls.__members__.items()]
return role_names
class RoleNames(str, BaseEnum):
AGENT = "agent"
USER = "user"
PRIMARY_USER = "primary_user"
SUPER_USER = "super_user"
class PermissionNames(str, BaseEnum):
READ = "updated_at"
WRITE = "sort_by"
READ_WRITE = "sort_order"
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
Yes, via extensions. Try Bookmarks extension on marketplace.visualstudio.com
Hit Ctrl+Shift+P and type the install extensions
and press enter, then type Bookmark
and press enter.
Next you may wish to customize what keys are used to make a bookmark and move to it. For that see this question.
The pytz
module is one option, and there is another python-dateutil
, which although is also third party package, may already be available depending on your other dependencies and operating system.
I just wanted to include this methodology for reference- if you've already installed python-dateutil
for other purposes, you can use its tzinfo
instead of duplicating with pytz
import datetime
import dateutil.tz
# Get the UTC time with datetime.now:
utcdt = datetime.datetime.now(dateutil.tz.tzutc())
# Get the UTC time with datetime.utcnow:
utcdt = datetime.datetime.utcnow()
utcdt = utcdt.replace(tzinfo=dateutil.tz.tzutc())
# For fun- get the local time
localdt = datetime.datetime.now(dateutil.tz.tzlocal())
I tend to agree that calls to utcnow
should include the UTC timezone information. I suspect that this is not included because the native datetime library defaults to naive datetimes for cross compatibility.
Case String:
String password = "ill stay in StringPool after Death !!!";
// some long code goes
// ...Now I want to remove traces of password
password = null;
password = "";
// above attempts wil change value of password
// but the actual password can be traced from String pool through memory dump, if not garbage collected
Case CHAR ARRAY:
char[] passArray = {'p','a','s','s','w','o','r','d'};
// some long code goes
// ...Now I want to remove traces of password
for (int i=0; i<passArray.length;i++){
passArray[i] = 'x';
}
// Now you ACTUALLY DESTROYED traces of password form memory
myList.Where(item=>item.Name == nameToExtract)
Docker is some-kind of super-fast virtual machine which can be use to run tools like node (instead install them directly on mac-os). Advantages to do it are following
all stuff ('milions' node files) are install inside docker image/container (they encapsulated in few inner-docker files)
you can map your mac directory with project to your docker container and have access to node - but outside docker, mac-os sytem don't even know that node is installed. So you get some kind of 'virtual' console with available node commands which can works on real files
you can easily kill node by find it by docker ps
and kill by docker rm -f name_or_num
you can easily uninstall docker image/containers by one command docker rmi ...
and get free space - and install it again by run script (below)
your node is encapsulated inside docker and don't have access to whole system - only to folders you map to it
you can run node services and easily map they port to mac port and have access to it from web browser
you can run many node versions at the same time
in similar way you can install other tools like (in many versions in same time): php, databases, redis etc. - inside docker without any interaction with mac-os (which not notice such software at all). E.g. you can run at the same time 3 mysql db with different versions and 3 php application with different php version ... - so you can have many tools but clean system
TEAM WORK: such enviroment can be easily cloned into other machines (and even to windows/linux systems - with some modifications) and provide identical docker-level environment - so you can easily set up and reuse you scripts/dockerfiles, and setup environment for new team member in very fast way (he just need to install docker and create similar folder-structure and get copy of scripts - thats all). I work this way for 2 year and with my team - and we are very happy
Install docker using e.g. this instructions
Prepare 'special' directory for work e.g. my directory is /Users/kamil/work
(I will use this directory further - but it can be arbitrary) - this directory will be 'interface' between docker containers and your mac file ststem. Inside this dir create following dir structure:
/Users/kamil/work/code
- here you put your projects with code
/Users/kamil/work/tools
/Users/kamil/work/tools/docker-data
- here we map containers output data like logs (or database files if someone ouse db etc.)
/Users/kamil/work/tools/docker
/Users/kamil/work/tools/docker/node-cmd
- here we put docker node scripts
inside tools
create file .env
which will contain in one place global-paths used in other scripts
toolspath="/Users/kamil/work/tools"
codepath="/Users/kamil/work/code"
workpath=/Users/kamil/work
_x000D_
innside dir ../node-cmd
create file dockerfile
with following content
# default /var/www/html (mapped to .../code folder with projects)
FROM node
WORKDIR /work
# Additional arbitrary tools (ng, gulp, bower)
RUN npm install -g n @angular/cli bower gulp grunt
CMD while true; do sleep 10000; done
# below ports are arbitrary
EXPOSE 3002 3003 3004 4200
_x000D_
innside dir ../node-cmd
create file run-container
with following content (this file should be executable e.g. by chmod +x run-container
) - (notice how we map port-s and directories form external 'world' to internal docker filesystem)
set -e
cd -- "$(dirname "$0")" # this script dir (not set on doubleclick)
source ../../.env
toolsdir=$toolspath/docker-data
workdir=$workpath
if [ ! "$(docker ps | grep node-cmd)" ]
then
docker build -t node-cmd .
docker rm -f node-cmd |:
docker run -d --name node-cmd -p 4200:4200 -p 4201:4201 -p 3002:3002 -p 3003:3003 -p 3004:3004 -v $toolsdir/node-cmd/logs:/root/.npm/_logs -v $workdir:/work node-cmd
fi
_x000D_
ok now you can add some project e.g. work/code/myProject
and add to it following file 'run-cmd' (must be executable)
cd -- "$(dirname "$0")"
../../tools/docker/node-cmd/run-container
docker exec -it node-cmd bash -c "cd /work/code/myProject; bash"
_x000D_
then if you run above script (by double-click), you will see console with available node commands in project directory e.g. npm install
to run project in background (e.g some serwice) e.g. run web-server angular-cli application you can use following script (named run-front
-must be executable) - (you must also edit /etc/hosts
file to add proper domain)
cd -- "$(dirname "$0")"
open "http://my-angular.local:3002"
../../tools/docker/node-cmd/run-container
docker exec -it node-cmd /bin/sh -c "cd /work/code/my-angular-project; npm start"
cat # for block script and wait for user ctrl+C
_x000D_
I think your solution would be to wrap your content container and your sidebar in a parent containing div. Float your sidebar to the left and give it the background image. Create a wide margin at least the width of your sidebar for your content container. Add clearing a float hack to make it all work.
Not a Javascript library but it may be a suitable alternative - check out Google Charts where you can generate charts by passing querystring data to their web service.
It is stated on the same tutorial that
Please note that the code below is only useful for testing your settings in an application targeting Android API 12 or later
Just change your min SDK version to 12 and it will works
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
Haven's tried Aurel's workaround for older versions of the API yet.
Yes, -f
is the most suitable option for this.
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.
The one line version to group a list
of objects by a certain key
in es6:
const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})
The longer version that filters out the objects without the key
:
function groupByKey(array, key) {
return array
.reduce((hash, obj) => {
if(obj[key] === undefined) return hash;
return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
}, {})
}
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
console.log(groupByKey(cars, 'make'))
_x000D_
NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:
const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
console.log(groupByKey(cars, 'make', {omitKey:true}))
_x000D_
The importance of locales is that your environment/os can provide formatting functionality for all installed locales even if you don't know about them when you write your application. My Windows 7 system has 211 locales installed (listed below), so you wouldn't likely write any custom code or translation specific to this many locales.
The most important thing for various versions of English is in formatting numbers and dates. Other differences are significant to the extent that you want and able to cater to specific variations.
af-ZA
am-ET
ar-AE
ar-BH
ar-DZ
ar-EG
ar-IQ
ar-JO
ar-KW
ar-LB
ar-LY
ar-MA
arn-CL
ar-OM
ar-QA
ar-SA
ar-SY
ar-TN
ar-YE
as-IN
az-Cyrl-AZ
az-Latn-AZ
ba-RU
be-BY
bg-BG
bn-BD
bn-IN
bo-CN
br-FR
bs-Cyrl-BA
bs-Latn-BA
ca-ES
co-FR
cs-CZ
cy-GB
da-DK
de-AT
de-CH
de-DE
de-LI
de-LU
dsb-DE
dv-MV
el-GR
en-029
en-AU
en-BZ
en-CA
en-GB
en-IE
en-IN
en-JM
en-MY
en-NZ
en-PH
en-SG
en-TT
en-US
en-ZA
en-ZW
es-AR
es-BO
es-CL
es-CO
es-CR
es-DO
es-EC
es-ES
es-GT
es-HN
es-MX
es-NI
es-PA
es-PE
es-PR
es-PY
es-SV
es-US
es-UY
es-VE
et-EE
eu-ES
fa-IR
fi-FI
fil-PH
fo-FO
fr-BE
fr-CA
fr-CH
fr-FR
fr-LU
fr-MC
fy-NL
ga-IE
gd-GB
gl-ES
gsw-FR
gu-IN
ha-Latn-NG
he-IL
hi-IN
hr-BA
hr-HR
hsb-DE
hu-HU
hy-AM
id-ID
ig-NG
ii-CN
is-IS
it-CH
it-IT
iu-Cans-CA
iu-Latn-CA
ja-JP
ka-GE
kk-KZ
kl-GL
km-KH
kn-IN
kok-IN
ko-KR
ky-KG
lb-LU
lo-LA
lt-LT
lv-LV
mi-NZ
mk-MK
ml-IN
mn-MN
mn-Mong-CN
moh-CA
mr-IN
ms-BN
ms-MY
mt-MT
nb-NO
ne-NP
nl-BE
nl-NL
nn-NO
nso-ZA
oc-FR
or-IN
pa-IN
pl-PL
prs-AF
ps-AF
pt-BR
pt-PT
qut-GT
quz-BO
quz-EC
quz-PE
rm-CH
ro-RO
ru-RU
rw-RW
sah-RU
sa-IN
se-FI
se-NO
se-SE
si-LK
sk-SK
sl-SI
sma-NO
sma-SE
smj-NO
smj-SE
smn-FI
sms-FI
sq-AL
sr-Cyrl-BA
sr-Cyrl-CS
sr-Cyrl-ME
sr-Cyrl-RS
sr-Latn-BA
sr-Latn-CS
sr-Latn-ME
sr-Latn-RS
sv-FI
sv-SE
sw-KE
syr-SY
ta-IN
te-IN
tg-Cyrl-TJ
th-TH
tk-TM
tn-ZA
tr-TR
tt-RU
tzm-Latn-DZ
ug-CN
uk-UA
ur-PK
uz-Cyrl-UZ
uz-Latn-UZ
vi-VN
wo-SN
xh-ZA
yo-NG
zh-CN
zh-HK
zh-MO
zh-SG
zh-TW
zu-ZA
If you're open to a Perl solution...
perl -ane 'print "$F[0] $F[1]\n"' file
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-e
execute the following perl code
Two things are happening here.
Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.
What you want to do is the following:
<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
<div class="row">
<div class="col-md-4 myClassName"> <!-- myClassName is defined in my CSS as you defined your container -->
<img src="#.jpg" height="200px" width="300px">
</div>
</div>
</div>
Here you can find more info on the Bootstrap grid system.
That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
max-width: 900px;
overflow:hidden;
min-height:0px !important;
}
But I have always found that the "!important" clause just makes for messy CSS.
Following is a simple function to check if a particular node is present or not in the xml file.
public boolean envParamExists(String xmlFilePath, String paramName){
try{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));
doc.getDocumentElement().normalize();
if(doc.getElementsByTagName(paramName).getLength()>0)
return true;
else
return false;
}catch (Exception e) {
//error handling
}
return false;
}
This is my code:
IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();
Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like
select count(*) from ...
Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.
The git checkout master
of the answer by Woland isn't needed. Instead use the "Checkout to specific local branch" in the "Additional Behaviors" section to set the "Branch name" to master.
The git commit -am "blah"
is still needed.
Now you can use the "Git Publisher" under "Post-build Actions" to push the changes. Be sure to specify the "Branches" to push ("Branch to push" = master, "Target remote name" = origin).
"Merge Results" isn't needed.
db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})
The short answer is you can't because Math
and Date
(off the top of my head, I'm sure there are others) are't normal objects. To see this, create a simple test script:
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
alert("Math: " + Math);
alert("Math: " + Math.sqrt);
alert("Date: " + Date);
alert("Array: " + Array);
alert("jQuery: " + jQuery);
alert("Document: " + document);
alert("Document: " + document.ready);
});
</script>
</body>
</html>
You see it presents as an object the same ways document does overall, but when you actually try and see in that object, you see that it's native code and something not exposed the same way for enumeration.
I found this answer when I was getting a similar error for nodeName
after upgrading to Bootstrap 4. The issue was that the tabs didn't have the nav
and nav-tab
classes; adding those to the <ul>
element fixed the issue.
Here is a simpler method for batch scripts
@echo off
goto %PROCESSOR_ARCHITECTURE%
:AMD64
echo AMD64
goto :EOF
:x86
echo x86
goto :EOF
No need to initial value
! Because if no initial value
is passed, the callback function
is not invoked on the first element of the list, and the first element is instead passed as the initial value
. Very cOOl feature :)
[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1
Use this manual http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/ This guide really helped me. It is important to observe a sequence of certificates in the store. For example: import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
if you need to you can cast the dtype
back again calling astype(int)
on the column
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index
.
The second problem you have is that you don't have the variable index
.
What you can do is a loop with 12 iterations to fill all your arrays. (and index
will be your iteration variable)
I just give it a shot:
In [9]: s = Series([True, True, True, False])
In [10]: s
Out[10]:
0 True
1 True
2 True
3 False
In [11]: -s
Out[11]:
0 False
1 False
2 False
3 True
If you are calling from within Stored Procedure don't use @. In my case it returns 0
CALL SP_NAME(L_OUTPUT_PARAM)
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
You can get the path of sdcard from this code:
File extStore = Environment.getExternalStorageDirectory();
Then specify the foldername and file name
for e.g:
"/LazyList/"+serialno.get(position).trim()+".jpg"
#btnClear{margin-left:100px;}
Or add a class to the buttons and have:
.yourClass{margin-left:100px;}
This achieves this - http://jsfiddle.net/QU93w/
The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.
The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.
The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.
Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.
The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.
So, yes, the launch screens need to be that size.
The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.
The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.
In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
ASCII was indeed originally conceived as a 7-bit code. This was done well before 8-bit bytes became ubiquitous, and even into the 1990s you could find software that assumed it could use the 8th bit of each byte of text for its own purposes ("not 8-bit clean"). Nowadays people think of it as an 8-bit coding in which bytes 0x80 through 0xFF have no defined meaning, but that's a retcon.
There are dozens of text encodings that make use of the 8th bit; they can be classified as ASCII-compatible or not, and fixed- or variable-width. ASCII-compatible means that regardless of context, single bytes with values from 0x00 through 0x7F encode the same characters that they would in ASCII. You don't want to have anything to do with a non-ASCII-compatible text encoding if you can possibly avoid it; naive programs expecting ASCII tend to misinterpret them in catastrophic, often security-breaking fashion. They are so deprecated nowadays that (for instance) HTML5 forbids their use on the public Web, with the unfortunate exception of UTF-16. I'm not going to talk about them any more.
A fixed-width encoding means what it sounds like: all characters are encoded using the same number of bytes. To be ASCII-compatible, a fixed-with encoding must encode all its characters using only one byte, so it can have no more than 256 characters. The most common such encoding nowadays is Windows-1252, an extension of ISO 8859-1.
There's only one variable-width ASCII-compatible encoding worth knowing about nowadays, but it's very important: UTF-8, which packs all of Unicode into an ASCII-compatible encoding. You really want to be using this if you can manage it.
As a final note, "ASCII" nowadays takes its practical definition from Unicode, not its original standard (ANSI X3.4-1968), because historically there were several dozen variations on the ASCII 127-character repertoire -- for instance, some of the punctuation might be replaced with accented letters to facilitate the transmission of French text. Nowadays all of those variations are obsolescent, and when people say "ASCII" they mean that the bytes with value 0x00 through 0x7F encode Unicode codepoints U+0000 through U+007F. This will probably only matter to you if you ever find yourself writing a technical standard.
If you're interested in the history of ASCII and the encodings that preceded it, start with the paper "The Evolution of Character Codes, 1874-1968" (samizdat copy at http://falsedoor.com/doc/ascii_evolution-of-character-codes.pdf) and then chase its references (many of which are not available online and may be hard to find even with access to a university library, I regret to say).
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.
I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.
https://jsfiddle.net/cgeiser/m0j7Lwyt/1/
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
var filename = window.document.myform.docname.value;
var name = window.document.myform.name.value;
var text = window.document.myform.text.value;
var problem = window.document.myform.problem.value;
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
"Your Name: " + encodeURIComponent(name) + "\n\n" +
"Problem: " + encodeURIComponent(problem) + "\n\n" +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
<input type="text" id="docname" value="test.txt" />
<input type="text" id="name" placeholder="Your Name" />
<div style="display:unblock">
Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
<input type="text" id="problem" />
</div>
<textarea rows=3 cols=50 id="text" />Please type in this box.
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
<input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
</form>
</body>
</html>
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.
void foo(int a)
void foo(int a, float b)
Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override
annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.
class Parent {
void foo(double d) {
// do something
}
}
class Child extends Parent {
@Override
void foo(double d){
// this method is overridden.
}
}
Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)
I had the exact same problem. I couldn't commit, and cleanup would fail.
Using a command-line client I was able to see an error message indicating that it was failing to move a file from .svn/props
to .svn/prop-base
.
I looked at the specific file and found that it was marked read-only. After removing the read-only attribute I was able to cleanup the folder and the commit my changes.
In principle, you can pass any reformatting function to the labels
parameter:
+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %
Or
+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign
Reproducible example:
library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
ggplot(df, aes(x,y)) +
geom_point() +
scale_y_continuous(labels = function(x) paste0(x*100, "%"))
After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.
Please take eye (care) on line return response.json();
where response is not a response - it is promise.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
})
.catch (function (error) {
console.log('Request failed', error);
});
jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42
A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }
Though The above answers are right, I found something more user-friendly approach while using ternary operator.
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
If someone need to work through foreach then,
{% for attachment in attachments %}
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
If you are familiar with nodejs/npm, ttembed-js is an easy way to set the "installable embedding allowed" flag on a TTF font. This will modify the specified .ttf file:
npm install -g ttembed-js
ttembed-js somefont.ttf
align-self-start, align-self-center... in flexbox
.centercol h1{
background: #F2EFE9;
border-left: 3px solid #C6C1B8;
color: #006BB6;
display: block;
align-self: center;
font-weight: normal;
font-size: 18px;
padding: 3px 3px 3px 6px;
}
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
Have you tried?
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Example Link: Webview File Download - Thanks @c49
In addition to bvamos's answer, according to the documentation the use of sem
is deprecated :
NAME ipcrm - remove a message queue, semaphore set or shared memory id SYNOPSIS ipcrm [ -M key | -m id | -Q key | -q id | -S key | -s id ] ... deprecated usage
ipcrm [ shm | msg | sem ] id ...
remove shared memory
us ipcrm -m
to remove a shared memory segment by the id
#!/bin/bash
set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "
for id in $IPCS_M; do
ipcrm -m $id;
done
or ipcrm -M
to remove a shared memory segment by the key
#!/bin/bash
set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "
for id in $IPCS_M; do
ipcrm -M $id;
done
remove message queues
us ipcrm -q
to remove a shared memory segment by the id
#!/bin/bash
set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "
for id in $IPCS_Q; do
ipcrm -q $id;
done
or ipcrm -Q
to remove a shared memory segment by the key
#!/bin/bash
set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "
for id in $IPCS_Q; do
ipcrm -Q $id;
done
remove semaphores
us ipcrm -s
to remove a semaphore segment by the id
#!/bin/bash
set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "
for id in $IPCS_S; do
ipcrm -s $id;
done
or ipcrm -S
to remove a semaphore segment by the key
#!/bin/bash
set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "
for id in $IPCS_S; do
ipcrm -S $id;
done
As mentioned above @NotNull
does nothing on its own. A good way of using @NotNull
would be using it with Objects.requireNonNull
public class Foo {
private final Bar bar;
public Foo(@NotNull Bar bar) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
}
}
The package name is used for unique identification for your application.
Android uses the package name to determine if the application has been installed or not.
The general naming is:
com.companyname.applicationname
eg:
com.android.Camera
Found all answers useful, just wanted to add one more use case.
In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.
As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.
You can use either of the following:
include "class.twitter.php";
or
require "class.twitter.php";
Using require
(or require_once
if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include
will only raise a warning. See http://php.net/require and http://php.net/include for more details
There is an Open Source java library MgntUtils that has a Utility that converts Strings to unicode sequence and vise versa:
result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);
The output of this code is:
\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World
The library can be found at Maven Central or at Github It comes as maven artifact and with sources and javadoc
Here is javadoc for the class StringUnicodeEncoderDecoder
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
XML code
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="5dp"
app:contentPadding="25dp"
app:cardBackgroundColor="#e4bfef"
app:cardElevation="4dp"
app:cardMaxElevation="6dp" />
From the code
CardView card = findViewById(R.id.card_view_top);
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));
The best thing is to go to your phpmyadmin folder and open config.inc.php and change allownopassword=false to $cfg['Servers'][$i]['AllowNoPassword'] = true;
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
if you are using width
and height
, you should try margin-right: 45%;
... it is 100% working for me.. so i can take it to anywhere with percentage!
Type in your URL localhost/[name of your folder in htdocs]
: this is one way to comment
As a result:
:: this will also work
:; so will this
:! and this
Above styles work outside codeblocks, otherwise:
REM is another way to comment.
Shift + Insert usually works throughout X11.
Well, any specific reason to not make Proxy its own struct?
Anyway you have 2 options:
The proper way, simply move proxy to its own struct, for example:
type Configuration struct {
Val string
Proxy Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
fmt.Println(c.Proxy.Address)
}
The less proper and ugly way but still works:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
In bash:
ls -d */
Will list all directories
ls -ld */
will list all directories in long form
ls -ld */ .*/
will list all directories, including hidden directories, in long form.
I have recently switched to zsh (MacOS Catalina), and found that:
ls -ld */ .*/
no longer works if the current directory contains no hidden directories.
zsh: no matches found: .*/
It will print the above error, but also will fail to print any directories.
ls -ld *(/) .*(/)
Also fails in the same way.
So far I have found that this:
ls -ld */;ls -ld .*/
is a decent workaround. The ;
is a command separator. But it means that if there are no hidden directories, it will list directories, and still print the error for no hidden directories:
foo
bar
zsh: no matches found: .*/
ls
is the shell command for list contents of current directory
-l
is the flag to specify that you want to list in Longford (one item per line + a bunch of other cool information)
-d
is the flag to list all directories "as files" and not recursively
*/
is the argument 'list all files ending in a slash'
*
is a simple regex command for "anything", so */
is asking the shell to list "anything ending in '/'"
See man ls
for more information.
I put this:
alias lad="ls -ld */;ls -ld .*/"
in my .zshrc, and it seems to work fine.
NOTE: I've also discovered that
ls -ld .*/ 2> /dev/null
doesn't work, as it still prints sterr to the terminal. I'll update my answer if/when I find a solution.
Use static_cast<int>
:
int num = static_cast<int>(letter); // if letter='a', num=97
Edit: You probably should try to avoid to use (int)
int num = (int) letter;
check out Why use static_cast<int>(x) instead of (int)x? for more info.
It seems Google have updated their docs since all these answers, so hopefully this will help someone else in future :) Just came across this question myself, while creating a new (new new) project.
TL;DR: drawables may be stripped out as part of dp-specific resource optimisation. Mipmaps will not be stripped.
Different home screen launcher apps on different devices show app launcher icons at various resolutions. When app resource optimization techniques remove resources for unused screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale a lower-resolution icon for display. To avoid these display issues, apps should use the
mipmap/
resource folders for launcher icons. The Android system preserves these resources regardless of density stripping, and ensures that launcher apps can pick icons with the best resolution for display.
(from http://developer.android.com/tools/projects/index.html#mipmap)
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
for people who need CGO enabled and cross compile from OSX targeting windows
I needed CGO enabled while compiling for windows from my mac since I had imported the https://github.com/mattn/go-sqlite3 and it needed it. Compiling according to other answers gave me and error:
/usr/local/go/src/runtime/cgo/gcc_windows_amd64.c:8:10: fatal error: 'windows.h' file not found
If you're like me and you have to compile with CGO. This is what I did:
1.We're going to cross compile for windows with a CGO dependent library. First we need a cross compiler installed like mingw-w64
brew install mingw-w64
This will probably install it here /usr/local/opt/mingw-w64/bin/
.
2.Just like other answers we first need to add our windows arch to our go compiler toolchain now. Compiling a compiler needs a compiler (weird sentence) compiling go compiler needs a separate pre-built compiler. We can download a prebuilt binary or build from source in a folder eg: ~/Documents/go
now we can improve our Go compiler, according to top answer but this time with CGO_ENABLED=1
and our separate prebuilt compiler GOROOT_BOOTSTRAP
(Pooya is my username):
cd /usr/local/go/src
sudo GOOS=windows GOARCH=amd64 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
sudo GOOS=windows GOARCH=386 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
3.Now while compiling our Go code use mingw
to compile our go file targeting windows with CGO enabled:
GOOS="windows" GOARCH="386" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/i686-w64-mingw32-gcc" go build hello.go
GOOS="windows" GOARCH="amd64" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc" go build hello.go
I had a similar problem with pip and easy_install:
Cannot fetch index base URL https://pypi.python.org/simple/
As suggested in the referenced blog post, there must be an issue with some older versions of OpenSSL being incompatible with pip 1.3.1.
Installing pip-1.2.1 is a working workaround.
[Edit]:
This definitely happens in RHEL/CentOS 4 distros
Try restarting the terminal, I had the same issue, worked after restarting the terminal.
In my opinion the most readable version
public enum PIN_PULL_RESISTANCE {
PULL_UP {
@Override
public int getValue() {
return 1;
}
},
PULL_DOWN {
@Override
public int getValue() {
return 0;
}
};
public abstract int getValue();
}
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
//delay callback function_x000D_
function delay (seconds, callback){_x000D_
setTimeout(() =>{_x000D_
console.log('The long delay ended');_x000D_
callback('Task Complete');_x000D_
}, seconds*1000);_x000D_
}_x000D_
//Execute delay function_x000D_
delay(1, res => { _x000D_
console.log(res); _x000D_
})
_x000D_