I found this question and none of the solutions here worked for me. I found another solution that got rid of the gaps below images in Chrome. I had to add line-height:0;
to the img selector in my CSS and the gaps below images went away.
Crazy that this problem persists in browsers in 2013.
Try this - You have to import java.util.regex.*;
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(string);
boolean check = matcher.find();
String str = matcher.replaceAll(" ");
Where string
is your string on which you need to remove duplicate white spaces
No special escape sequence is required: you can just type the space directly:
if (char_i_want_to_test == ' ') {
// Do something because it is space
}
In ASCII, space is code 32, so you could specify space by '\x20'
or even 32
, but you really shouldn't do that.
Aside: the word "whitespace" is a catch all for space, tab, newline, and all of that. When you're referring specifically to the ordinary space character, you shouldn't use the term.
In Android Studio:
I removed git clone and just retain the url only and it worked!!
For leading and trailing whitespace:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
Here is my suggested validation:
var isValid = false;
// Check whether this entered value is numeric.
function checkNumeric() {
var numericVal = document.getElementById("txt_numeric").value;
if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
alert("Please, enter a numeric value!");
isValid = false;
} else {
isValid = true;
}
}
<?php
echo "<p>hello\n";
echo "world</p>";
echo "\n\n";
echo "<p>\n\tindented\n</p>\n";
echo "
<div>
easy formatting<br />
across multiple lines!
</div>
";
?>
<p>hello
world</p>
<p>
indented
</p>
<div>
easy formatting<br />
across multiple lines!
</div>
Something in the lines of
myString.split("\\s+");
This groups all white spaces as a delimiter.
So if I have the string:
"Hello[space character][tab character]World"
This should yield the strings "Hello"
and "World"
and omit the empty space between the [space]
and the [tab]
.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal "\s"
, which means, you need to pass "\\s"
. It can get a bit confusing.
The \\s
is equivalent to [ \\t\\n\\x0B\\f\\r]
.
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
While personally I would be preferring !str.isBlank()
, as others already suggested (or str -> !str.isBlank()
as a Predicate), a more modern and efficient version of the str.trim()
approach mentioned above, would be using str.strip()
- considering nulls as "whitespace":
if (str != null && str.strip().length() > 0) {...}
For example as Predicate, for use with streams, e. g. in a unit test:
@Test
public void anyNonEmptyStrippedTest() {
String[] strings = null;
Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}
It is best to also quote $1:
sed -i.bak 's/[[:blank:]]*$//' "$1"
I think you are talking about padding strings with spaces.
One way to do this is with string format codes.
For example, if you want to pad a string to a certain length with spaces, use something like this:
String padded = String.format("%-20s", str);
In a formatter, %
introduces a format sequence. The -
means that the string will be left-justified (spaces will be added on the right of the string). The 20
means the resulting string will be 20 characters long. The s
is the character string format code, and ends the format sequence.
I was trying the white-space: pre-wrap;
technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre>
tags and the following css and everything was good to go..
pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}
VB.NET
Linha.Split(" ").ToList().Where(Function(x) x <> " ").ToArray
C#
Linha.Split(" ").ToList().Where(x => x != " ").ToArray();
Enjoy the power of LINQ =D
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
/^(?!\s*$).+/
You can test this out at regex101
Those settings (core.whitespace
and apply.whitespace
) are not there to remove trailing whitespace but to:
core.whitespace
: detect them, and raise errors apply.whitespace
: and strip them, but only during patch, not "always automatically"I believe the git hook pre-commit
would do a better job for that (includes removing trailing whitespace)
Note that at any given time you can choose to not run the pre-commit
hook:
git commit --no-verify .
cd .git/hooks/ ; chmod -x pre-commit
Warning: by default, a pre-commit
script (like this one), has not a "remove trailing" feature", but a "warning" feature like:
if (/\s$/) {
bad_line("trailing whitespace", $_);
}
You could however build a better pre-commit
hook, especially when you consider that:
Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.
For instance, oldman proposes in another answer a pre-commit
hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md
(markdown) files!
For version 3 there doesn't appear to be "bootstrap" way to achieve this neatly.
A panel
, a well
and a form-group
all provide some vertical spacing.
A more formal specific vertical spacing solution is, apparently, on the roadmap for bootstrap v4
https://github.com/twbs/bootstrap/issues/4286#issuecomment-36331550 https://github.com/twbs/bootstrap/issues/13532
In Visual Studio vesrion 1.34.0
View -> Toggle Render Whitespace
Using a regex
#include <regex>
#include <string>
string trim(string s) {
regex e("^\\s+|\\s+$"); // remove leading and trailing spaces
return regex_replace(s, e, "");
}
Credit to: https://www.regular-expressions.info/examples.html for the regex
map(lambda s: s.strip(), mylist)
would be a little better than explicitly looping. Or for the whole thing at once: map(lambda s:s.strip(), string.split(','))
Don't miss Tab policy for both of * Spaces only * Use spaces to indent wrapped lines
I checked only the latter thing and left the Combobox as Tabs Only which kept failing CheckStyle.. FYI, I'm talking about Preferences > Java > Formatter > Edit...
On the truth, if think that you want something like this:
preg_replace('/\n+|\t+|\s+/',' ',$string);
I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.
EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.
You should try different approaches and see what is best for you: you might not have any performance issues at all.
This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration
As stated, git diff -b
or git diff --ignore-space-change
will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:
git config --global core.whitespace trailing-space
In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:
git diff --ignore-cr-at-eol
or
git config --global core.whitespace cr-at-eol
from here.
You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.
For your purpose you can use this snnippet:
import org.apache.commons.lang3.StringUtils;
StringUtils.normalizeSpace(string);
This will normalize the spacing to single and will strip off the starting and trailing whitespaces as well.
String sampleString = "Hello world!";
sampleString.replaceAll("\\s{2}", " "); // replaces exactly two consecutive spaces
sampleString.replaceAll("\\s{2,}", " "); // replaces two or more consecutive white spaces
Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces
.
Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces
.
Edit:
Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.
Addressing Steven's comment to Sam Dufel's answer
Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?
This should do the trick:
/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
See this page for all the different variations of 'cats' that this matches.
You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.
A browser isn't going to show you white space reliably. I recommend the Linux 'od' command to see what's really in there. Comforming XML parsers will respect all of the methods you listed.
As per your question if you want add spaces more than one in string resources their are many option to add spaces between character or word :
1.By default one space you can add directly in string resource file it working fine. but if give more than one space inside string resources file then it exclude that spaces. eg . -4, 5, -5, 6, -6,
If you want add more extra spaces inside string resource file then uses:- i. adding unicode after character like
<string name="test">-4,  5,  -5,  6,  -6,</string>
ii.you can use "\u0020"
<string name="test">-4,\u0020\u0020 5,\u0020\u00205 -5,\u0020\u00205 6,\u0020\u00205 -6,</string>
This one does a little bit more. I use it to rename my downloaded torrents (no special characters (non-ASCII), spaces, multiple dots, etc.).
#!/usr/bin/perl
&rena(`find . -type d`);
&rena(`find . -type f`);
sub rena
{
($elems)=@_;
@t=split /\n/,$elems;
for $e (@t)
{
$_=$e;
# remove ./ of find
s/^\.\///;
# non ascii transliterate
tr [\200-\377][_];
tr [\000-\40][_];
# special characters we do not want in paths
s/[ \-\,\;\?\+\'\"\!\[\]\(\)\@\#]/_/g;
# multiple dots except for extension
while (/\..*\./)
{
s/\./_/;
}
# only one _ consecutive
s/_+/_/g;
next if ($_ eq $e ) or ("./$_" eq $e);
print "$e -> $_\n";
rename ($e,$_);
}
}
In Java:
String str = " hello world ";
// prints "hello world"
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));
Using sed:
T=$(printf "\t")
sed "s/[[:blank:]]\+/$T/g"
or
sed "s/[[:space:]]\+/$T/g"
This sounds like an output formatting issue? If using SQL Plus, use the COLUMN command like this (assuming you want a maximum display width of 20 chars for each):
column a format a20
column b format a20
select a, b from mytable;
I had this issue today and replace / trim did the trick..see below.
update table_foo
set column_bar = REPLACE(LTRIM(RTRIM(column_bar)), ' ', '')
before and after :
old-bad: column_bar | New-fixed: column_bar
' xyz ' | 'xyz'
' xyz ' | 'xyz'
' xyz ' | 'xyz'
' xyz ' | 'xyz'
' xyz ' | 'xyz'
' xyz ' | 'xyz'
In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:
.wrapper{_x000D_
width: 290px; _x000D_
white-space: no-wrap;_x000D_
resize:both;_x000D_
overflow:auto; _x000D_
border: 1px solid gray;_x000D_
}_x000D_
_x000D_
.breakable-text{_x000D_
display: inline;_x000D_
white-space: no-wrap;_x000D_
}_x000D_
_x000D_
.no-break-before {_x000D_
padding-left: 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>‍<span class="no-break-before">TOGETHER</span>_x000D_
</div>
_x000D_
Use mysz.replaceAll("\\s+","");
CTRL+SHIFT+* is the de-facto standard key combination for showing/hiding whitespace characters in all Microsoft products that support this feature.
P.S: * refers to 8- * key, not to numeric keypad * key.
Settings ->
Preference ->
Edit Components (tab) ->
Tab Setting (group) ->
Replace by space
In version 5.6.8 (and above):
Settings ->
Preferences... ->
Language Menu/Tab Settings ->
Tab Settings (group) ->
Replace by space
If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
word = ' Hello World '
stripped = word.strip()
print(stripped)
>>> value=42
>>> print "Value is %s"%('"'+str(value)+'"')
Value is "42"
The cleanest way to fix this is to apply the vertical-align: top
property to you CSS rules:
#div1 div {
width:30px;height:30px;
border:blue 1px solid;
display:inline-block;
*display:inline;zoom:1;
margin:0px;outline:none;
vertical-align: top;
}
If you were to add content to your div
's, then using either line-height: 0
or font-size: 0
would cause problems with your text layout.
See fiddle: http://jsfiddle.net/audetwebdesign/eJqaZ/
This problem can arise when a browser is in "quirks" mode. In this example, changing the doctype from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
to
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
will change how the browser deals with extra whitespace.
In quirks mode, the whitespace is ignored, but preserved in strict mode.
References:
https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps
For php there is also an option:
I had huge difficulty getting this to work for a shell variable containing a filename with whitespace. For some reason using:
file="foo bar/baz"
scp [email protected]:"'$file'"
as in @Adrian's answer seems to fail.
Turns out that what works best is using a parameter expansion to prepend backslashes to the whitespace as follows:
file="foo bar/baz"
file=${file// /\\ }
scp [email protected]:"$file"
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
highlight search
:set hlsearch
in .vimrc
that is
and search for space tabs and carriage returns
/ \|\t\|\r
or search for all whitespace characters
/\s
of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)
/\S
to show all trailing white space characters - at the end of the line
/\s$
for /f "usebackq tokens=*" %%a in (`echo %StringWithLeadingSpaces%`) do set StringWithout=%%a
This is very simple. for
without any parameters considers spaces to be delimiters; setting "*" as the tokens
parameter causes the program to gather up all the parts of the string that are not spaces and place them into a new string into which it inserts gaps of its own.
#!/bin/bash
dirtys=()
for folder in *
do
if [ -d "$folder" ]; then
dirtys=("${dirtys[@]}" "$folder")
fi
done
for dir in "${dirtys[@]}"
do
for file in "$dir"/\*.mov # <== *.mov
do
#dir_e=`echo "$dir" | sed 's/[[:space:]]/\\\ /g'` -- This line will replace each space into '\ '
out=`echo "$file" | sed 's/\(.*\)\/\(.*\)/\2/'` # These two line code can be written in one line using multiple sed commands.
out=`echo "$out" | sed 's/[[:space:]]/_/g'`
#echo "ffmpeg -i $out_e -sameq -vcodec msmpeg4v2 -acodec pcm_u8 $dir_e/${out/%mov/avi}"
`ffmpeg -i "$file" -sameq -vcodec msmpeg4v2 -acodec pcm_u8 "$dir"/${out/%mov/avi}`
done
done
The above code will convert .mov files to .avi. The .mov files are in different folders and the folder names have white spaces too. My above script will convert the .mov files to .avi file in the same folder itself. I don't know whether it help you peoples.
Case:
[sony@localhost shell_tutorial]$ ls
Chapter 01 - Introduction Chapter 02 - Your First Shell Script
[sony@localhost shell_tutorial]$ cd Chapter\ 01\ -\ Introduction/
[sony@localhost Chapter 01 - Introduction]$ ls
0101 - About this Course.mov 0102 - Course Structure.mov
[sony@localhost Chapter 01 - Introduction]$ ./above_script
... successfully executed.
[sony@localhost Chapter 01 - Introduction]$ ls
0101_-_About_this_Course.avi 0102_-_Course_Structure.avi
0101 - About this Course.mov 0102 - Course Structure.mov
[sony@localhost Chapter 01 - Introduction]$ CHEERS!
Cheers!
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//it work fine with any spaces
*don't forget space in sting b
I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter
throws at you.
You can have VSCode automatically trim whitespaces from an entire file using
the keyboard chord.
CTRL+K / X (by default)
I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.
Ad 1) To see white spaces you could directly call print.data.frame
with modified arguments:
print(head(iris), quote=TRUE)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 "5.1" "3.5" "1.4" "0.2" "setosa"
# 2 "4.9" "3.0" "1.4" "0.2" "setosa"
# 3 "4.7" "3.2" "1.3" "0.2" "setosa"
# 4 "4.6" "3.1" "1.5" "0.2" "setosa"
# 5 "5.0" "3.6" "1.4" "0.2" "setosa"
# 6 "5.4" "3.9" "1.7" "0.4" "setosa"
See also ?print.data.frame
for other options.
You can use this
char name[20];
scanf("%20[^\n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("\n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^\n]", variable);
}
char name[20];
getText("Your name", name, 20);
Why don't you check if text.trim() has a different length? :
if(text.length() == text.trim().length() || otherConditions){
//your code
}
To remove whitespace from only the beginning and end of a string in Swift:
string.trimmingCharacters(in: .whitespacesAndNewlines)
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
The best way to get filetype-specific indentation is to use filetype plugin indent on
in your vimrc. Then you can specify things like set sw=4 sts=4 et
in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).
You can try:
if(Character.isSpaceChar(ch))
{
// Do something...
}
Or:
if((int) ch) == 32)
{
// Do something...
}
import re
s = "many fancy word \nhello \thi"
re.split('\s+', s)
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
Simplest answer if your browser supports the trim()
function
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
I'm assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.
if(str.strip()):
print("string is not empty")
else:
print("string is empty")
Note this does not check for None
A simple way to remove spaces from the whole string is to use the explode function and print the whole string using a for loop.
$text = $_POST['string'];
$a=explode(" ", $text);
$count=count($a);
for($i=0;$i<$count; $i++){
echo $a[$i];
}
Here is a function to do what you want. It should take care of degenerate cases where the string is all whitespace. You must pass in an output buffer and the length of the buffer, which means that you have to pass in a buffer that you allocate.
void str_trim(char *output, const char *text, int32 max_len)
{
int32 i, j, length;
length = strlen(text);
if (max_len < 0) {
max_len = length + 1;
}
for (i=0; i<length; i++) {
if ( (text[i] != ' ') && (text[i] != '\t') && (text[i] != '\n') && (text[i] != '\r')) {
break;
}
}
if (i == length) {
// handle lines that are all whitespace
output[0] = 0;
return;
}
for (j=length-1; j>=0; j--) {
if ( (text[j] != ' ') && (text[j] != '\t') && (text[j] != '\n') && (text[j] != '\r')) {
break;
}
}
length = j + 1 - i;
strncpy(output, text + i, length);
output[length] = 0;
}
The if statements in the loops can probably be replaced with isspace(text[i]) or isspace(text[j]) to make the lines a little easier to read. I think that I had them set this way because there were some characters that I didn't want to test for, but it looks like I'm covering all whitespace now :-)
Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation
I'm not sure exactly how to use it.
Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).
You need to create a new indent level after each colon:
for x in range(0, 50):
print x
print 2*x
print x
In this code, the first two print
statements are "inside" the body of the for
statement because they are indented more than the line containing the for
. The third print
is outside because it is indented less than the previous (nonblank) line.
If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.
Finally, certain statements, like lambda
feature a colon, but cannot have a multiline block as the body.
NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.
#include<stdio.h>
int main()
{
int i,size;
char a[100];
fgets(a,100,stdin);;
size = strlen(a);
a[size-1]='\0';
return 0;
}
Update: Updated with help from other users.
Use 'utf8mb4' as encoding to cover all unicode (including emojis)
default: &default
adapter: mysql2
encoding: utf8mb4
collation: utf8mb4_bin
username: <%= ENV.fetch("MYSQL_USERNAME") %>
password: <%= ENV.fetch("MYSQL_PASSWORD") %>
host: <%= ENV.fetch("MYSQL_HOST") %>
(Reference1) (Reference2)
Came across the same issue and in my case (Java project), I had to include all the dependent jars in the project's libraries section.
File -> Project Structure -> Libraries
I had to add my project dependent jars in the above section (for example; project/web/lib/). After doing so, all resolved fine. I hope this will help someone.
You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...
def change
change_column :widgets, :colour, :string, default: 'red'
end
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).
That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:
class Vehicle {
public:
Vehicle(int wheels, std::string name = "Mini");
};
Vehicle x = 5; // this compiles just fine... did you really want it to?
for those looking for a DESC ... this seems to work --sort=-
ty for the formatting, new to this ...my eyes are loosing some of it's bloodshot
git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p) %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=-authordate refs/remotes
further ref: https://stackoverflow.com/a/5188364/10643471
Using .Equals is also a lot easier to read.
Here is a solution that removes all lines that are either blank or contain only space characters:
grep -v '^[[:space:]]*$' foo.txt
With GNU Parallel you can do:
cat file | parallel 'foo {}; foo2 {}; foo3 {}'
This will run one job on each cpu core. To run 50 do:
cat file | parallel -j 50 'foo {}; foo2 {}; foo3 {}'
Watch the intro videos to learn more:
switch($someString.ToLower())
{
{($_ -eq "y") -or ($_ -eq "yes")} { "You entered Yes." }
default { "You entered No." }
}
You can't.
"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."
The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.
You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.
Prasoon has already offered up a host of different (and good) ways to do this, none of which need repeating here. I'd like to suggest an alternative approach for speed however.
If you're going to be doing this quite a bit, you may want to consider "sub-classing" your vector so that a sum of elements is maintained separately (not actually sub-classing vector which is iffy due to the lack of a virtual destructor - I'm talking more of a class that contains the sum and a vector within it, has-a
rather than is-a
, and provides the vector-like methods).
For an empty vector, the sum is set to zero. On every insertion to the vector, add the element being inserted to the sum. On every deletion, subtract it. Basically, anything that can change the underlying vector is intercepted to ensure the sum is kept consistent.
That way, you have a very efficient O(1) method for "calculating" the sum at any point in time (just return the sum currently calculated). Insertion and deletion will take slightly longer as you adjust the total and you should take this performance hit into consideration.
Vectors where the sum is needed more often than the vector is changed are the ones likely to benefit from this scheme, since the cost of calculating the sum is amortised over all accesses. Obviously, if you only need the sum every hour and the vector is changing three thousand times a second, it won't be suitable.
Something like this would suffice:
class UberVector:
private Vector<int> vec
private int sum
public UberVector():
vec = new Vector<int>()
sum = 0
public getSum():
return sum
public add (int val):
rc = vec.add (val)
if rc == OK:
sum = sum + val
return rc
public delindex (int idx):
val = 0
if idx >= 0 and idx < vec.size:
val = vec[idx]
rc = vec.delindex (idx)
if rc == OK:
sum = sum - val
return rc
Obviously, that's pseudo-code and you may want to have a little more functionality, but it shows the basic concept.
The only way to do that with pure javascript is to implement some kind of polling mechanism. You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.
A more efficient way would be to use flash. The flex component FileReference dispatchs periodically a 'progress' event holding the number of bytes already uploaded. If you need to stick with javascript, bridges are available between actionscript and javascript. The good news is that this work has been already done for you :)
This library allows to register a javascript handler on the flash progress event.
This solution has the hudge advantage of not requiring aditionnal resources on the server side.
The accepted answer worked for most browsers but for some reason on iOS Chrome and Safari browsers the content that should have shown second was being hidden. I tried some other steps that forced content to stack on top of each other, and eventually I tried the following solution that gave me the intended effect (switch content display order on mobile screens), without bugs of stacked or hidden content:
.container {
display:flex;
flex-direction: column-reverse;
}
.section1,
.section2 {
height: auto;
}
If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.
substitute:
mMyListView.invalidate();
for:
((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged();
If that doesnt work, refer to this thread: Android List view refresh
function getMatch(elem) {
function action(ele, val) {
if(ele === val){
elem = arr2[i];
}
}
for (var i = 0; i < arr2.length; i++) {
action(elem.id, Object.values(arr2[i])[0]);
}
return elem;
}
var modified = arr1.map(getMatch);
First, thanks for the answers above! They lead to my solution.
I added this alias to my .bashrc file:
alias now='date +%Y-%m-%d-%H.%M.%S'
Now when I want to put a time stamp on a file such as a build log I can do this:
mvn clean install | tee build-$(now).log
and I get a file name like:
build-2021-02-04-03.12.12.log
When you already have all the "pieces" you wish to append, there is no point in using StringBuilder
at all. Using StringBuilder
and string concatenation in the same call as per your sample code is even worse.
This would be better:
return "select id1, " + " id2 " + " from " + " table";
In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:
return "select id1, id2 from table";
Using new StringBuilder().append("select id1, ").append(" id2 ")....toString()
will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.
If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.
I have an article on String
/ StringBuffer
which I wrote a while ago - before StringBuilder
came along. The principles apply to StringBuilder
in the same way though.
This falls into workaround category, containing some extra information too:
Since the notifications are handled differently depending on the state of the app (foreground/background/not launched) I've seen the best way to implement a helper class where the selected activity is launched based on the custom data sent in the notification message.
This way you do not need the click_action or intent filter specific to it. Also you write the code just once and can reasonably easily start any activity.
So the minimum custom data would look something like this:
Key: run_activity
Value: com.mypackage.myactivity
And the code for handling it:
if (intent.hasExtra("run_activity")) {
handleFirebaseNotificationIntent(intent);
}
private void handleFirebaseNotificationIntent(Intent intent){
String className = intent.getStringExtra("run_activity");
startSelectedActivity(className, intent.getExtras());
}
private void startSelectedActivity(String className, Bundle extras){
Class cls;
try {
cls = Class.forName(className);
}catch(ClassNotFoundException e){
...
}
Intent i = new Intent(context, cls);
if (i != null) {
i.putExtras(extras);
this.startActivity(i);
}
}
That is the code for the last two cases, startSelectedActivity would be called also from onMessageReceived (first case).
The limitation is that all the data in the intent extras are strings, so you may need to handle that somehow in the activity itself. Also, this is simplified, you probably don't what to change the Activity/View on an app that is on the foreground without warning your user.
use the below line
e2.setSelection(e2.length());
e2
is edit text Object Name
Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object)
.
Here is a simple example:
Entry<String, String> entry = Map.entry("foo", "bar");
As it is immutable, calling setValue
will throw an UnsupportedOperationException
. The other limitations are the fact that it is not serializable and null
as key or value is forbidden, if it is not acceptable for you, you will need to use AbstractMap.SimpleImmutableEntry
or AbstractMap.SimpleEntry
instead.
NB: If your need is to create directly a Map
with 0 to up to 10 (key, value) pairs, you can instead use the methods of type Map.of(K key1, V value1, ...)
.
#include <iomanip>
#include <iostream>
int main()
{
double num1 = 3.12345678;
std::cout << std::fixed << std::showpoint;
std::cout << std::setprecision(2);
std::cout << num1 << std::endl;
return 0;
}
I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.
Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.
You may compiling your program while another program may be running in background. Firstly, see if another program is running .Close it and then try ro compile.
Compatible with: Xcode 6.0.1+
You can create an empty array by specifying the Element type of your array in the declaration.
For example:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Example from the apple developer page (Array):
Hope this helps anyone stumbling onto this page.
If you know that you won't have an empty field (,,) then this expression works well:
("[^"]*"|[^,]+)
As in the following example...
Set rx = new RegExp
rx.Pattern = "(""[^""]*""|[^,]+)"
rx.Global = True
Set col = rx.Execute(sText)
For n = 0 to col.Count - 1
if n > 0 Then s = s & vbCrLf
s = s & col(n)
Next
However, if you anticipate an empty field and your text is relatively small than you might consider replacing the empty fields with a space prior to parsing to ensure that they are captured. For example...
...
Set col = rx.Execute(Replace(sText, ",,", ", ,"))
...
And if you need to maintain the integrity of the fields, you can restore the commas and test for empty spaces inside the loop. This may not be the most efficient method but it gets the job done.
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc
by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
.
to my /home/xy/.bashrc
file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH
variable, by run -> edit Configuration.
I got the following error using Docker 19.03.8 on CentOS 7:
COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory
The solution for me was to build from Docker file with docker build .
instead of docker build - < Dockerfile
.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
The acepted Answer is very detailed and correct in most of the cases.
I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.
To solve it, i made this PHP function:
function load_utf8_file($filePath)
{
$response = null;
try
{
if (file_exists($filePath)) {
$text = file_get_contents($filePath);
$response = preg_replace("/^\xEF\xBB\xBF/", '', $text);
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
}
finally{ }
return $response;
}
Then i use it like this to load a JSON file and get a value from it:
$str = load_utf8_file('appconfig.json');
$json = json_decode($str, true);
//print_r($json);
echo $json['prod']['deploy']['hostname'];
char*
is a mutable pointer to a mutable character/string.
const char*
is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char *
to char*
is deprecated.
char* const
is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable.
const char* const
is an immutable pointer to an immutable character/string.
I dont know if you want to achieve that in js or java, in js the simplest way to get the unix timestampt (this is time in seconds from 1/1/1970) it's as follows:
var myDate = new Date();
console.log(+myDate); // +myDateObject give you the unix from that date
You can accomplish the same using the extended choice parameter plugin before mentioned by malenkiy_scot and a simple php script as follows(assuming you have somewhere a server to deploy php scripts that you can hit from the Jenkins machine)
<?php
chdir('/path/to/repo');
exec('git branch -r', $output);
print('branches='.str_replace(' origin/','',implode(',', $output)));
?>
or
<?php
exec('git ls-remote -h http://user:[email protected]', $output);
print('branches='.preg_replace('/[a-z0-9]*\trefs\/heads\//','',implode(',', $output)));
?>
With the first option you would need to clone the repo. With the second one you don't, but in both cases you need git installed in the server hosting your php script. Whit any of this options it gets fully dynamic, you don't need to build a list file. Simply put the URL to your script in the extended choice parameter "property file" field.
chmod +w <directory>
There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
There are two ways to do this, depending on your Bash version.
The classic and portable (Bash pre-4) way is:
cmd >> outfile 2>&1
A nonportable way, starting with Bash 4 is
cmd &>> outfile
(analog to &> outfile
)
For good coding style, you should
If your script already starts with #!/bin/sh
(no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.
Also remember that Bash 4 &>>
is just shorter syntax — it does not introduce any new functionality or anything like that.
The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output
If you use the conditional(ternary) operator the compiler needs an implicit conversion between both types, otherwise you get an exception.
So you could fix it by casting one of both to System.Object
:
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;
But since the result is not really pretty and you always have to remember this casting, you could use such an extension method instead:
public static object GetDBNullOrValue<T>(this T val)
{
bool isDbNull = true;
Type t = typeof(T);
if (Nullable.GetUnderlyingType(t) != null)
isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
else if (t.IsValueType)
isDbNull = false;
else
isDbNull = val == null;
return isDbNull ? DBNull.Value : (object) val;
}
Then you can use this concise code:
planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call. Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'. Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
Based on existing responses on this post, this simplify the implementation :)
namespace System
{
public static class BaseTypesExtensions
{
/// <summary>
/// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
/// </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
}
}
[project properties dialog]
For development using VisualStudio 2017 and a NetCore API-project:
1) In Cmd-Box: ipconfig /all to determine IP-address
2a) Enter the retrieved IP-address in Project properties-> Debug Tab
2b) Select a Port and attach that to the IP-address from step 2a.
3) Add an allow rule in the firewall to allow incoming TCP-traffic on the selected Port (my firewall triggered with a dialog: "Block or add rule to firewall"). Add will in that case do the trick.
Disadvantage of the solution above:
1) If you use a dynamic IP-address you need to redo the steps above in case another IP-address has been assigned.
2) You server has now an open Port which you might forget, but this open port remains an invitation for unwanted guests.
You could also use a StringVar
variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
I had the same error after I posted a form of mine. they have a space in to my input name attributes. input name=' first_name'
Fixing that got rid of the error.
Don't forget that we have the slide to back gesture now. You probably want to remove this as well. Don't forget to enable it back again if necessary.
if ([self.navigationItem respondsToSelector:@selector(hidesBackButton)]) {
self.navigationItem.hidesBackButton = YES;
}
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
Setting position: absolute
and then transform: rotate(45deg)
will provide a background:
div {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
outline: 2px dashed slateBlue;_x000D_
overflow: hidden;_x000D_
}_x000D_
div img {_x000D_
position: absolute;_x000D_
transform: rotate(45deg);_x000D_
z-index: -1;_x000D_
top: 40px;_x000D_
left: 40px;_x000D_
}
_x000D_
<div>_x000D_
<img src="https://placekitten.com/120/120" />_x000D_
<h1>Hello World!</h1>_x000D_
</div>
_x000D_
In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop
. An alternative to photoshop
for rotating images is online tool too for rotating images. Once rotated, I'm working with the rotated-image
in the background
property.
div.with-background {
background-image: url(/img/rotated-image.png);
background-size: contain;
background-repeat: no-repeat;
background-position: top center;
}
Good Luck...
You can't use $(this)
since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide()
. There's no reason to test to see if the class exists.
I had an old Excel database with "human-readable" dates, like 2010.03.28 20:12:30 Theese dates were in UTC+1 (CET) and needed to convert it to epoch time.
I used the =(A4-DATE(1970;1;1))*86400-3600 formula to convert the dates to epoch time from the A column to B column values. Check your timezone offset and make a math with it. 1 hour is 3600 seconds.
The only thing why i write here an anwser, you can see that this topic is more than 5 years old is that i use the new Excel versions and also red posts in this topic, but they're incorrect. The DATE(1970;1;1). Here the 1970 and the January needs to be separated with ; and not with ,
If you're also experiencing this issue, hope it helps you. Have a nice day :)
Just verified this today, but if you are trying to open a Facebook page, you can use "fb://page/{Page ID}"
Page ID can be found under your page in the about section near the bottom.
Specific to my use case, in Xamarin.Forms, you can use this snippet to open in the app if available, otherwise in the browser.
Device.OpenUri(new Uri("fb://page/{id}"));
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
# dump into file
pg_dump myDB > /tmp/myDB.sql
# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql
# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";'
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
# see the result
psql myDB -c "SHOW LC_COLLATE"
If you don't care about supporting old browsers, you can use :not()
to exclude that element:
.parent:hover span:not(:hover) {
border: 10px solid red;
}
Demo: http://jsfiddle.net/vz9A9/1/
If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:
.parent span:hover {
border: 10px solid green;
}
This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.
In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:
<img v-bind:src="`${imgPreUrl()}img/logo.png`">
I know this is old, but I did not see this response.
In the window (xaml) add:
Deactivated="Window_Deactivated"
In the code behind for Window_Deactivated:
private void Window_Deactivated(object sender, EventArgs e)
{
Window window = (Window)sender;
window.Activate();
}
This will keep your window on top.
I rewrote the @Udinic answer so that the code generates table creation query automatically. It also doesn't need ConnectionSource
. It also has to do this inside a transaction.
public static String getOneTableDbSchema(SQLiteDatabase db, String tableName) {
Cursor c = db.rawQuery(
"SELECT * FROM `sqlite_master` WHERE `type` = 'table' AND `name` = '" + tableName + "'", null);
String result = null;
if (c.moveToFirst()) {
result = c.getString(c.getColumnIndex("sql"));
}
c.close();
return result;
}
public List<String> getTableColumns(SQLiteDatabase db, String tableName) {
ArrayList<String> columns = new ArrayList<>();
String cmd = "pragma table_info(" + tableName + ");";
Cursor cur = db.rawQuery(cmd, null);
while (cur.moveToNext()) {
columns.add(cur.getString(cur.getColumnIndex("name")));
}
cur.close();
return columns;
}
private void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) {
db.beginTransaction();
try {
List<String> columnNamesWithoutRemovedOnes = getTableColumns(db, tableName);
// Remove the columns we don't want anymore from the table's list of columns
columnNamesWithoutRemovedOnes.removeAll(Arrays.asList(columnsToRemove));
String newColumnNamesSeparated = TextUtils.join(" , ", columnNamesWithoutRemovedOnes);
String sql = getOneTableDbSchema(db, tableName);
// Extract the SQL query that contains only columns
String oldColumnsSql = sql.substring(sql.indexOf("(")+1, sql.lastIndexOf(")"));
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
db.execSQL("CREATE TABLE `" + tableName + "` (" + getSqlWithoutRemovedColumns(oldColumnsSql, columnsToRemove)+ ");");
db.execSQL("INSERT INTO " + tableName + "(" + newColumnNamesSeparated + ") SELECT " + newColumnNamesSeparated + " FROM " + tableName + "_old;");
db.execSQL("DROP TABLE " + tableName + "_old;");
db.setTransactionSuccessful();
} catch {
//Error in between database transaction
} finally {
db.endTransaction();
}
}
None of the answers provided here are completely correct when using TypeScript, as you may not know the kind of element that is selected.
This would therefore be preferred:
if (document.activeElement instanceof HTMLElement)
document.activeElement.blur();
I would furthermore discourage using the solution provided in the accepted answer, as the resulting blurring is not part of the official spec, and could break at any moment.
If you really want to have a blocking (synchronous) delay
function (for whatsoever), why not do something like this:
<script type="text/javascript">
function delay(ms) {
var cur_d = new Date();
var cur_ticks = cur_d.getTime();
var ms_passed = 0;
while(ms_passed < ms) {
var d = new Date(); // Possible memory leak?
var ticks = d.getTime();
ms_passed = ticks - cur_ticks;
// d = null; // Prevent memory leak?
}
}
alert("2 sec delay")
delay(2000);
alert("done ... 500 ms delay")
delay(500);
alert("done");
</script>
from threading import Thread
from time import sleep
def run(name):
for x in range(10):
print("helo "+name)
sleep(1)
def run1():
for x in range(10):
print("hi")
sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
You change the bundle display name in the info.plist. It's as simple as that.
Changing the 'bundle display name' (as opposed to 'bundle name') is the only way to include characters like '+' in your applications name. Including special characters in the project name will cause an error when uploading to the app store!
The following is what this would look like inside of .draggable({});
$("#yourDraggable").draggable({
revert: "invalid" ,
start: function(){
$(this).css("opacity",0.3);
},
stop: function(){
$(this).draggable( 'disable' )
},
opacity: 0.7,
helper: function () {
$copy = $(this).clone();
$copy.css({
"list-style":"none",
"width":$(this).outerWidth()
});
return $copy;
},
appendTo: 'body',
scroll: false
});
You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector
.class {
margin:20px;
&:hover {
color:yellow;
}
}
For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
// obviously these values might come from somewhere non-trivial
return Index(2, "text");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
// would probably do something non-trivial here with the param values
return View();
}
That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.
I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.
Hope that helps.
One way to 'minimise' the cmd window is to reduce the size of the console using something like...
echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2
You can reduce the COLS to about 18 and the LINES to 1 if you wish. The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.
If you want to do it with a Windows Store App, following by @Hans Kesting and @Jink answer:
string colorcode = "#FFEEDDCC";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
tData.DefaultData = Color.FromArgb((byte)((argb & -16777216) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:
System.Net.ServicePointManager.Expect100Continue = false;
Some servers choke on that header and send back the 417 error you're seeing.
Give that a shot.
I wrote up this handy function to find the mode.
def mode(nums):
corresponding={}
occurances=[]
for i in nums:
count = nums.count(i)
corresponding.update({i:count})
for i in corresponding:
freq=corresponding[i]
occurances.append(freq)
maxFreq=max(occurances)
keys=corresponding.keys()
values=corresponding.values()
index_v = values.index(maxFreq)
global mode
mode = keys[index_v]
return mode
Using Apache ArrayUtils downloadable at this link you can easy use the method
subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive)
"boolean" is only an example, there are methods for all primitives java types
getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.
Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.
If I could suggest setting up your dataframes like this (auto-indexing):
df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})
then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):
s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})
then the result you want is easy:
display (df.merge(s, left_index=True, right_index=True))
Alternatively, just add the new values to your dataframe df:
df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)
Both return:
a b s1 s2
0 NaN 4 5 6
1 1.0 5 5 6
2 2.0 6 5 6
If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:
s1=['a','b','c']
then you can attach this in the same way:
df['s1']=s1
returns:
a b s1
0 NaN 4 a
1 1.0 5 b
2 2.0 6 c
using System.IO;
...
Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.
(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d")
suffices, even if C:\a
does not exist yet.)
Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\
is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA%
or %LOCALAPPDATA%
instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
man you can use the basic Bootstrap Datepicker this way:
<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pickyDate').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
and inside body:
<body>
<div id="testDIV">
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</div>
</div>
</div>
datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.
I got involved whole a day, too! and finally found the solution in shell
command instead of copy: or command: as below:
- hosts: remote-server-name
gather_facts: no
vars:
src_path: "/path/to/source/"
des_path: "/path/to/dest/"
tasks:
- name: Ansible copy files remote to remote
shell: 'cp -r {{ src_path }}/. {{ des_path }}'
strictly notice to:
1. src_path and des_path end by /
symbol
2. in shell command src_path ends by .
which shows all content of directory
3. I used my remote-server-name both in hosts: and execute shell
section of jenkins, instead of remote_src:
specifier in playbook.
I guess it is a good advice to run below command in Execute Shell section in jenkins:
ansible-playbook copy-payment.yml -i remote-server-name
It's possible to debug JavaScript by setting breakpoints in Eclipse using the AJAX Tools Framework.
You can find the list of formats here (in the Double.ToString()-MSDN-Article) as comments in the example section.
It's just as easy as the following:
AND> if+if
if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" *do something*
OR> if // if
set BOTH=0
if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" set BOTH=1
if "%BOTH%"=="0" if "%VAR1%"=="VALUE" *do something*
if "%BOTH%"=="0" if "%VAR2%"=="VALUE" *do something*
I know that there are other answers, but I think that the mine is more simple, so more easy to understand. Hope this helps you! ;)
Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
Essentially you have the following options
FragmentManager.popBackStack(String name,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.getBackStackEntryCount()
/getBackStackEntryAt().getId()
to retrieve the ID of the first entry on the back stack, and
FragmentManager.popBackStack(int id,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
is supposed to pop the entire back stack... I think the documentation for
that is just wrong. (Actually I guess it just doesn't cover the case where
you pass in POP_BACK_STACK_INCLUSIVE
), The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient
class.
HttpClient
is considered the new API and it should replace the old ones (WebClient
and WebRequest
)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
for more information about how to use the HttpClient
class (especially in async cases), you can refer this question
NOTE 1: If you want to use async/await
string url = "page url";
HttpClient client = new HttpClient(); // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
NOTE 2: If use C# 8 features
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
There's this example in the SensioLab page on the for
tag:
<h1>Members</h1>
<ul>
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
</ul>
http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys
You can do this by creating a factory method in MyObject:
class MyObject {
public static MyObject create() {
return new MyObject();
}
}
then mock that with PowerMock.
However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.
In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:
void method1(MyObject obj1) {
obj1.method1();
}
passing in the dependency, which you can easily mock for the unit test.
as i understood it so you won't think the value in memory is changed. in c when you do x++ the value of x in memory changes. but in python all numbers are immutable hence the address that x pointed as still has x not x+1. when you write x++ you would think that x change what really happens is that x refrence is changed to a location in memory where x+1 is stored or recreate this location if doe's not exists.
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
Refreshing db context with Reload is not recommended way due to performance loses. It is good enough and the best practice to initialize a new instance of the dbcontext before each operation executed. It also provide you a refreshed up to date context for each operation.
using (YourContext ctx = new YourContext())
{
//Your operations
}
If pip "says" six is installed but you're still getting:
ImportError: No module named six.moves
try re-installing six (worked for me):
pip uninstall six
pip install six
A general answer
select * from [dbo].[SplitString]('1,2',',') -- Will work
but
select [dbo].[SplitString]('1,2',',') -- will not work and throws this error
I normally have them in an array and call writeBooleanArray
and readBooleanArray
If it's a single boolean you need to pack, you could do this:
parcel.writeBooleanArray(new boolean[] {myBool});
You can use grep -P
(perl regex) supported negative lookbehind
:
grep -P '(?<!g)loom\b' ~/projects/**/trunk/src/**/*.@(h|cpp)
I added \b
for word boundaries.
Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.
Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). Because the Tuple is only holding a reference to that kind of object.
Also - a tuple has its own constructor tuple()
which you can give any iterator. Which means that to create a tuple, you could do:
tuple(i for i in (1,2,3))
var x = from row in table
where row.ID == 0
select row
Supposing you have a DataTable that knows about the rows, other wise you'll need to use the row index:
where row[rowNumber] == 0
In this instance you'd also want to use the select to place the row data into an anonymous class or a preprepared class (if you want to pass it to another method)
If you use the prettier extension in Visual Studio Code, try adding this to the settings.json file:
"editor.insertSpaces": false,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"prettier.tabWidth": 4,
"prettier.useTabs": true // This made it finally work for me
Inspired by an answer of @walid2mi:
(Get-Item 'c:\temp\myfile.txt').Basename
Please note: this only works if the given file really exists.
Most of the answers above should suffice you but if you are doing a lot more of such predicate and complex combinations check out Squeel. You will be able to doing something like:
Topic.where{{forum_id.not_in => @forums.map(&:id)}}
Topic.where{forum_id.not_in @forums.map(&:id)}
Topic.where{forum_id << @forums.map(&:id)}
The @supports rule (92% browser support July 2017) rule can be used for conditional logic on css properties:
@supports (display: -webkit-box) {
.for_older_webkit_browser { display: -webkit-box }
}
@supports not (display: -webkit-box) {
.newer_browsers { display: flex }
}
You can add any iOS
version to support with iOS DiskImage
to you Xcode
from Xcode-iOS-Developer-Disk-Image repository
Xcode
Applications
folderXcode.app
and choose Show Package Contents
menu/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
DeveloperDiskImage.dmg
and DeveloperDiskImage.dmg.signature
filesXcode
Disk image must be in folder like this:
Using calendar module:
Number-to-Abbr
calendar.month_abbr[month_number]
Abbr-to-Number
list(calendar.month_abbr).index(month_abbr)
Using
dependencies:
connectivity: ^0.4.2
what we got from resouces is
import 'package:connectivity/connectivity.dart';
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
Future is little problematic for me, we have to implement it every single time like :
check().then((intenet) {
if (intenet != null && intenet) {
// Internet Present Case
}
// No-Internet Case
});
So to solve this problem i have created a class Which accept a function with boolean isNetworkPresent parameter like this
methodName(bool isNetworkPresent){}
And the Utility Class is
import 'package:connectivity/connectivity.dart'; class NetworkCheck { Future<bool> check() async { var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.mobile) { return true; } else if (connectivityResult == ConnectivityResult.wifi) { return true; } return false; } dynamic checkInternet(Function func) { check().then((intenet) { if (intenet != null && intenet) { func(true); } else{ func(false); } }); } }
And to use connectivity-check utilty
fetchPrefrence(bool isNetworkPresent) {
if(isNetworkPresent){
}else{
}
}
i will use this syntax
NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)
There are two cases in which this error is raised.
The term Duck Typing is a lie.
You see the idiom “If it walks like a duck and quacks like a duck then it is a duck." that is being repeated here time after time.
But that is not what duck typing (or what we commonly refer to as duck typing) is about. All that the Duck Typing we are discussing is about, is trying to force a command on something. Seeing whether something quacks or not, regardless of what it says it is. But there is no deduction about whether the object then is a Duck or not.
For true duck typing, see type classes. Now that follows the idiom “If it walks like a duck and quacks like a duck then it is a duck.". With type classes, if a type implements all the methods that are defined by a type class, it can be considered a member of that type class (without having to inherit the type class). So, if there is a type class Duck which defines certain methods (quack and walk-like-duck), anything that implements those same methods can be considered a Duck (without needing to inherit Duck).
For temporary internal files their are 2 options
1.
File file;
file = File.createTempFile(filename, null, this.getCacheDir());
2.
File file
file = new File(this.getCacheDir(), filename);
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp
by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp
by default) e.g you specify your filename as internal_file
and comes out as internal_file1456345.tmp
. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();
, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
1.Added these codes to at the end of your app/build.gradle:
configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:28.0.0'
// the above lib may be old dependencies version
}
2.Modified sdk and tools version to 28:
compileSdkVersion 28
buildToolsVersion '28.0.3'
targetSdkVersion 28
3.In your AndroidManifest.xml file, you should add two line:
<application
android:name=".YourApplication"
android:appComponentFactory="AnyStrings"
tools:replace="android:appComponentFactory"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
Or Simply
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT: we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
bash:
for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done
I use Git Bash for my Windows.
$ eval $(ssh-agent -s) //activates the connection
$ ssh-add ~/.ssh/id_rsa //adds the identity
$ clip < ~/.ssh/id_rsa.pub //THIS IS THE IMPORTANT ONE. This adds your key to your clipboard. Go back to GitHub and just paste it in, and voilá! You should be good to go.
Here's another method that's unorthodox, but works*.
I recently found myself in a situation where I'd checked in breaking code, knowing that I couldn't update our production code to it until all the integration work had taken place (in retrospect this was a bad decision, but we didn't expect to get stalled out, but other projects took precedence). That was several months ago, and the integration has been stalled for that entire time. Along comes a requirement to change the base code and get it into production last week without the breaking change.
Here's what we did:
After verifying that the new requirement doesn't break anything when using the revision before my check in, I made a copy of the working directory containing the new code. Then I deleted everything in the working directory and checked out the revision I wanted to it. Then I deleted all the files I'd just checked out, and copied in the files from the working copy. Then I committed that change, effectively wiping out the breaking change from the repository and getting the production code in place as the head revision. We still have the breaking change available, but it's no longer in the head revision so we can move forward to production.
*I don't recommend this method, but if you find yourself in a similar situation, it's a way out that's not too painful.
detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)
function onScale(el, callback) {
let hypo = undefined;
el.addEventListener('touchmove', function(event) {
if (event.targetTouches.length === 2) {
let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
(event.targetTouches[0].pageY - event.targetTouches[1].pageY));
if (hypo === undefined) {
hypo = hypo1;
}
callback(hypo1/hypo);
}
}, false);
el.addEventListener('touchend', function(event) {
hypo = undefined;
}, false);
}
I had the same issue. And I tried to reset my keys as everyone said, but it still didn't worked. For was because I renamed the app.
So what I did was to reset my keys and also rename app from console. Check this question for more information: Heroku push app problem
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
Lets take an anchor tag with an onclick event, that calls a Javascript function.
<a href="#" onClick="showDiv(1);">1</a>
Now in javascript write the below code
function showDiv(pageid)
{
alert(pageid);
}
This will show you an alert of "1"....
If your original dataframe df
is not too big, you have no memory constraints, and you only need to keep a few columns, or, if you don't know beforehand the names of all the extra columns that you do not need, then you might as well create a new dataframe with only the columns you need:
new_df = df[['spam', 'sausage']]
The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.
Code:
@font-face {
font-family: Eau_Sans_Bold;
src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND
Answer or Solution.:
@font-face {
font-family: Eau_Sans_Book;
src: url("../fonts/eau_sans_book.otf") format("opentype");
}
Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.
This is how to pass the struct
by reference. This means that your function can access the struct
outside of the function and modify its values. You do this by passing a pointer to the structure to the function.
#include <stdio.h>
/* card structure definition */
struct card
{
int face; // define pointer face
}; // end structure card
typedef struct card Card ;
/* prototype */
void passByReference(Card *c) ;
int main(void)
{
Card c ;
c.face = 1 ;
Card *cptr = &c ; // pointer to Card c
printf("The value of c before function passing = %d\n", c.face);
printf("The value of cptr before function = %d\n",cptr->face);
passByReference(cptr);
printf("The value of c after function passing = %d\n", c.face);
return 0 ; // successfully ran program
}
void passByReference(Card *c)
{
c->face = 4;
}
This is how you pass the struct
by value so that your function receives a copy of the struct
and cannot access the exterior structure to modify it. By exterior I mean outside the function.
#include <stdio.h>
/* global card structure definition */
struct card
{
int face ; // define pointer face
};// end structure card
typedef struct card Card ;
/* function prototypes */
void passByValue(Card c);
int main(void)
{
Card c ;
c.face = 1;
printf("c.face before passByValue() = %d\n", c.face);
passByValue(c);
printf("c.face after passByValue() = %d\n",c.face);
printf("As you can see the value of c did not change\n");
printf("\nand the Card c inside the function has been destroyed"
"\n(no longer in memory)");
}
void passByValue(Card c)
{
c.face = 5;
}
Different types of variable:
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
Therefore, if you are defining a stored program and actually do want a "local variable", you will need to drop the @ character and ensure that your DECLARE statement is at the start of your program block. Otherwise, to use a "user variable", drop the DECLARE statement.
Furthermore, you will either need to surround your query in parentheses in order to execute it as a subquery:
SET @countTotal = (SELECT COUNT(*) FROM nGrams);
Or else, you could use SELECT ... INTO:
SELECT COUNT(*) INTO @countTotal FROM nGrams;
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
First, let's make some test data:
create table client (client_id integer not null primary key auto_increment,
name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
client_id integer references client.id,
cash decimal(10,2),
stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
(1, 10.11, 23.22),
(2, 30.30, 40.40),
(2, 40.40, 50.50);
If you didn't need the portfolio ID, it would be easy:
select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id
+-----------+----------+--------------------+
| client_id | name | max(cash + stocks) |
+-----------+----------+--------------------+
| 1 | John Doe | 33.33 |
| 2 | Jane Doe | 90.90 |
+-----------+----------+--------------------+
Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:
select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id
+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
| 1 | 33.33 |
| 2 | 90.90 |
+-----------+----------+
Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:
select portfolio_id, cash + stocks from portfolio
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
| 5 | 33.33 |
| 6 | 33.33 |
| 8 | 90.90 |
+--------------+---------------+
Finally, we can join to the client table (as you did) in order to include the name of each client:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 1 | John Doe | 6 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Try this for Amazon Linux AMI or for centOS
sudo service mysqld restart
For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32
My issue was the java version 1.7 installed.
You can view all stashes' list by the following command:
$ git stash list
stash@{0}: WIP on dev: ddd4d75 spelling fix
stash@{1}: WIP on dev: 40e65a8 setting width for messages
......
......
......
stash@{12}: WIP on dev: 264fdab added token based auth
Newest stash is the first one.
You can simply select index n
of stash provided in the above list and use the following command to view stashed details
git stash show -p stash@{3}
Similarly,
git stash show -p stash@{n}
You can also check diff by using the command :
git diff HEAD stash@{n} -- /path/to/file
You can use %
:
SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'
/^(([+]{0,1}\d{2})|\d?)[\s-]?[0-9]{2}[\s-]?[0-9]{3}[\s-]?[0-9]{4}$/gm
Tested for
+94 77 531 2412
+94775312412
077 531 2412
0775312412
77 531 2412
// Not matching
77-53-12412
+94-77-53-12412
077 123 12345
77123 12345
In Bootstrap 3 you need to change the modal-dialog. So, in this case, you can add the class modal-admin in the place where modal-dialog stands.
@media (min-width: 768px) {
.modal-dialog {
width: 600;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
it worked for me adding type="module"
to the script import
ing my mjs:
<script type="module">
import * as module from 'https://rawgit.com/abernier/7ce9df53ac9ec00419634ca3f9e3f772/raw/eec68248454e1343e111f464e666afd722a65fe2/mymod.mjs'
console.log(module.default()) // Prints: Hi from the default export!
</script>
See demo: https://codepen.io/abernier/pen/wExQaa
You can't. This is an open issue in TypeScript: https://github.com/Microsoft/TypeScript/issues/19573
Bah, comments are too small. Anyway, @Dirk is very right.
R doesn't need to be told the code starts at the next line. It is smarter than Python ;-) and will just continue to read the next line whenever it considers the statement as "not finished". Actually, in your case it also went to the next line, but R takes the return as a character when it is placed between "".
Mind you, you'll have to make sure your code isn't finished. Compare
a <- 1 + 2
+ 3
with
a <- 1 + 2 +
3
So, when spreading code over multiple lines, you have to make sure that R knows something is coming, either by :
When we're talking strings, this still works but you need to be a bit careful. You can open the quotation marks and R will read on until you close it. But every character, including the newline, will be seen as part of the string :
x <- "This is a very
long string over two lines."
x
## [1] "This is a very\nlong string over two lines."
cat(x)
## This is a very
## long string over two lines.
That's the reason why in this case, your code didn't work: a path can't contain a newline character (\n
). So that's also why you better use the solution with paste()
or paste0()
Dirk proposed.
Prefix is the prefix for url routing. If it's equals to '/' it means it will have no prefix. Then you defined a route with pattern "it should start with /hello".
To create a route for '/' you need to add these lines in your src/Shop/MyShopBundle/Resources/config/routing.yml :
ShopMyShopBundle_homepage:
pattern: /
defaults: { _controller: ShopMyShopBundle:Main:index }
It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...
YOU HAVE BEEN WARNED!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
As an alternative, to get around the elements-can-be-modified issue with a readonly array, you can use a static property instead. (The individual elements can still be changed, but these changes will only be made on the local copy of the array.)
public static string[] Titles
{
get
{
return new string[] { "German", "Spanish", "Corrects", "Wrongs"};
}
}
Of course, this will not be particularly efficient as a new string array is created each time.
<?, >?, <?=, >?=
In a very old version of GCC there were the operators <?, >?
(see here, here it was in C++ but I think it also applied as a C extension back then)
I have also seen the operators <?=, >?=
corresponding to the assignment statements.
The operands were evaluated once and even allowed for a very short assignment statement. Its very short compared to common min/max assignments. There is nothing that can top this.
Those were a shorthand for the following:
min(a, b) === a < b ? a : b === a <? b;
max(a, b) === a > b ? a : b === a >? b;
a = min(a, b); === if(b < a) a = b; === a <?= b;
a = max(a, b); === if(b > a) a = b; === a >?= b;
Finding the minimum is very concise:
int find_min(const int* ints, int num_ints)
{
assert(num_ints > 0);
int min = ints[0];
for(int i = 1; i < num_ints; ++i)
min <?= ints[i];
return min;
}
I hope this might be some day brought back to GCC, because I think these operators are genious.
There should be no difference at all maybe the first is a little more performant but i think it's trivial ( you shouldn't worry about this, really ).
With both you wrap the <body>
tag in a jQuery object
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
In your HTML all h2
s have the same off-set of 4 columns, so they won't make a diagonal.
A row
has 12 columns, so we should put every h2
in it's own row
.
You should have something like this:
<div class="jumbotron">
<div class="container">
<div class="row">
<h2 class="col-md-4 col-md-offset-1">Browse.</h2>
</div>
<div class="row">
<h2 class="col-md-4 col-md-offset-2">create.</h2>
</div>
<div class="row">
<h2 class="col-md-4 col-md-offset-3">share.</h2>
</div>
</div>
</div>
An alternative is to make every h2
width plus offset sum 12 columns, so each one automatically wraps in a new line.
<div class="jumbotron">
<div class="container">
<div class="row">
<h2 class="col-md-11 col-md-offset-1">Browse.</h2>
<h2 class="col-md-10 col-md-offset-2">create.</h2>
<h2 class="col-md-9 col-md-offset-3">share.</h2>
</div>
</div>
</div>
npm i -f
I'd like to repost some comments from this thread, where you can read up on the issue and the issue was solved.
This is exactly Angular's issue. Current package.json requires fsevent as not optionalDependencies but devDependencies. This may be a problem for non-OSX users.
Sometimes
Even if you remove it from package.json npm i still fails because another module has it as a peer dep.
So
if npm-shrinkwrap.json is still there, please remove it or try npm i -f
There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.
name = gets
"mukesh\n"
You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type
name = gets
you will see somethings like"mukesh\n"
You can get rid of pesky newline character using chomp method.
The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.
name = gets.chomp
"mukesh"
You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.
When written inside your Ruby program, ARGV will take take a command line command that looks like this:
test.rb hi my name is mukesh
and create an array that looks like this:
["hi", "my", "name", "is", "mukesh"]
But, if I want to passed limited input then we can use something like this.
test.rb 12 23
and use those input like this in your program:
a = ARGV[0]
b = ARGV[1]
I had the same error and struggled to fix it, then answer above by Nagaraja JB helped me to fix it. In my case:
Was before: JSONObject response_json = new JSONObject(response_data);
Changed it to: JSONArray response_json = new JSONArray(response_data);
This fixed it.
It is possible and it is really simple if you look at it when finishing the implementation, which is again - very simple, since the only items you need are two boolean variables: internet reachability and host reachability (you often need more than one of these). Once you assemble your helper class that can determine the connections status, you really don't care again of the implementation needed for knowing these procedures.
Example:
#import <Foundation/Foundation.h>
@class Reachability;
@interface ConnectionManager : NSObject {
Reachability *internetReachable;
Reachability *hostReachable;
}
@property BOOL internetActive;
@property BOOL hostActive;
- (void) checkNetworkStatus:(NSNotification *)notice;
@end
And the .m file:
#import "ConnectionManager.h"
#import "Reachability.h"
@implementation ConnectionManager
@synthesize internetActive, hostActive;
-(id)init {
self = [super init];
if(self) {
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
hostReachable = [[Reachability reachabilityWithHostName:@"www.apple.com"] retain];
[hostReachable startNotifier];
return self;
}
- (void) checkNetworkStatus:(NSNotification *)notice {
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
self.internetActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
self.internetActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
self.internetActive = YES;
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
self.hostActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
self.hostActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
self.hostActive = YES;
break;
}
}
}
// If lower than SDK 5 : Otherwise, remove the observer as pleased.
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end
For a unique column, use this:
INSERT OR REPLACE INTO table () values();
For more information, see: sqlite.org/lang_insert
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
app.manifest
should be like this:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
Define a property of the form like, then use this in other places it would be available with the form instance
public string SetText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
I think this is related, but I had a problem when building directly using msbuild
command line (from a batch file) vs building from within VS.
Using something like the following:
<PostBuildEvent>
MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
</PostBuildEvent>
(note: start XCOPY
rather than XCOPY
used to get around a permissions issue which prevented copying)
The macro $(SolutionDir)
evaluated to ..\
when executing msbuild from a batchfile, which resulted in the XCOPY
command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic
to see the evaluated output.
Using the macro $(ProjectDir)..\
instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.
That's how I've added mine in profiles json table,
{
"guid": "{00000000-0000-0000-ba54-000000000002}",
"name": "Git",
"commandline": "C:/Program Files/Git/bin/bash.exe --login",
"icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
"startingDirectory": "%USERPROFILE%",
"hidden": false
}
If linked server name is IP address following code is true:
select * from [1.2.3.4,1433\MSSQLSERVER].test.dbo.Table1
It's just, note [] around IP address section.
reload
hacksWithout seeing the source it's difficult to know the root cause, so I'll have to speak generally.
UnicodeDecodeError: 'ascii' codec can't decode byte
generally happens when you try to convert a Python 2.x str
that contains non-ASCII to a Unicode string without specifying the encoding of the original string.
In brief, Unicode strings are an entirely separate type of Python string that does not contain any encoding. They only hold Unicode point codes and therefore can hold any Unicode point from across the entire spectrum. Strings contain encoded text, beit UTF-8, UTF-16, ISO-8895-1, GBK, Big5 etc. Strings are decoded to Unicode and Unicodes are encoded to strings. Files and text data are always transferred in encoded strings.
The Markdown module authors probably use unicode()
(where the exception is thrown) as a quality gate to the rest of the code - it will convert ASCII or re-wrap existing Unicodes strings to a new Unicode string. The Markdown authors can't know the encoding of the incoming string so will rely on you to decode strings to Unicode strings before passing to Markdown.
Unicode strings can be declared in your code using the u
prefix to strings. E.g.
>>> my_u = u'my ünicôdé string'
>>> type(my_u)
<type 'unicode'>
Unicode strings may also come from file, databases and network modules. When this happens, you don't need to worry about the encoding.
Conversion from str
to Unicode can happen even when you don't explicitly call unicode()
.
The following scenarios cause UnicodeDecodeError
exceptions:
# Explicit conversion without encoding
unicode('€')
# New style format string into Unicode string
# Python will try to convert value string to Unicode first
u"The currency is: {}".format('€')
# Old style format string into Unicode string
# Python will try to convert value string to Unicode first
u'The currency is: %s' % '€'
# Append string to Unicode
# Python will try to convert string to Unicode first
u'The currency is: ' + '€'
In the following diagram, you can see how the word café
has been encoded in either "UTF-8" or "Cp1252" encoding depending on the terminal type. In both examples, caf
is just regular ascii. In UTF-8, é
is encoded using two bytes. In "Cp1252", é is 0xE9 (which is also happens to be the Unicode point value (it's no coincidence)). The correct decode()
is invoked and conversion to a Python Unicode is successfull:
In this diagram, decode()
is called with ascii
(which is the same as calling unicode()
without an encoding given). As ASCII can't contain bytes greater than 0x7F
, this will throw a UnicodeDecodeError
exception:
It's good practice to form a Unicode sandwich in your code, where you decode all incoming data to Unicode strings, work with Unicodes, then encode to str
s on the way out. This saves you from worrying about the encoding of strings in the middle of your code.
If you need to bake non-ASCII into your source code, just create Unicode strings by prefixing the string with a u
. E.g.
u'Zürich'
To allow Python to decode your source code, you will need to add an encoding header to match the actual encoding of your file. For example, if your file was encoded as 'UTF-8', you would use:
# encoding: utf-8
This is only necessary when you have non-ASCII in your source code.
Usually non-ASCII data is received from a file. The io
module provides a TextWrapper that decodes your file on the fly, using a given encoding
. You must use the correct encoding for the file - it can't be easily guessed. For example, for a UTF-8 file:
import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
my_unicode_string = my_file.read()
my_unicode_string
would then be suitable for passing to Markdown. If a UnicodeDecodeError
from the read()
line, then you've probably used the wrong encoding value.
The Python 2.7 CSV module does not support non-ASCII characters . Help is at hand, however, with https://pypi.python.org/pypi/backports.csv.
Use it like above but pass the opened file to it:
from backports import csv
import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
for row in csv.reader(my_file):
yield row
Most Python database drivers can return data in Unicode, but usually require a little configuration. Always use Unicode strings for SQL queries.
MySQLIn the connection string add:
charset='utf8',
use_unicode=True
E.g.
>>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")
PostgreSQL
Add:
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
Web pages can be encoded in just about any encoding. The Content-type
header should contain a charset
field to hint at the encoding. The content can then be decoded manually against this value. Alternatively, Python-Requests returns Unicodes in response.text
.
If you must decode strings manually, you can simply do my_string.decode(encoding)
, where encoding
is the appropriate encoding. Python 2.x supported codecs are given here: Standard Encodings. Again, if you get UnicodeDecodeError
then you've probably got the wrong encoding.
Work with Unicodes as you would normal strs.
print
writes through the stdout stream. Python tries to configure an encoder on stdout so that Unicodes are encoded to the console's encoding. For example, if a Linux shell's locale
is en_GB.UTF-8
, the output will be encoded to UTF-8
. On Windows, you will be limited to an 8bit code page.
An incorrectly configured console, such as corrupt locale, can lead to unexpected print errors. PYTHONIOENCODING
environment variable can force the encoding for stdout.
Just like input, io.open
can be used to transparently convert Unicodes to encoded byte strings.
The same configuration for reading will allow Unicodes to be written directly.
Python 3 is no more Unicode capable than Python 2.x is, however it is slightly less confused on the topic. E.g the regular str
is now a Unicode string and the old str
is now bytes
.
The default encoding is UTF-8, so if you .decode()
a byte string without giving an encoding, Python 3 uses UTF-8 encoding. This probably fixes 50% of people's Unicode problems.
Further, open()
operates in text mode by default, so returns decoded str
(Unicode ones). The encoding is derived from your locale, which tends to be UTF-8 on Un*x systems or an 8-bit code page, such as windows-1251, on Windows boxes.
sys.setdefaultencoding('utf8')
It's a nasty hack (there's a reason you have to use reload
) that will only mask problems and hinder your migration to Python 3.x. Understand the problem, fix the root cause and enjoy Unicode zen.
See Why should we NOT use sys.setdefaultencoding("utf-8") in a py script? for further details
If you are working with numpy you need to use the delete method:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
a = np.delete(a, 0)
print(a) # [2 3 4 5]
You can use dbeaver to do this. It allows you to export the ER diagram as png/svg etc.
DBeaver - https://dbeaver.io/
Double click on a schema (eg, Schemas->public->Tables) and open the "ER Diagram" tab (next to "Properties" tab)
I have used the following for this issue. I know it's not very elegant, but it's working.
DateTime zeroTime = new DateTime(1, 1, 1);
var date1 = new DateTime(1983, 03, 04);
var date2 = DateTime.Now;
var dif = date2 - date1;
int years = (zeroTime + dif).Year - 1;
Log.DebugFormat("Years -->{0}", years);
For int
use this:
>>> "1221323".isdigit()
True
But for float
we need some tricks ;-). Every float number has one point...
>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False
Also for negative numbers just add lstrip()
:
>>> '-12'.lstrip('-')
'12'
And now we get a universal way:
>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False
This is a implementation of Pearson Correlation function using numpy:
def corr(data1, data2):
"data1 & data2 should be numpy arrays."
mean1 = data1.mean()
mean2 = data2.mean()
std1 = data1.std()
std2 = data2.std()
# corr = ((data1-mean1)*(data2-mean2)).mean()/(std1*std2)
corr = ((data1*data2).mean()-mean1*mean2)/(std1*std2)
return corr
You are trying to remove value from list in advanced "for loop", which is not possible, even if you apply any trick (which you did in your code). Better way is to code iterator level as other advised here.
I wonder how people have not suggested traditional for loop approach.
for( int i = 0; i < lStringList.size(); i++ )
{
String lValue = lStringList.get( i );
if(lValue.equals("_Not_Required"))
{
lStringList.remove(lValue);
i--;
}
}
This works as well.
XAMPP is more powerful and resource taking than WAMP.
WAMP provides support for MySQL and PHP.
XAMPP provides support for MYSQL, PHP and PERL
XAMPP also has SSL feature while WAMP doesnt.
If your applications need to deal with native web apps only, Go for WAMP.
If you need advanced features as stated above, go for XAMPP.
As of priority, you cant run both together with default installation as XAMPP gets a higher priority and it takes up ports. So WAMP cant be run in parallel with XAMPP.
To understand why it does not return the list:
sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.
So problem is with answer = newList.sort()
where answer is none.
Instead you can just do return newList.sort()
.
The syntax of the sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same purpose.
sorted(list, key=..., reverse=...)
Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.
So in your case answer = sorted(newList)
.
If you are in a po-up and you want to access the opening window, use window.opener
.
The easiest would be if you could load JQuery in the parent window as well:
window.opener.$("#serverMsg").html
// this uses JQuery in the parent window
or you could use plain old document.getElementById
to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):
element = window.opener.document.getElementById("serverMsg");
element = $(element);
If you are in an iframe or frameset and want to access the parent frame, use window.parent
instead of window.opener
.
According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.
You're applying your class to the <a>
elements, which aren't siblings because they're each enclosed in an <li>
element. You need to move up the tree to the parent <li>
and find the ` elements in the siblings at that level.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().find('a').removeClass('current');
});
See this updated fiddle
Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:
GRANT CREATE JOB TO scott;
After this statement is executed, scott can create jobs, schedules, or programs in his schema.
copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239
I struggled with this 'fully loaded' issue for some time but found the following solution worked for me. I'm using IE7, so I'm not sure if this works in other versions, but worth a look.
I split the problem into two parts; first I needed a message from the DocumentComplete event;
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
fullyLoaded = True
End Sub
Then in the part of code where I need to wait till the web page has fully loaded I call another sub that does this;
Private Sub holdBrowserPage()
fullyLoaded = False
Do While fullyLoaded = False
DoEvents
Loop
fullyLoaded = False
End Sub
In addition, I also needed to do the same thing whilst waiting for javascript code to complete. For instance on one page when you select an item from an html drop down list, it populated the next drop down list, but took a while to reveal itself. In that instance I found calling this;
Private Sub holdBrowser()
Do While WebBrowser1.Busy Or WebBrowser1.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
End Sub
was enough to hold the browser. Not sure if this will help everyone, as a combination of IE7, the website I was loading, and the javascript that the page was running alone might have allowed this solution, but certainly worth a try.
In Ef .net core there are two options that you can do; first with data annotations:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Or with fluent api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
There are more details here
It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).
Specifics are described as Netbeans bug #248182.
This problem is also related to postings mentioning the following error output:
'127.0.0.1*' is not recognized as an internal or external command, operable program or batch file.
For a tomcat installed from the zip file, I fixed it by changing the catalina.bat
file in the tomcat bin
directory.
Find the bellow configuration in your catalina.bat
file.
:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"
:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"
And change it as in below by removing the double quotes:
:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%
:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%
Now save your changes, and start your tomcat from within NetBeans.
Use a public static class and access it from anywhere.
public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}
used like so, from master page or anywhere:
string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
You don't need to make an instance of the class; in fact you can't because it's static. Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because new
const
is implicitly static by nature.
The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)
You can make as many static classes as you like and name them whatever you want.
Sometimes programmers like to group their constants by using nested static classes. For example,
public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}
and access them like so:
MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
I had this issue when converting an older project to use a new version of Visual Studio. Upon conversion, the project target framework was set to 2.0
I was able to solve this issue by changing the target framework to be 3.5.
In short:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
Many examples on the matplotlib website. The one I most commonly use is here
Did you override equals and hashCode in the Block class?
EDIT:
I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.
Solr currently checks for a "pure negative" query and inserts *:*
(which matches all documents) so that it works correctly.
-foo
is transformed by solr into (*:* -foo)
The big caveat is that Solr only checks to see if the top level query is a pure negative query!
So this means that a query like bar OR (-foo)
is not changed since the pure negative query is in a sub-clause of the top level query. You need to transform this query yourself into bar OR (*:* -foo)
You may check the solr query explanation to verify the query transformation:
?q=-title:foo&debug=query
is transformed to
(+(-title:foo +MatchAllDocsQuery(*:*))
The reason you are getting the unexpected result is that hist(...)
calculates the distribution from a numeric vector. In your code, table(animalFactor)
behaves like a numeric vector with three elements: 1, 3, 7. So hist(...)
plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.
Here's a way to do this using ggplot
:
library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))
You would get precisely the same result using animalFactor
instead of animals
in the code above.
Just in case someone else was struggeling with the accepted answer:
There are different OnCheckedChangeListener-Interfaces. I added to first one to see if a CheckBox was changed.
import android.widget.CompoundButton.OnCheckedChangeListener;
vs
import android.widget.RadioGroup.OnCheckedChangeListener;
When adding the snippet from Ricky I had errors:
The method setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener) in the type RadioGroup is not applicable for the arguments (new CompoundButton.OnCheckedChangeListener(){})
Can be fixed with answer from Ali :
new RadioGroup.OnCheckedChangeListener()
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
for converting dd/mm/yyyy
to mm/dd/yyyy
=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))
I tried all of these solutions mentioned above under Debian Jessie. They don't work, because it just takes the latest version compile by the debian package manager which is 1.5.6 which equates to version 6.0.x. Some packages that use pip as prerequisites will not work as a results, such as spaCy (which needs the option --no-cache-dir to function correctly).
So the actual best way to solve these problems is to run get-pip.py downloaded using wget, from the website or using curl as follows:
wget https://bootstrap.pypa.io/get-pip.py -O ./get-pip.py
python ./get-pip.py
python3 ./get-pip.py
This will install the current version which at the time of writing this solution is 9.0.1 which is way beyond what Debian provides.
$ pip --version
pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python2.7/dist-packages (python 2.7)
$ pip3 --version
pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python3.4/site-packages (python 3.4)
In C# when debugging threads for example, you can see each thread's ID.
This will be the Ids of the managed threads. ManagedThreadId
is a member of Thread
so you can get the Id from any Thread object. This will get you the current ManagedThreadID:
Thread.CurrentThread.ManagedThreadId
To get an OS thread by its OS thread ID (not ManagedThreadID), you can try a bit of linq.
int unmanagedId = 2345;
ProcessThread myThread = (from ProcessThread entry in Process.GetCurrentProcess().Threads
where entry.Id == unmanagedId
select entry).First();
It seems there is no way to enumerate the managed threads and no relation between ProcessThread and Thread, so getting a managed thread by its Id is a tough one.
For more details on Managed vs Unmanaged threading, see this MSDN article.
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS
doesn't include 'n'.
Turning off line numbers by default (for example, setting LESS=n
) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.
I typically run with LESS=RSXin
(escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less
as needed.
Instead of switching autocommit off manually at restore time you can already dump your MySQL data in a way that includes all necessary statements right into your SQL file.
The command line parameter for mysqldump is --no-autocommit
. You might also consider to add --opt
which sets a combination of other parameters to speed up restore operations.
Here is an example for a complete mysqldump command line as I use it, containing --no-autocommit
and --opt
:
mysqldump -hlocalhost -uMyUser -p'MyPassword' --no-autocommit --opt --default-character-set=utf8 --quote-names MyDbName > dump.sql
For details of these parameters see the reference of mysqldump
The endpoint of the term is the URL that is focused on creating a request. Take a look at the following examples from different points:
/api/groups/6/workings/1
/api/v2/groups/5/workings/2
/api/workings/3
They can clearly access the same source in a given API.
The issue appeared while I did not change the code, using a recent VS2019 16.7.5.
Just opening for edition the corresponding XAML file solved the problem.
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
By configuring that the IDE projects are setup to use a Java 6 JRE or above sometimes does not remove the eclipse error. For me a restart of the Eclipe IDE helped.
If you define the timezone in your PHP app (as you should), which you can do this way:
date_default_timezone_set('Europe/Paris');
Then it's as simple as:
$yesterday = new DateTime('yesterday'); // will use our default timezone, Paris
echo $yesterday->format('Y-m-d'); // or whatever format you want
(You may want to define a constant or environment variable to store your default timezone.)
You can hide columns by this command:
fnSetColumnVis( 1, false );
Where first parameter is index of column and second parameter is visibility.
Via: http://www.datatables.net/api - function fnSetColumnVis
The answer, in a few words
In your example, itsProblem
is a local variable.
Your must use self
to set and get instance variables. You can set it in the __init__
method. Then your code would be:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
But if you want a true class variable, then use the class name directly:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)
But be careful with this one, as theExample.itsProblem
is automatically set to be equal to Example.itsProblem
, but is not the same variable at all and can be changed independently.
Some explanations
In Python, variables can be created dynamically. Therefore, you can do the following:
class Example(object):
pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem
prints
True
Therefore, that's exactly what you do with the previous examples.
Indeed, in Python we use self
as this
, but it's a bit more than that. self
is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self
or not.
Which means you can do:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
or:
class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
It's exactly the same. The first argument of ANY object method is the current object, we only call it self
as a convention. And you add just a variable to this object, the same way you would do it from outside.
Now, about the class variables.
When you do:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?
Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.
As a conclusion, never use class variables to set default values to object variables. Use __init__
for that.
Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.
textFieldView.keyboardType = UIKeyboardType.PhonePad
This is for swift. Also in order for this to function properly it must be set after the textFieldView.delegate = self
try the following:
myPictureBox.Image = global::mynamespace.Properties.Resources.photo1;
and replace namespace with your project namespace
First of all, as many others already said, your .gitignore
should be tracked by Git (and should therefore not be ignored). Let me explain why.
(TL;DR: commit the .gitignore
file, and use a global .gitignore
to ignore files that are created by your IDE or operating system)
Git is, as you probably already know, a distributed version control system. This means that it allows you to switch back and forth between different versions (even if development has diverged into different branches) and it also allows multiple developers to work on the same project.
Although tracking your .gitignore
also has benefits when you switch between snapshots, the most important reason for committing it is that you'll want to share the file with other developers who are working on the same project. By committing the file into Git, other contributers will automatically get the .gitignore
file when they clone the repository, so they won't have to worry about accidentally committing a file that shouldn't be committed (such as log files, cache directories, database credentials, etc.). And if at some point the project's .gitignore
is updated, they can simply pull in those changes instead of having to edit the file manually.
Of course, there will be some files and folders that you'll want to ignore, but that are specific for you, and don't apply to other developers. However, those should not be in the project's .gitignore
. There are two other places where you can ignore files and folders:
.gitignore
. The benefit is that this .gitignore
is applied to all repositories on your computer, so you don't have to repeat this for every repository. And it's not shared with other developers, since they might be using a different operating system and/or IDE..gitignore
, nor in the global .gitignore
, can be ignored using explicit repository excludes in your_project_directory/.git/info/exclude
. This file will not be shared with other developers, and is specific for that single repositoryHere is the sample code, which is working in Android Oreo and less than Oreo.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
} else {
builder = new NotificationCompat.Builder(getApplicationContext());
}
builder = builder
.setSmallIcon(R.drawable.ic_notification_icon)
.setColor(ContextCompat.getColor(context, R.color.color))
.setContentTitle(context.getString(R.string.getTitel))
.setTicker(context.getString(R.string.text))
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(requestCode, builder.build());
This is what do you want? DEMO. Try to shrink the browser's window and you'll see that the elements will be ordered.
What I used? Flexible Box Model or Flexbox.
Just add the follow CSS classes to your container element (in this case div#container
):
flex-init-setup
and flex-ppal-setup
.
Where:
Here are the CSS rules:
.flex-init-setup {
display: -webkit-box;
display: -moz-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.flex-ppal-setup {
-webkit-flex-flow: column wrap;
-moz-flex-flow: column wrap;
flex-flow: column wrap;
-webkit-justify-content: center;
-moz-justify-content: center;
justify-content: center;
}
Be good, Leonardo
I agree with Mike, though I'm a Vim die-hard. I've been using GEdit quite frequently lately when I'm doing lightweight Ruby scripting. The standard editor (plus Ruby code snippets) is extremely usable and polished, and can provide a nice reprieve from full-strength, always-on programming editors.
I recently wrote a gem to simplify this process and to neaten up your views, etc etc.
Check it out at: http://github.com/platform45/easy_dates
As others have mentioned, comments are referenced with a #
and are documented here. However, unlike some languages, the #
must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.
# This is a comment
COPY test_dir target_dir # This is not a comment, it is an argument to COPY
RUN echo hello world # This is an argument to RUN but the shell may ignore it
It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY
and RUN
commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax
line. See the experimental syntax for more details on how this is being used in practice.
With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:
$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
&& echo third command
$ docker build .
Sending build context to Docker daemon 23.04kB
Step 1/2 : FROM busybox:latest
---> 59788edf1f3e
Step 2/2 : RUN echo first command && echo third command
---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
---> 5442cfe321ac
Successfully built 5442cfe321ac
I had tried various things, including "Clean Up" on lower subdirectories. Finally, I tried updating the top level folder. Nothing. Then I read the "Clean up top level" tip. I tried that. The clean up part succeeded, but the lock remained. My solution was to go back to the top level, clean up, then clean up each red (!) folder I could drill down to. After all was "Cleaned up", the update worked perfectly. The "break lock" tip looks good, too, with the exception that someone on your team might have a legitimate lock on things.
To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
You mean that you want something like:
''.join(n for n in phone_str if n.isdigit())
This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.
Regarding your efforts,
This one actually removes all of the digits from the string leaving you with only non-digits.
x = row.translate(None, string.digits)
This one splits the string on runs of whitespace, not after each character:
list = x.split()
I wrote this comment already more than 4 years ago and decided now to make it to an answer.
The script from jruzafa can be a bit simplified:
#!/bin/bash
USER="zend"
PASSWORD=""
ExcludeDatabases="Database|information_schema|performance_schema|mysql"
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | egrep -v $ExcludeDatabases`
for db in $databases; do
echo "Dumping database: $db"
mysqldump -u $USER -p$PASSWORD --databases $db > `date +%Y%m%d`.$db.sql
# gzip $OUTPUT`date +%Y%m%d`.$db.sql
done
Note:
ExcludeDatabases
Yes, it's
use Illuminate\Support\Facades\Redirect;
return Redirect::to('http://heera.it');
Update: Redirect::away('url')
(For external link, Laravel Version 4.19):
public function away($path, $status = 302, $headers = array())
{
return $this->createRedirect($path, $status, $headers);
}
You are correct here:
Integer i = 0;
i = i + 1; // <- I think that this is somehow creating a new object!
First: Integer is immutable.
Second: the Integer class is not overriding the +
operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1
the compiler first converts the Integer to an (primitive) int
for performing the addition: autounboxing. Next, doing i = <some int>
the compiler converts from int
to an (new) Integer: autoboxing.
So +
is actually being applied to primitive int
s.
This thread is a bit older but here something I just came across:
Try this code:
$date = new DateTime();
$arr = ['date' => $date];
echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';
function mytest($params = []) {
if (isset($params['date'])) {
$params['date']->add(new DateInterval('P1D'));
}
}
http://codepad.viper-7.com/gwPYMw
Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.
If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.