If you only need to replace characters in one specific column, somehow regex=True and in place=True all failed, I think this way will work:
data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))
lambda is more like a function that works like a for loop in this scenario. x here represents every one of the entries in the current column.
The only thing you need to do is to change the "column_name", "characters_need_to_replace" and "new_characters".
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);
function escapeHtml(text) {
if('' !== text) {
return text.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\./g,' ')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
In python \
(backslash) is used as an escape character. What this means that in places where you wish to insert a special character (such as newline), you would use the backslash and another character (\n
for newline)
With your example string you would notice that when you put "C:\Users\Josh\Desktop\20130216"
in the repl you will get "C:\\Users\\Josh\\Desktop\x8130216"
. This is because \2
has a special meaning in a python string. If you wish to specify \
then you need to put two \\
in your string.
"C:\\Users\\Josh\\Desktop\\28130216"
The other option is to notify python that your entire string must NOT use \
as an escape character by pre-pending the string with r
r"C:\Users\Josh\Desktop\20130216"
This is a "raw" string, and very useful in situations where you need to use lots of backslashes such as with regular expression strings.
In case you still wish to replace that single \
with \\
you would then use:
directory = string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\\\")
Notice that I am not using r'
in the last two strings above. This is because, when you use the r'
form of strings you cannot end that string with a single \
Why can't Python's raw string literals end with a single backslash?
thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
You could also pass a dict
to the pandas.replace
method:
data.replace({
'column_name': {
'value_to_replace': 'replace_value_with_this'
}
})
This has the advantage that you can replace multiple values in multiple columns at once, like so:
data.replace({
'column_name': {
'value_to_replace': 'replace_value_with_this',
'foo': 'bar',
'spam': 'eggs'
},
'other_column_name': {
'other_value_to_replace': 'other_replace_value_with_this'
},
...
})
There is an option in search => file and shortcut is Ctrl+H. Go for further refer follow link. This is work fine with Eclipse Neon
Is there a way to find/replace across an entire project in Eclipse?
The original form is nearly perfect, you just have to omit prereq after CASE:
SELECT
CASE
WHEN prereq IS NULL THEN ' '
ELSE prereq
END AS prereq
FROM test;
Try this:
find /home/user/ -type f | xargs sed -i 's/a\.example\.com/b.example.com/g'
In case you want to ignore dot directories
find . \( ! -regex '.*/\..*' \) -type f | xargs sed -i 's/a\.example\.com/b.example.com/g'
Edit: escaped dots in search expression
You can also use replaceAll(search, replaceWith)
[MDN].
Then, make sure you have a string by wrapping one type of quotes by a different type:
'a "b" c'.replaceAll('"', "'")
// result: "a 'b' c"
'a "b" c'.replaceAll(`"`, `'`)
// result: "a 'b' c"
// Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
'a "b" c'.replaceAll(/\"/g, "'")
// result: "a 'b' c"
Important(!) if you choose regex:
when using a
regexp
you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".
If you set "Use regular expressions" flag then \n would be translated. But keep in mind that you would have to modify you search term to be regexp friendly. In your case it should be escaped like this "\~\~\?" (no quotes).
Here is an awk
based on oogas sed
echo 'abbc' | awk '{gsub(/ab/,"xy");gsub(/bc/,"ab");gsub(/xy/,"bc")}1'
bcab
To have the new string returned use this:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
For larger s&r tasks it's better and faster to use grep and xargs, so, for example;
grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'
find /home/www/ -type f -exec perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
find /home/www/ -type f
will list all files in /home/www/ (and its subdirectories).
The "-exec" flag tells find to run the following command on each file found.
perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
is the command run on the files (many at a time). The {}
gets replaced by file names.
The +
at the end of the command tells find
to build one command for many filenames.
Per the find
man page:
"The command line is built in much the same way that
xargs builds its command lines."
Thus it's possible to achieve your goal (and handle filenames containing spaces) without using xargs -0
, or -print0
.
Another way we could replace the original column labels is by stripping the unwanted characters (here '$') from the original column labels.
This could have been done by running a for loop over df.columns and appending the stripped columns to df.columns.
Instead, we can do this neatly in a single statement by using list comprehension like below:
df.columns = [col.strip('$') for col in df.columns]
(strip
method in Python strips the given character from beginning and end of the string.)
I got the same issue. The problem is that when you load a .txt in a variable you use it like an array of string while it's an array of character.
swapString = []
with open(filepath) as f:
s = f.read()
for each in s:
swapString.append(str(each).replace('this','that'))
s = swapString
print(s)
This will search and replace all non ASCII letters:
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
As a summary
import sys
import re
f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
s=myfile.read()
ret = re.sub(find,replace, s) # <<< This is where the magic happens
print ret
At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
System.out.println(inputStr); // display the original file for debugging
// logic to replace lines in the string (could use regex here to be generic)
if (type.equals("0")) {
inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");
} else if (type.equals("1")) {
inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
}
// display the new file for debugging
System.out.println("----------------------------------\n" + inputStr);
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then call it:
public static void main(String[] args) {
replaceSelected("Do the dishes", "1");
}
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1
New text file content:
Do the dishes1
Feed the dog0
Cleaned my room1
And as a note, if the text file was:
Do the dishes1
Feed the dog0
Cleaned my room1
and you used the method replaceSelected("Do the dishes", "1");
,
it would just not change the file.
Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).
// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
try {
// input the (modified) file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = ... // replace the line here
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
FYI, this is of little or no use to the OP but it may be of use to other readers (please do not downvote, I'm aware of this).
As a somewhat ridiculous but interesting exercise, wanted to see if I could use python functional programming to replace multiple chars. I'm pretty sure this does NOT beat just calling replace() twice. And if performance was an issue, you could easily beat this in rust, C, julia, perl, java, javascript and maybe even awk. It uses an external 'helpers' package called pytoolz, accelerated via cython (cytoolz, it's a pypi package).
from cytoolz.functoolz import compose
from cytoolz.itertoolz import chain,sliding_window
from itertools import starmap,imap,ifilter
from operator import itemgetter,contains
text='&hello#hi&yo&'
char_index_iter=compose(partial(imap, itemgetter(0)), partial(ifilter, compose(partial(contains, '#&'), itemgetter(1))), enumerate)
print '\\'.join(imap(text.__getitem__, starmap(slice, sliding_window(2, chain((0,), char_index_iter(text), (len(text),))))))
I'm not even going to explain this because no one would bother using this to accomplish multiple replace. Nevertheless, I felt somewhat accomplished in doing this and thought it might inspire other readers or win a code obfuscation contest.
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/
is here to delimit your pattern so you have one to start and one to end[]
indicates the pattern your are looking for on one specific character^
indicates that you want every character NOT corresponding to what followsa-z
matches any character between 'a' and 'z' included0-9
matches any digit between '0' and '9' included (meaning any digit)-
the '-' characterg
at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole stringThen your expression is delimited by /
before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');
if you have done it that way variable string
now holds "123456"
you can also (i guess the better way) do this...
$mylabel.text("-123456");
$mylabel.text(function(i,v){
return v.replace('-','');
});
If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after.
For example
SET QUOTED_IDENTIFIER OFF;
UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
SET QUOTED_IDENTIFIER OFF;
Just download fart (find and replace text) from here
use it in CMD (for ease of use I add fart folder to my path variable)
here is an example:
fart -r "C:\myfolder\*.*" findSTR replaceSTR
this command will search in C:\myfolder and all sub-folders and replace findSTR with replaceSTR
-r means process sub-folders recursively.
fart is really fast and easy
this will remove all the special character
str.replace(/[_\W]+/g, "");
this is really helpful and solve my issue. Please run the below code and ensure it works
var str="hello world !#to&you%*()";_x000D_
console.log(str.replace(/[_\W]+/g, ""));
_x000D_
I would go like this (regex explained in comments):
import re
# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")
# <\/{0,}\[\d+>
#
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»
subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>"""
result = pattern.sub("", subject)
print(result)
If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.
Since you actually want a different array which is arr
where arr < 255
, and 255
otherwise, this can be done simply:
result = np.minimum(arr, 255)
More generally, for a lower and/or upper bound:
result = np.clip(arr, 0, 255)
If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but np.clip
and np.minimum
(or np.maximum
) are nicer and much faster for your case:
In [292]: timeit np.minimum(a, 255)
100000 loops, best of 3: 19.6 µs per loop
In [293]: %%timeit
.....: c = np.copy(a)
.....: c[a>255] = 255
.....:
10000 loops, best of 3: 86.6 µs per loop
If you want to do it in-place (i.e., modify arr
instead of creating result
) you can use the out
parameter of np.minimum
:
np.minimum(arr, 255, out=arr)
or
np.clip(arr, 0, 255, arr)
(the out=
name is optional since the arguments in the same order as the function's definition.)
For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as minimum
:
In [328]: %%timeit
.....: a = np.random.randint(0, 300, (100,100))
.....: np.minimum(a, 255, a)
.....:
100000 loops, best of 3: 303 µs per loop
In [329]: %%timeit
.....: a = np.random.randint(0, 300, (100,100))
.....: a[a>255] = 255
.....:
100000 loops, best of 3: 356 µs per loop
For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without clip
you would have to do this twice, with something like
np.minimum(a, 255, a)
np.maximum(a, 0, a)
or,
a[a>255] = 255
a[a<0] = 0
Below is my script for converting all files recursively. You can specify folders or files to exclude.
$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"
Function Dos2Unix {
[CmdletBinding()]
Param([Parameter(ValueFromPipeline)] $fileName)
Write-Host -Nonewline "."
$fileContents = Get-Content -raw $fileName
$containsCrLf = $fileContents | %{$_ -match "\r\n"}
If($containsCrLf -contains $true)
{
Write-Host "`r`nCleaing file: $fileName"
set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
}
}
Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }
The syntax for REPLACE:
REPLACE (string_expression,string_pattern,string_replacement)
So that the SQL you need should be:
UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')
You can also do it like this:
var tt="88,9827";
tt=tt.replace(",", ".");
alert(tt);
Update for 2020
If you are using the search feature to search across files (Ctrl + Shift + F
) it can be easy to miss how to convert your search to a search and replace within the UI.
Here's a typical search result:
To convert this to a search and replace you need to click the arrow icon to the left of the search input field. This will open the replace options as seen below. Note the arrow icon is now pointed down.
The keyboard shortcut Ctrl + Shift + H
will also work as well to access the search and replace.
Link to VSCode docs on search and replace: https://code.visualstudio.com/docs/editor/codebasics#_search-and-replace
Use StringBuilder
:
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
You want to use postgresql's replace function:
replace(string text, from text, to text)
for instance :
UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')
Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.
This implements a checkbox as a button which shows either Yes or No depending on its 'checked' state. So it demonstrates one way of replacing text using CSS without having to write any code.
It will still behave like a checkbox as far as returning (or not returning) a POST value, but from a display point of view it looks like a toggle button.
The colours may not be to your liking, they're only there to illustrate a point.
The HTML is:
<input type="checkbox" class="yesno" id="testcb" /><label for="testcb"><span></span></label>
...and the CSS is:
/* --------------------------------- */
/* Make the checkbox non-displayable */
/* --------------------------------- */
input[type="checkbox"].yesno {
display:none;
}
/* --------------------------------- */
/* Set the associated label <span> */
/* the way you want it to look. */
/* --------------------------------- */
input[type="checkbox"].yesno+label span {
display:inline-block;
width:80px;
height:30px;
text-align:center;
vertical-align:middle;
color:#800000;
background-color:white;
border-style:solid;
border-width:1px;
border-color:black;
cursor:pointer;
}
/* --------------------------------- */
/* By default the content after the */
/* the label <span> is "No" */
/* --------------------------------- */
input[type="checkbox"].yesno+label span:after {
content:"No";
}
/* --------------------------------- */
/* When the box is checked the */
/* content after the label <span> */
/* is "Yes" (which replaces any */
/* existing content). */
/* When the box becomes unchecked the*/
/* content reverts to the way it was.*/
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span:after {
content:"Yes";
}
/* --------------------------------- */
/* When the box is checked the */
/* label <span> looks like this */
/* (which replaces any existing) */
/* When the box becomes unchecked the*/
/* layout reverts to the way it was. */
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span {
color:green;
background-color:#C8C8C8;
}
I've only tried it on Firefox, but it's standard CSS so it ought to work elsewhere.
Well I think you just need to add a quantifier to each pattern. Also the carriage-return thing is a little funny:
text.replace(/[^a-z0-9]+|\s+/gmi, " ");
edit The \s
thing matches \r
and \n
too.
Since .NET Core 2.0 or .NET Standard 2.1 respectively, this is baked into the .NET runtime [1]:
"hello world".Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase); // "hello csharp"
I got the answer.
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
You can use the text
method and pass a function that returns the modified text, using the native String.prototype.replace
method to perform the replacement:
?$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});?????
Here's a working example.
just use this to replace all white spaces with
-
:
myString.replace(/ /g,"-")
You can use matcher.start() and matcher.end() methods to get the group positions. So using this positions you can easily replace any text.
In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print
statement to see what the string actually looks like.
This example shows the difference:
>>> '\\'
'\\'
>>> print '\\'
\
library(stringi)
group <- c('12357e', '12575e', '12575e', ' 197e18', 'e18947')
pattern <- "e"
replacement <- ""
group <- str_replace(group, pattern, replacement)
group
[1] "12357" "12575" "12575" " 19718" "18947"
And if you want to search and replace based on the value of another field you could do a CONCAT:
update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));
Just to have this one here so that others will find it at once.
Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2
...replaces ...
from checks import checklist(_list):
...with...
from checks import checklist
Blocks in regex are delineated by parenthesis (which are not preceded by a "\")
(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)
(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)
(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"
Then in the replace, just put the $1$2 to replace all three blocks with just the first two.
Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:
> df[df=="" | df==12] <- NA
> df
A B
1 <NA> <NA>
2 xyz <NA>
3 jkl 100
For factors, zxzak's code already yields factors:
> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame': 3 obs. of 2 variables:
$ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
$ B: Factor w/ 3 levels "","100","12": 3 1 2
If in trouble, I'd suggest to temporarily drop the factors.
df[] <- lapply(df, as.character)
Regex.Unescape(string) method converts any escaped characters in the input string.
The Unescape method performs one of the following two transformations:
It reverses the transformation performed by the Escape method by removing the escape character ("\") from each character escaped by the method. These include the \, *, +, ?, |, {, [, (,), ^, $, ., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters.
It replaces the hexadecimal values in verbatim string literals with the actual printable characters. For example, it replaces @"\x07" with "\a", or @"\x0A" with "\n". It converts to supported escape characters such as \a, \b, \e, \n, \r, \f, \t, \v, and alphanumeric characters.
string str = @"a\\b\\c";
var output = System.Text.RegularExpressions.Regex.Unescape(str);
Reference:
replace for persian word
UPDATE dbo.TblNews
SET keyWords = REPLACE(keyWords, '-', N'?')
help: dbo.TblNews -- table name
keyWords -- fild name
The dot operator .
does not need to be escaped inside of a character class []
.
$
variables are only set to matches into the block:
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }
This is also the only way to call a method on the match. This will not change the match, only strip
"\1" (leaving it unchanged):
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
From a file:
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)
this will work
String myName="domanokz";
String p=myName.replace(myName.charAt(4),'x');
System.out.println(p);
Output : domaxokz
Here's another way:
>>> L = range (11)
>>> map(lambda x: x if x%2 else None, L)
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.
Try this:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);
Or if you're sure there won't be any other digits in the string:
var str = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);
This is the idiom I've always used to get a modified copy of a string without changing the original:
(my $newstring = $oldstring) =~ s/foo/bar/g;
In perl 5.14.0 or later, you can use the new /r
non-destructive substitution modifier:
my $newstring = $oldstring =~ s/foo/bar/gr;
NOTE:
The above solutions work without g
too. They also work with any other modifiers.
SEE ALSO:
perldoc perlrequick
: Perl regular expressions quick start
You can use python within the bash script too. I didn't have much success with some of the top answers here, and found this to work without the need for loops:
#!/bin/bash
python
filetosearch = '/home/ubuntu/ip_table.txt'
texttoreplace = 'tcp443'
texttoinsert = 'udp1194'
s = open(filetosearch).read()
s = s.replace(texttoreplace, texttoinsert)
f = open(filetosearch, 'w')
f.write(s)
f.close()
quit()
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
Old thread I know but I am sort of new to Java and discover one of it's strange things. I have used String.replaceAll()
but get unpredictable results.
Something like this mess up the string:
sUrl = sUrl.replaceAll( "./", "//").replaceAll( "//", "/");
So I designed this function to get around the weird problem:
//String.replaceAll does not work OK, that's why this function is here
public String strReplace( String s1, String s2, String s )
{
if((( s == null ) || (s.length() == 0 )) || (( s1 == null ) || (s1.length() == 0 )))
{ return s; }
while( (s != null) && (s.indexOf( s1 ) >= 0) )
{ s = s.replace( s1, s2 ); }
return s;
}
Which make you able to do:
sUrl=this.strReplace("./", "//", sUrl );
sUrl=this.strReplace( "//", "/", sUrl );
I found comment of @Artyom useful but unfortunately he has not posted an answer.
This is the short version, in my opinion best version, of the accepted answer;
ls *.config -rec | %{$f=$_; (gc $f.PSPath) | %{$_ -replace "Dev", "Demo"} | sc $f.PSPath}
Set your Textbox value in a string like:
string MySTring = textBox1.Text;
Then replace your string. For example, replace "Text" with "Hex":
MyString = MyString.Replace("Text", "Hex");
Or for your problem (replace "," with ;) :
MyString = MyString.Replace(@""",""", ",");
Note: If you have "" in your string you have to use @ in the back of "", like:
@"","";
Isn't string.replace returning a value, rather than modifying the source string?
So if you wanted to modify variableABC, you'd need to do this:
var variableABC = "A B C";
variableABC = variableABC.replace('B', 'D') //output: 'A D C'
str_replace(PHP_EOL, null, $str);
With Java-11 and above, you can make use of the String.strip
API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :
/**
* Returns a string whose value is this string, with all leading
* and trailing {@link Character#isWhitespace(int) white space}
* removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all code points in this string are
* {@link Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point that is not a {@link Character#isWhitespace(int) white space}
* up to and including the last code point that is not a
* {@link Character#isWhitespace(int) white space}.
* <p>
* This method may be used to strip
* {@link Character#isWhitespace(int) white space} from
* the beginning and end of a string.
*
* @return a string whose value is this string, with all leading
* and trailing white space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String strip()
The sample cases for these could be:--
System.out.println(" leading".strip()); // prints "leading"
System.out.println("trailing ".strip()); // prints "trailing"
System.out.println(" keep this ".strip()); // prints "keep this"
If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.
for col in df.columns:
df[col][df[col] < 0] = 0
Try this code.You can replace any character with another given character. Here I tried to replace the letter 'a' with "-" character for the give string "abcdeaa"
OutPut -->_bcdef__
public class Replace {
public static void replaceChar(String str,String target){
String result = str.replaceAll(target, "_");
System.out.println(result);
}
public static void main(String[] args) {
replaceChar("abcdefaa","a");
}
}
sSource = sSource.replace("\\/", "/");
String
is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)replaceAll(..)
uses regex. You don't need that.String res =" Application " res=res.trim();
o/p: Application
Note: White space ,blank space are trim or removed
Try it like this:
Replace("\\\"","");
This will replace occurrences of \"
with empty string.
Ex:
string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");
This will result in:
the dog is my friend
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
Switch to text-mode
M-x text-mode
Highlight block to indent
Indent
C+M \
Switch back to whatever mode..
You should re-assign the result of the replacement, like this:
sentence = sentence.replace("and", " ");
Be aware that the String
class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String
must be assigned to a variable or used immediately for the change to take effect.
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
With version 3 of PowerShell you can chain the replace calls together:
(Get-Content $sourceFile) | ForEach-Object {
$_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
} | Set-Content $destinationFile
Even if this thread is old is the first on Google, so I'll post an Oracle equivalent to the function implemented here, using regular expressions.
Is fairly faster than nested replace(), and much cleaner.
To replace strings 'a','b','c' with 'd' in a string column from a given table
select regexp_replace(string_col,'a|b|c','d') from given_table
It is nothing else than a regular expression for several static patterns with 'or' operator.
Beware of regexp special characters!
Why not return a modified string?
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
'some+multi+word+string'.replace(/\+/g, ' ');
^^^^^^
'g' = "global"
Cheers
For situations when I need to replace or match(find) something against string I prefer using regular expressions.
Since, the regular expressions are not fully supported in T-SQL
you can implement them using CLR
functions. Furthermore, you do not need any C#
or CLR
knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.
In your case, the solution using regular expressions is:
SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]
But implementing such function in your database is going to help you solving more complex issues at all.
The example below shows how to deploy only the [dbo].[RegexReplace]
function, but I will recommend to you to deploy the whole String Utility
class.
Enabling CLR Integration. Execute the following Transact-SQL commands:
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
Bulding the code (or creating the .dll
). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.
create new class library project:
copy and paste the following code in the Class1.cs
file:
using System;
using System.IO;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
public sealed class RegularExpression
{
public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
{
string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
return Regex.Replace(input, pattern, replacement);
}
}
build the solution and get the path to the created .dll
file:
replace the path to the .dll
file in the following T-SQL
statements and execute them:
IF OBJECT_ID(N'RegexReplace', N'FS') is not null
DROP Function RegexReplace;
GO
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
DROP ASSEMBLY StringUtils;
GO
DECLARE @SamplePath nvarchar(1024)
-- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
CREATE ASSEMBLY [StringUtils]
FROM @SamplePath + 'StringUtils.dll'
WITH permission_set = Safe;
GO
CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
RETURNS nvarchar(max)
AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
GO
That's it. Test your function:
declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part'
union all select 7, ';' -- test semicolon by itself
SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
FROM @MyTable
select * from @MyTable
There are already multiple answers using str.replace() (which is fair enough for this question) and regex
but you can use combination of str.split() and join() together which is faster than str.replace()
and regex
.
Below is working example:
var text = "this is some sample text that i want to replace";_x000D_
_x000D_
console.log(text.split("want").join("dont want"));
_x000D_
You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):
"$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")
Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).
Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.
It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way
=((E9-E8)/E8)
became
=((R[-1]C-R[-2]C)/R[-2]C)
and
(EXP((LN(E9/E8)/14.32))-1)
became
=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)
In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!
Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.
That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'
? Absolutely!
String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"
Everything seems to work fine to me! indexOf
can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.
It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!
String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;
It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):
In the Java programming language, unlike C, an array of
char
is not aString
, and neither aString
nor an array ofchar
is terminated by '\u0000' (the NUL character).
Would this be the culprit to the funky characters?
Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.
That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.
Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence)
overload.
System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU
The replaceAll
solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.
This worked for me:
import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"
URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string
Result:
text1
text2
text3
text4
text5
text6
I think using visual block mode is a better and more versatile method for dealing with this type of thing. Here's an example:
This is the First line.
This is the second.
The third.
To insert " Hello world." (space + clipboard) at the end of each of these lines:
The result is:
This is the First line. Hello world.
This is the second. Hello world.
The third. Hello world.
(example from Vim.Wikia.com)
With my replace-once package, you could do the following:
const replaceOnce = require('replace-once')
var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'
Use String#replace()
.
To replace them with spaces (as per your question title):
System.out.println("I don't like these \"double\" quotes".replace("\"", " "));
The above can also be done with characters:
System.out.println("I don't like these \"double\" quotes".replace('"', ' '));
To remove them (as per your example):
System.out.println("I don't like these \"double\" quotes".replace("\"", ""));
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
To replace easily all 1
with 10
in
a = [1,2,3,4,5,1,2,3,4,5,1]
one could use the following one-line lambda+map combination, and 'Look, Ma, no IFs or FORs!' :
# This substitutes all '1' with '10' in list 'a' and places result in list 'c':
c = list(map(lambda b: b.replace("1","10"), a))
You could replace something in there by getting the index along with the item.
>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
... print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
... if item in ('a', 'A'):
... foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.
Wrong:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c', 2]
The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c']
As an alternative to Regex, running:
Sub Replacer()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If Left(Cells(i, "A").Value, 9) = "texts are" Then
Cells(i, "A").Value = "texts are replaced"
End If
Next i
End Sub
will produce:
Try this for paths:
echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'
It replaces the space inside the double-quoted string with a +
sing, then replaces the +
sign with a backslash, then removes/replaces the double-quotes.
I had to use this to replace the spaces in one of my paths in Cygwin.
echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'
You can't. Take the characters before and after the position and concat into a new string:
var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
In Chrome version 49
you need always this code
$("select option:first").prop('selected', true)
I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation
DB::create($db, 'YOUR_TABLE_NAME', $dataArray);
where $db is your Database connection.
Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud
A .pl is a single script.
In .pm (Perl Module) you have functions that you can use from other Perl scripts:
A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.
I was getting the same error, and running the following code in the command line solved it:
$ heroku config:set BUNDLE_WITHOUT="development:test"
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)
) before sending to report services and handle it as described above.
Here is a small snippet to demonstrate the date modifications:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
Nautilus can be used easily in this case.
For Fedora 16, go to File
-> Connect To server
,
select the appropriate protocol, enter required details and simply connect, just make sure that the SSH Server is running on other side. It works great.
Edit: This is valid on Ubuntu 14.04 as well
The static factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class's constructor directly: Foo x = new Foo()
. With this pattern, you would instead call the factory method: Foo x = Foo.create()
. The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static
so that it can be called without first having an object.
There are a few advantages to this pattern. One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.
Another advantage is, as Matthew and James have pointed out, controlling access to a limited resource such as connections. This a way to implement pools of reusable objects - instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null
if it's above the upper threshold.
As per the article on Wikipedia, multiple factory methods also allow different interpretations of similar argument types. Normally the constructor has the same name as the class, which means that you can only have one constructor with a given signature. Factories are not so constrained, which means you can have two different methods that accept the same argument types:
Coordinate c = Coordinate.createFromCartesian(double x, double y)
and
Coordinate c = Coordinate.createFromPolar(double distance, double angle)
This can also be used to improve readability, as Rasmus notes.
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processIn Java 6, there is a method doing exactly what you want:
private static final byte[] CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")
Alternatively you could use Google Guava:
import com.google.common.io.BaseEncoding;
private static final byte[] CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());
The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.
You should use System.Windows.Forms.Cursor.Position: "A Point that represents the cursor's position in screen coordinates."
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
We can break both a $(selector).each()
loop and a $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false
is the same as a continue statement in a for
loop; it will skip immediately to the next iteration.
return false; // this is equivalent of 'break' for jQuery loop
return; // this is equivalent of 'continue' for jQuery loop
Note that $(selector).each()
and $.each()
are different functions.
References:
1. Download MongoDB
2. Install MongoDB
3. Create the required folders:
"C:\MongoDB_2_6_Standard\bin\data\db"
"C:\MongoDB_2_6_Standard\logs"
"C:\MongoDB_2_6_Standard\etc"
NOTE: If the directories do not exist, mongod.exe will not start.
4. Create a simple configuration file:
systemLog:
destination: file
path: C:\MongoDB_2_6_Standard\logs\mongo.log
logAppend: true
net:
bindIp: 127.0.0.1
port: 27017
More info about how to create a configuration file: http://docs.mongodb.org/manual/reference/configuration-options/
5. Install MongoDB as a Windows Service (this way it will start automatically when you reboot your computer)
Run cmd with administrator privilegies, and enter the following commands:
"C:\MongoDB_2_6_Standard\bin\mongod.exe" --config "C:\MongoDB_2_6_Standard\etc\mongodb.conf" --dbpath c:\MongoDB_2_6_Standard\bin\data\db --directoryperdb --install
6. Start the MongoDB Windows Service
net start MongoDB
7. Connect to MongoDB via shell/cmd for testing
C:\MongoDB_2_6_Standard\bin\mongo.exe
NOTE: http://docs.mongodb.org/manual/tutorial/getting-started-with-the-mongo-shell/
8. That's it! You are done. :)
9. Uninstall/remove the MongoDB Windows Service (if you messed up something)
"C:\MongoDB_2_6_Standard\bin\mongod.exe" --remove
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
Apache HttpComponents also have an async http client now too:
/**
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0-beta4</version>
</dependency>
**/
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
public class HttpTest {
public static void main(final String[] args) throws Exception {
final CloseableHttpAsyncClient httpclient = HttpAsyncClients
.createDefault();
httpclient.start();
try {
final Future<Boolean> future = httpclient.execute(
HttpAsyncMethods.createGet("http://www.google.com/"),
new MyResponseConsumer(), null);
final Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("Request successfully executed");
} else {
System.out.println("Request failed");
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {
@Override
protected void onResponseReceived(final HttpResponse response) {
}
@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl)
throws IOException {
while (buf.hasRemaining()) {
System.out.print(buf.get());
}
}
@Override
protected void releaseResources() {
}
@Override
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}
}
}
Try adding a TextView to the menubar first and using setCompoundDrawables()
to place the image on whichever side you want. Bond click activity to the textview in the end.
MenuItem item = menu.add(Menu.NONE, R.id.menu_item_save, 10, R.string.save);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
TextView textBtn = getTextButton(btn_title, btn_image);
item.setActionView(textBtn);
textBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// your selector here }
});
You can literally customize everything here:
public TextView getTextButton (String btn_title, Drawable btn_image) {
TextView textBtn = new TextView(this);
textBtn.setText(btn_title);
textBtn.setTextColor(Color.WHITE);
textBtn.setTextSize(18);
textBtn.setTypeface(Typeface.create("sans-serif-light", Typeface.BOLD));
textBtn.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Drawable img = btn_image;
img.setBounds(0, 0, 30, 30);
textBtn.setCompoundDrawables(null, null, img, null);
// left,top,right,bottom. In this case icon is right to the text
return textBtn;
}
Similarities:
DTDs and Schemas both perform the same basic functions:
Differences:
DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.
Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.
Examples:
DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
<!ELEMENT Efirstname (#PCDATA)>
<!ELEMENT Elastname (#PCDATA)>
<!ELEMENT Etitle (#PCDATA)>
<!ELEMENT Ephone (#PCDATA)>
<!ELEMENT Eemail (#PCDATA)>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="generated" type="xsd:dateTime"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="employees">
<xsd:annotation>
<xsd:appinfo>
<od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
unique="yes" clustered="no"/>
<od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
clustered="no"/>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Elastname" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephone" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Eemail" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
This error occurred for me when I mistakenly added a comment following a line continuation character in VB.Net. I removed the comment and the problem went away.
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
@Frode F. gave the right answer.
By the Way Invoke-WebRequest
also prints you the 200 OK
and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod
which is lighter.
Also, keep in mind that you need to use | ConvertTo-Json
for the body only, not the header:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
and you can then append a | ConvertTo-HTML
at the end of the request for better readability
case the column isn't string, use astype to convert:
df['col'] = df['col'].astype(str).str[:9]
This might help you out:
Sub SelectFolder()
Dim diaFolder As FileDialog
Dim Fname As String
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
Fname = diaFolder.SelectedItems(1)
ActiveSheet.Range("B9") = Fname
End Sub
Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?
Json.NET - Documentation
http://james.newtonking.com/json/help/index.html?topic=html/SelectToken.htm
Interpretation for the author
var o = JObject.Parse(response);
var a = o.SelectToken("data").Select(jt => jt.ToObject<TheUser>()).ToList();
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
#include <iostream>
#include <iomanip>
using namespace std;
You can enter the line using namespace std;
for your convenience. Otherwise, you'll have to explicitly add std::
every time you wish to use cout
, fixed
, showpoint
, setprecision(2)
and endl
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
return 0;
}
You can use Toolbar inside the fragment and it is easy to handle. First add Toolbar to layout of the fragment
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>
Inside the onCreateView Method in the fragment you can handle the toolbar like this.
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
IT will set the toolbar,title and the back arrow navigation to toolbar.You can set any icon to setNavigationIcon method.
If you need to trigger any event when click toolbar navigation icon you can use this.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//handle any click event
});
If your activity have navigation drawer you may need to open that when click the navigation back button. you can open that drawer like this.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
drawer.openDrawer(Gravity.START);
}
});
Full code is here
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate the layout to the fragement
view = inflater.inflate(R.layout.layout_user,container,false);
//initialize the toolbar
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//open navigation drawer when click navigation back button
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
drawer.openDrawer(Gravity.START);
}
});
return view;
}
Just want to add that you can debug android apps using Genymotion. It's WAY faster then the stock android emulator.
I too had the same issue when I was trying to clone a repository on my Windows 7 machine. I tried most of the answers mentioned here. None of them worked for me.
What worked for me was, running the Pageant (Putty authentication agent) program. Once the Pageant was running in the background I was able to clone, push & pull from/to the repository. This worked for me, may be because I've setup my public key such that whenever it is used for the first time a password is required & the Pageant starts up.
raw.githubusercontent.com/username/repo-name/branch-name/path
Replace username
with the username of the user that created the repo.
Replace repo-name
with the name of the repo.
Replace branch-name
with the name of the branch.
Replace path
with the path to the file.
To reverse to go to GitHub.com:
GitHub.com/username/repo-name/directory-path/blob/branch-name/filename
Please take care on how to use setState(). The correct form is
this.setState({
Key: Value,
});
And so I would do it as follows:
onChangeText={(event) => this.setState({username:event.nativeEvent.text})}
...
var username=this.state.username;
You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.
Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);
Now in your NewActivity, you can get this bundle and retrive your value.
Bundle bundle = getArguments();
String value = bundle.getString(key);
You can also pass data through the intent. In your current activity, set intent like this,
Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);
Now in your NewActivity, you can get that value from intent like this,
String value = getIntent().getExtras().getString(key);
I've found the proper way to return XML to a client in ASP.NET. I think if I point out the wrong ways, it will make the right way more understandable.
Incorrect:
Response.Write(doc.ToString());
Incorrect:
Response.Write(doc.InnerXml);
Incorrect:
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.OutputStream);
Correct:
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
//using the encoding of the text-writer
//(which comes from response.contentEncoding)
Do not use Response.OutputStream
Do use Response.Output
Both are streams, but Output
is a TextWriter. When an XmlDocument
saves itself to a TextWriter, it will use the encoding specified by that TextWriter. The XmlDocument will automatically change the xml declaration node to match the encoding used by the TextWriter. e.g. in this case the XML declaration node:
<?xml version="1.0" encoding="ISO-8859-1"?>
would become
<?xml version="1.0" encoding="UTF-8"?>
This is because the TextWriter has been set to UTF-8. (More on this in a moment). As the TextWriter is fed character data, it will encode it with the byte sequences appropriate for its set encoding.
Incorrect:
doc.Save(Response.OutputStream);
In this example the document is incorrectly saved to the OutputStream, which performs no encoding change, and may not match the response's content-encoding or the XML declaration node's specified encoding.
Correct
doc.Save(Response.Output);
The XML document is correctly saved to a TextWriter object, ensuring the encoding is properly handled.
The encoding given to the client in the header:
Response.ContentEncoding = ...
must match the XML document's encoding:
<?xml version="1.0" encoding="..."?>
must match the actual encoding present in the byte sequences sent to the client. To make all three of these things agree, set the single line:
Response.ContentEncoding = System.Text.Encoding.UTF8;
When the encoding is set on the Response object, it sets the same encoding on the TextWriter. The encoding set of the TextWriter causes the XmlDocument to change the xml declaration:
<?xml version="1.0" encoding="UTF-8"?>
when the document is Saved:
doc.Save(someTextWriter);
You do not want to save the document to a binary stream, or write a string:
Incorrect:
doc.Save(Response.OutputStream);
Here the XML is incorrectly saved to a binary stream. The final byte encoding sequence won't match the XML declaration, or the web-server response's content-encoding.
Incorrect:
Response.Write(doc.ToString());
Response.Write(doc.InnerXml);
Here the XML is incorrectly converted to a string, which does not have an encoding. The XML declaration node is not updated to reflect the encoding of the response, and the response is not properly encoded to match the response's encoding. Also, storing the XML in an intermediate string wastes memory.
You don't want to save the XML to a string, or stuff the XML into a string and response.Write
a string, because that:
- doesn't follow the encoding specified
- doesn't set the XML declaration node to match
- wastes memory
Do use doc.Save(Response.Output);
Do not use doc.Save(Response.OutputStream);
Do not use Response.Write(doc.ToString());
Do not use 'Response.Write(doc.InnerXml);`
The Response's ContentType must be set to "text/xml"
. If not, the client will not know you are sending it XML.
Response.Clear(); //Optional: if we've sent anything before
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
//using the encoding of the text-writer
//(which comes from response.contentEncoding)
Response.End(); //Optional: will end processing
Rob Kennedy had the good point that I failed to include the start-to-finish example.
GetPatronInformation.ashx:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Xml;
using System.IO;
using System.Data.Common;
//Why a "Handler" and not a full ASP.NET form?
//Because many people online critisized my original solution
//that involved the aspx (and cutting out all the HTML in the front file),
//noting the overhead of a full viewstate build-up/tear-down and processing,
//when it's not a web-form at all. (It's a pure processing.)
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//GetXmlToShow will look for parameters from the context
XmlDocument doc = GetXmlToShow(context);
//Don't forget to set a valid xml type.
//If you leave the default "text/html", the browser will refuse to display it correctly
context.Response.ContentType = "text/xml";
//We'd like UTF-8.
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
//context.Response.ContentEncoding = System.Text.Encoding.UnicodeEncoding; //But no reason you couldn't use UTF-16:
//context.Response.ContentEncoding = System.Text.Encoding.UTF32; //Or UTF-32
//context.Response.ContentEncoding = new System.Text.Encoding(500); //Or EBCDIC (500 is the code page for IBM EBCDIC International)
//context.Response.ContentEncoding = System.Text.Encoding.ASCII; //Or ASCII
//context.Response.ContentEncoding = new System.Text.Encoding(28591); //Or ISO8859-1
//context.Response.ContentEncoding = new System.Text.Encoding(1252); //Or Windows-1252 (a version of ISO8859-1, but with 18 useful characters where they were empty spaces)
//Tell the client don't cache it (it's too volatile)
//Commenting out NoCache allows the browser to cache the results (so they can view the XML source)
//But leaves the possiblity that the browser might not request a fresh copy
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//And now we tell the browser that it expires immediately, and the cached copy you have should be refreshed
context.Response.Expires = -1;
context.Response.Cache.SetAllowResponseInBrowserHistory(true); //"works around an Internet Explorer bug"
doc.Save(context.Response.Output); //doc saves itself to the textwriter, using the encoding of the text-writer (which comes from response.contentEncoding)
#region Notes
/*
* 1. Use Response.Output, and NOT Response.OutputStream.
* Both are streams, but Output is a TextWriter.
* When an XmlDocument saves itself to a TextWriter, it will use the encoding
* specified by the TextWriter. The XmlDocument will automatically change any
* XML declaration node, i.e.:
* <?xml version="1.0" encoding="ISO-8859-1"?>
* to match the encoding used by the Response.Output's encoding setting
* 2. The Response.Output TextWriter's encoding settings comes from the
* Response.ContentEncoding value.
* 3. Use doc.Save, not Response.Write(doc.ToString()) or Response.Write(doc.InnerXml)
* 3. You DON'T want to save the XML to a string, or stuff the XML into a string
* and response.Write that, because that
* - doesn't follow the encoding specified
* - wastes memory
*
* To sum up: by Saving to a TextWriter: the XML Declaration node, the XML contents,
* and the HTML Response content-encoding will all match.
*/
#endregion Notes
}
private XmlDocument GetXmlToShow(HttpContext context)
{
//Use context.Request to get the account number they want to return
//GET /GetPatronInformation.ashx?accountNumber=619
//Or since this is sample code, pull XML out of your rear:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Patron><Name>Rob Kennedy</Name></Patron>");
return doc;
}
public bool IsReusable { get { return false; } }
}
I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
If you are using Bootstrap 4, you can simple use a color utility class (e.g. text-success
, text-danger
, etc... ).
You can also create your own classes (e.g. text-my-own-color
)
Both options are shown in the example below, run the code snippet to see a live demo.
.text-my-own-color {
color: #663300 !important; // Define your own color in your CSS
}
.text-my-own-color:hover, .text-my-own-color:active {
color: #664D33 !important; // Define your own color's darkening/lightening in your CSS
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="navbar-collapse">
<ul class="nav pull-right">
<!-- Bootstrap's color utility class -->
<li class="active"><a class="text-success" href="#">? ???</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-danger" href="#">??? ??? ????????</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-warning" href="#">????</a></li>
<!-- Custom color utility class -->
<li><a class="text-my-own-color" href="#">????????</a></li>
</ul>
</div>
_x000D_
Could do this, but then the user has to separate the numbers by a space:
#include "stdio.h"
int main()
{
int minx, x, y, z;
printf("Enter four ints: ");
scanf( "%i %i %i %i", &minx, &x, &y, &z);
printf("You wrote: %i %i %i %i", minx, x, y, z);
}
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
Simply mark any method you need to fake as virtual
(and not private). Then you will be able to create a fake that can override the method.
If you use new Mock<Type>
and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
If you have a code like
int arr[10] = {0, 5, 3, 64};
, and you want to append or add a value to next index, you can simply add it by typing a[5] = 5
.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8
to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append()
you can do it by continued indices.
There are several options, including using the method you demonstrate, With, and using a variable.
My preference is option 4 below: Dim
a variable of type Worksheet
and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.
Sub Test()
Dim SheetName As String
Dim SearchText As String
Dim FoundRange As Range
SheetName = "test"
SearchText = "abc"
' 0. If you know the sheet is the ActiveSheet, you can use if directly.
Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
' Since I usually have a lot of Subs/Functions, I don't use this method often.
' If I do, I store it in a variable to make it easy to change in the future or
' to pass to functions, e.g.: Set MySheet = ActiveSheet
' If your methods need to work with multiple worksheets at the same time, using
' ActiveSheet probably isn't a good idea and you should just specify the sheets.
' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)
' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
' sheet names use the title/name of the worksheet, however the name must
' be a valid VBA identifier (no spaces or special characters. Use the Object
' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)
' 3. Using "With" (more efficient than #1)
With Sheets(SheetName)
Set FoundRange = .UsedRange.Find(What:=SearchText)
End With
' or possibly...
With Sheets(SheetName).UsedRange
Set FoundRange = .Find(What:=SearchText)
End With
' 4. Using Worksheet variable (more efficient than 1)
Dim MySheet As Worksheet
Set MySheet = Worksheets(SheetName)
Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)
' Calling a Function/Sub
Test2 Sheets(SheetName) ' Option 1
Test2 Sheet1 ' Option 2
Test2 MySheet ' Option 4
End Sub
Sub Test2(TestSheet As Worksheet)
Dim RowIndex As Long
For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
' Do something
End If
Next RowIndex
End Sub
Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.
The positive sides of this approach are:
<DtoType>
() is all you needLinqHelper.cs:
public static IQueryable<TResult> Transform<TResult>(this IQueryable source)
{
var resultType = typeof(TResult);
var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);
ParameterExpression s = Expression.Parameter(source.ElementType, "s");
var memberBindings =
resultProperties.Select(p =>
Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType<MemberBinding>();
Expression memberInit = Expression.MemberInit(
Expression.New(typeof(TResult)),
memberBindings
);
var memberInitLambda = Expression.Lambda(memberInit, s);
var typeArgs = new[]
{
source.ElementType,
memberInit.Type
};
var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);
var query = source.Provider.CreateQuery<TResult>(mc);
return query;
}
public static IEnumerable<TResult> Transform<TResult>(this IEnumerable source)
{
return source.AsQueryable().Transform<TResult>();
}
Open Android AVD Manager: Tools -> Android -> AVD Manager and create an emulator:
This works for me.
The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
height = mImageView.getHeight();
width = mImageView.getWidth();
}
QUESTION was: suppose T john is to be converted john T, how to change in excel?
If text "T john" is in cell A1
=CONCATENATE(RIGHT(A1,LEN(A1)-2)," ",LEFT(A1,1))
and with a nod to the & crowd
=RIGHT(A1,LEN(A1)-2)&" "&LEFT(A1,1)
takes the right part of the string excluding the first 2 characters, adds a space, adds the first character.
Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.
# import time and OS modules to use to build file folder name
import time
import os
# Build string for directory to hold files
# Output Configuration
# drive_letter = Output device location (hard drive)
# folder_name = directory (folder) to receive and store PDF files
drive_letter = r'D:\\'
folder_name = r'downloaded-files'
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
folder_to_save_files = drive_letter + folder_name + folder_time
# IF no such folder exists, create one automatically
if not os.path.exists(folder_to_save_files):
os.mkdir(folder_to_save_files)
A simple way of looking at HTTP 301 vs. 302 redirects is:
Suppose you have a bookmark to "http://sample.com/sample". You use a browser to go there.
A 302 redirect to a different URL at this point would mean that you should keep your bookmark to "http://sample.com/sample". This is because the destination URL may change in the future.
A 301 redirect to a different URL would mean that your bookmark should change to point to the new URL as it is a permanent redirect.
If you wish to use a password in the command line, I've found that this works for filtering out the specific error message:
mysqlcommand 2>&1 | grep -v "Warning: Using a password"
It's basically redirecting standard error to standard output -- and using grep to drop all lines that match "Warning: Using a password".
This way, you can see any other output, including errors. I use this for various shell scripts, etc.
As per java doc's
Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent".
A concurrent collection is thread-safe, but not governed by a single exclusion lock.
In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability.
In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.
You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
Try to wrap wsdlLocation in wsdlUrls
<wsdlUrls>
<wsdlLocation>http://url</wsdlLocation>
</wsdlUrls>
For those of you who prefer a quick and dirty approach, just list all the columns that together define a unique record and create a unique index with those columns, like so:
ALTER IGNORE TABLE TABLE_NAME
ADD UNIQUE (column1
,column2
,column3
)
You can drop the unique index afterwords.
If it is running in the Python shell use Ctrl + Z, otherwise locate the python
process and kill it.
This can be done in three simple steps:
1) Add item id with url
tag:
{% for item in post %}
<tr>
<th>{{ item.id }}</th>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>
<a href={% url 'edit' id=item.id %}>Edit</a>
<a href={% url 'delete' id=item.id %}>Delete</a>
</td>
</tr>
{% endfor %}
2) Add path to urls.py:
path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')
3) Use the id on views.py:
def delete(request, id):
obj = post.objects.get(id=id)
obj.delete()
return redirect('dashboard')
Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on IEnumerable<T>
where T
is or derives from DataRow
. You can select r
the row object to call CopyToDataTable on it.
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == c_to &&
r.Field<string>("p_to") == p_to
select r;
DataTable conversions = query.CopyToDataTable();
You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.
In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:
$(function() {
$(".draggable").draggable({
opacity: .4,
create: function(){$(this).data('position',$(this).position())},
cursor:'move',
start:function(){$(this).stop(true,true)}
});
$('.active').droppable({
over: function(event, ui) {
$(ui.helper).unbind("mouseup");
},
drop:function(event, ui){
snapToMiddle(ui.draggable,$(this));
},
out:function(event, ui){
$(ui.helper).mouseup(function() {
snapToStart(ui.draggable,$(this));
});
}
});
});
function snapToMiddle(dragger, target){
var topMove = target.position().top - dragger.data('position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
var leftMove= target.position().left - dragger.data('position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
dragger.animate({top:topMove,left:leftMove},{duration:600,easing:'easeOutBack'});
}
function snapToStart(dragger, target){
dragger.animate({top:0,left:0},{duration:600,easing:'easeOutBack'});
}
Try this:
self.ff_driver = Firefox()
self.ff_driver.maximize_window()
Or if you want a simple one-liner:
Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);
You don't want to use .toString()
.
Notice that SecretKey inherits from java.security.Key, which itself inherits from Serializable. So the key here (no pun intended) is to serialize the key into a ByteArrayOutputStream, get the byte[] array and store it into the db. The reverse process would be to get the byte[] array off the db, create a ByteArrayInputStream offf the byte[] array, and deserialize the SecretKey off it...
... or even simpler, just use the .getEncoded()
method inherited from java.security.Key (which is a parent interface of SecretKey). This method returns the encoded byte[] array off Key/SecretKey, which you can store or retrieve from the database.
This is all assuming your SecretKey implementation supports encoding. Otherwise, getEncoded()
will return null.
You should look at the Key/SecretKey javadocs (available right at the start of a google page):
http://download.oracle.com/javase/6/docs/api/java/security/Key.html
Or this from CodeRanch (also found with the same google search):
http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or
You could simply use a target from your link, such as #someid, where #someid is the div's id.
Or, you could use any number of scrolling plugins that make this more elegant.
http://plugins.jquery.com/project/ScrollTo is an example.
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
Instead of using to remove a CR/LF between elements, I use the SGML processing instruction because minifiers often remove the comments, but not the XML PI. When the PHP PI is processed by PHP, it has the additional benefit of removing the PI completely along with the CR/LF in between, thus saving at least 8 bytes. You can use any arbitrary valid instruction name such as and save two bytes in X(HT)ML.
The simple example presented on Wikipedia worked for me. (you can read the complete description at http://en.wikipedia.org/wiki/Circular_dependency#Example_of_circular_dependencies_in_C.2B.2B )
File '''a.h''':
#ifndef A_H
#define A_H
class B; //forward declaration
class A {
public:
B* b;
};
#endif //A_H
File '''b.h''':
#ifndef B_H
#define B_H
class A; //forward declaration
class B {
public:
A* a;
};
#endif //B_H
File '''main.cpp''':
#include "a.h"
#include "b.h"
int main() {
A a;
B b;
a.b = &b;
b.a = &a;
}
This directive works as a [routerLink] replacement. All you have to do is to replace your [routerLink] usages with [link]. It works with ctrl+click, cmd+click, middle click.
import {Directive, HostListener, Input} from '@angular/core'
import {Router} from '@angular/router'
import _ from 'lodash'
import qs from 'qs'
@Directive({
selector: '[link]'
})
export class LinkDirective {
@Input() link: string
@HostListener('click', ['$event'])
onClick($event) {
// ctrl+click, cmd+click
if ($event.ctrlKey || $event.metaKey) {
$event.preventDefault()
$event.stopPropagation()
window.open(this.getUrl(this.link), '_blank')
} else {
this.router.navigate(this.getLink(this.link))
}
}
@HostListener('mouseup', ['$event'])
onMouseUp($event) {
// middleclick
if ($event.which == 2) {
$event.preventDefault()
$event.stopPropagation()
window.open(this.getUrl(this.link), '_blank')
}
}
constructor(private router: Router) {}
private getLink(link): any[] {
if ( ! _.isArray(link)) {
link = [link]
}
return link
}
private getUrl(link): string {
let url = ''
if (_.isArray(link)) {
url = link[0]
if (link[1]) {
url += '?' + qs.stringify(link[1])
}
} else {
url = link
}
return url
}
}
To Check JTextFiled is empty or not condition:
if( (billnotf.getText().length()==0)||(billtabtf.getText().length()==0))
Easy quick solution which worked for me. 1. Go to the root folder. Copy the default.aspx file. 2. Delete the original file. 3. Rename the copied file to default.aspx.
Its all set to experiment again. Not sure how sharepoint referencing these webparts in that page. But works :)
If you use NumPy 1.15 (released 2018-07-23) or newer, you can use the printoptions
context manager:
with numpy.printoptions(threshold=numpy.inf):
print(arr)
(of course, replace numpy
by np
if that's how you imported numpy
)
The use of a context manager (the with
-block) ensures that after the context manager is finished, the print options will revert to whatever they were before the block started. It ensures the setting is temporary, and only applied to code within the block.
See numpy.printoptions
documentation for details on the context manager and what other arguments it supports.
Swift 4
let webView = UIWebView(frame: view.bounds)
let targetURL = Bundle.main.url(forResource: "sampleFileName", withExtension: "pdf")
let request = URLRequest(url: targetURL!)
webView.loadRequest(request)
view.addSubview(webView)
To uninstall a module using npm, you can use:
npm uninstall moduleName
Also, if you want to uninstall and want the change to be reflected in your package.json then you can use the --save flag, like this:
npm uninstall moduleName --save
OR
npm uninstall -S
And if you want to uninstall a module from devDependencies and want the change to be reflected in package.json then you can use -D flag, like this:
npm uninstall moduleName -D
Found the problem, I was including another jquery file for my google translator, they were conflicting with each other and resulting in not loading the autocomplete function.
GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.
The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).
Assuming you mean UNIX shell commands, just run
echo >> file.txt
echo
prints a newline, and the >>
tells the shell to append that newline to the file, creating if it doesn't already exist.
In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use
echo > file.txt
EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do
test -e file.txt || echo > file.txt
At least that works in Bash, I'm not sure if it also does in other shells.
You need to go to Help>Eclipse Marketplace . Then type server in the search box it will display Eclipse JST Server Adapters (Apache Tomcat,...) .Select that one and install it .Then go back to Window>Preferences>Server>Runtime Environnement, click add choose Apache tomcat version then add the installation directory .
Easy. To change a time value like: 1:00:15 to text, you can use the 'TEXT' function. Example, if your time value (1:00:15) is contained in cell 'A1', you can convert it into a text by doing: Text(A1, "h:mm:ss"). The result still looks the same: 1:00:15. But notice that this time round, it has become a text value.
The last place I worked was primarily a C++ shop, and before I was hired my boss (who was the director of research and development) had issued a decree that "dynamic memory allocation is not allowed". No "new", not even a "malloc" -- because "those can lead to memory leaks if a developer forgets the corresponding delete/free operation". As a corollary to this particular rule, "pointers are also not allowed" (although references were totally acceptable, being both awesome and safe).
I repealed those rules (as opposed to, say, rewriting all our software in other languages) but I did have to add a few awesome rules of my own, like "you may not launch a new thread without written approval from someone qualified to do that sort of thing" based on an unfortunate series of code reviews (sigh).
I was facing the same issue with MSBuild for VS 17
I solved this by applying the following steps:
In my case the Microsoft.Cpp.Default.props
file was located at C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets
so I created VCTragetsPath
string in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
with value
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets
I also made my Jenkins run as an admin user
This solved my issue.
In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.
The script uses python websocket-client and pusher_client_python libraries, so install them.
#!/usr/bin/python
import pusherclient
import time
import logging
import sys
import datetime
import signal
import os
logging.basicConfig()
log_file_fd = None
def sigint_and_sigterm_handler(signal, frame):
global log_file_fd
log_file_fd.close()
sys.exit(0)
class BitstampLogger:
def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
self.channel = channel
self.event = event
self.log_file_fd = open(log_file_path, "a")
self.log_file_reload_path = log_file_reload_path
self.pusher = pusherclient.Pusher(pusher_key)
self.pusher.connection.logger.setLevel(logging.WARNING)
self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
self.pusher.connect()
def callback(self, data):
utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
line = str(utc_timestamp) + " " + data + "\n"
if os.path.exists(self.log_file_reload_path):
os.remove(self.log_file_reload_path)
self.log_file_fd.close()
self.log_file_fd = open(log_file_path, "a")
self.log_file_fd.write(line)
def connect_handler(self, data):
channel = self.pusher.subscribe(self.channel)
channel.bind(self.event, self.callback)
def main(log_file_path, log_file_reload_path):
global log_file_fd
bitstamp_logger = BitstampLogger(
log_file_path,
log_file_reload_path,
"de504dc5763aeef9ff52",
"live_trades",
"trade")
log_file_fd = bitstamp_logger.log_file_fd
signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
while True:
time.sleep(1)
if __name__ == '__main__':
log_file_path = sys.argv[1]
log_file_reload_path = sys.argv[2]
main(log_file_path, log_file_reload_path
and logrotate file config
/mnt/data/bitstamp_logs/bitstamp-trade.log
{
rotate 10000000000
minsize 10M
copytruncate
missingok
compress
postrotate
touch /mnt/data/bitstamp_logs/reload_log > /dev/null
endscript
}
then you can run it on background
nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &
Is there a command that does?
thread apply all where
As of PowerShell 6.0, Split-Path
has an -Extenstion
parameter. This means you can do:
$path | Split-Path -Extension
or
Split-Path -Path $path -Extension
For $path = "test.txt"
both versions will return .txt
, inluding the full stop.
I'd recommend checking out json-stringify-safe from @isaacs-- it's used in NPM.
BTW- if you're not using Node.js, you can just copy and paste lines 4-27 from the relevant part of the source code.
To install:
$ npm install json-stringify-safe --save
To use:
// Require the thing
var stringify = require('json-stringify-safe');
// Take some nasty circular object
var theBigNasty = {
a: "foo",
b: theBigNasty
};
// Then clean it up a little bit
var sanitized = JSON.parse(stringify(theBigNasty));
This yields:
{
a: 'foo',
b: '[Circular]'
}
Note that, just like with the vanilla JSON.stringify function as @Rob W mentioned, you can also customize the sanitization behavior by passing in a "replacer" function as the second argument to
stringify()
. If you find yourself needing a simple example of how to do this, I just wrote a custom replacer which coerces errors, regexps, and functions into human-readable strings here.
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
Here's a macro that allows you to shuffle selected cells in a column:
Option Explicit
Sub ShuffleSelectedCells()
'Do nothing if selecting only one cell
If Selection.Cells.Count = 1 Then Exit Sub
'Save selected cells to array
Dim CellData() As Variant
CellData = Selection.Value
'Shuffle the array
ShuffleArrayInPlace CellData
'Output array to spreadsheet
Selection.Value = CellData
End Sub
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim J As Long, _
N As Long, _
Temp As Variant
'Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If J <> N Then
Temp = InArray(N, 1)
InArray(N, 1) = InArray(J, 1)
InArray(J, 1) = Temp
End If
Next N
End Sub
You can read the comments to see what the macro is doing. Here's how to install the macro:
Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).
The quick and dirty way would be to simple bind to the keyup
event.
$('#mytxt').keyup(function(){_x000D_
$('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup
)
A simple way is to set line-height
to the height of the element.
kent's article gave me a new idea. this runCommand method doesn't need a script file, just runs a command by a line:
- (NSString *)runCommand:(NSString *)commandToRun
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command:%@", commandToRun);
[task setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return output;
}
You can use this method like this:
NSString *output = runCommand(@"ps -A | grep mysql");
.add_to_cart >>> .form-item:eq(1)
the second .form-item at tree level child from the .add_to_cart
You probably don't want to do this:
#include "client.cpp"
A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.
Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS
, however, each file that has #include "client.cpp"
is built independently and as such will find SOCKET_CLIENT_CLASS
not yet defined. Therefore it's contents will be included, not #ifdef'd out.
If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.
1 minute googling gave me this result. See the DEMO!
HTML
<form>
<label for="username">Username:</label>
<input id="username" name="username" type="text" placeholder="Username" />
<label for="password">Password:</label>
<input id="password" name="password" type="password" placeholder="Password" />
<input id="submit" name="submit" type="submit" value="Login" />
</form>
jQuery
// ----- Setup: Add dummy text field for password and add toggle link to form; "offPage" class moves element off-screen
$('input[type=password]').each(function () {
var el = $(this),
elPH = el.attr("placeholder");
el.addClass("offPage").after('<input class="passText" placeholder="' + elPH + '" type="text" />');
});
$('form').append('<small><a class="togglePassText" href="#">Toggle Password Visibility</a></small>');
// ----- keep password field and dummy text field in sync
$('input[type=password]').keyup(function () {
var elText = $(this).val();
$('.passText').val(elText);
});
$('.passText').keyup(function () {
var elText = $(this).val();
$('input[type=password]').val(elText);
});
// ----- Toggle link functionality - turn on/off "offPage" class on fields
$('a.togglePassText').click(function (e) {
$('input[type=password], .passText').toggleClass("offPage");
e.preventDefault(); // <-- prevent any default actions
});
CSS
.offPage {
position: absolute;
bottom: 100%;
right: 100%;
}
You don't show us the declaration of carBootSaleList
. However from the exception message I can see that it is of type CarBootSaleList
. This type doesn't implement the IEnumerable
interface and therefore cannot be used in a foreach.
Your CarBootSaleList
class should implement IEnumerable<CarBootSale>
:
public class CarBootSaleList : IEnumerable<CarBootSale>
{
private List<CarBootSale> carbootsales;
...
public IEnumerator<CarBootSale> GetEnumerator()
{
return carbootsales.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return carbootsales.GetEnumerator();
}
}
Quicksort is in place. You just need to swap positions of data during the Partitioning function. Mergesort requires a lot more data copying. You need another temporary storage (typically the same size as your original data array) for the Merge function.
Note that services and tools for sending emails may be able to inline your CSS for you, allowing CSS in <style>
tags to work in Gmail.
For instance, if you're sending emails with MailChimp, your CSS from <style>
tags will get inlined automatically by default. With Mandrill, you can enable this functionality (although it's disabled by default for performance reasons) by checking the "Inline CSS Styles in HTML Emails" box in the "Sending Defaults" section of the Settings tab:
Try removing the position
from header
and add overflow
to container
:
#container {
position:relative;
width:80%;
height:auto;
overflow:auto;
}
#header {
width:80%;
height:50px;
padding:10px;
}
The Process
class has a member StartInfo
that you should check out:
This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com
yield is more flexible than map(), see example below
val aList = List( 1,2,3,4,5 )
val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.map( _+ 1 > 3 )
println( res3 )
println( res4 )
yield will print result like: List(5, 6), which is good
while map() will return result like: List(false, false, true, true, true), which probably is not what you intend.
Use this Code in code behind
Div_Card.Style["background-image"] = Page.ResolveUrl(Session["Img_Path"].ToString());
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
int is a binary representation of a whole number, double is a double-precision floating point number.
Just had a similar problem trying to use SoapClient. Everything was working fine but in production, sometimes on page refresh, I would get the "SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from .." error.
I was using the params:
new \SoapClient($WSDL, array('cache_wsdl' => WSDL_CACHE_NONE, 'trace' => true, "exception" => 0));
Removing all the params worked for me:
new \SoapClient($WSDL);
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0
(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:
levels(df$species) <- c(levels(df$species), "unknown")
df$species[df$depth<10] <- "unknown"
If using jruby, here is a code snippet to return an array of all tables in a db.
require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"
def get_database_tables(connection, db_name)
md = connection.get_meta_data
rs = md.get_tables(db_name, nil, '%',["TABLE"])
tables = []
count = 0
while rs.next
tables << rs.get_string(3)
end #while
return tables
end
Here is one test you can do to see how the bare
server stuff work:
Imagine you have a workstation and a server with live site hosted on it, and you want to update this site from time to time (this also applies to a situation where two developers are sending their work back and forth through a bare middleman).
Create some directory on your local computer and cd
into it, then execute these commands:
# initialization
git init --bare server/.git
git clone server content
git clone server local
server
directory (notice the .git at the end). This directory will serve as a container for your repository files only.content
directory. This is your live/production directory which will be served by your server software.Now here is the basic workflow:
Enter the local
directory, create some files and commit them. Finally push them to the server:
# create crazy stuff
git commit -av
git push origin master
Now enter the content
directory and update the server's content:
git pull
Repeat 1-2. Here content
may be another developer that can push to the server too, and local
as you may pull from him.
I'd say the minimum would be to
Move:
var k = Math.pow(10, i);
above
var j = k / 10;
Here you go....
Im using the code below..
DATEPART(WK,@DATE_INSERT) - DATEPART(WK,DATEADD(DAY,1,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@DATE_INSERT),0)))) + 1
If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.
Here's a suggestion:
public class SuperClass {
public void method1() {
System.out.println("superclass method1");
this.internalMethod2();
}
public void method2() {
// this method can be overridden.
// It can still be invoked by a childclass using super
internalMethod2();
}
private void internalMethod2() {
// this one cannot. Call this one if you want to be sure to use
// this implementation.
System.out.println("superclass method2");
}
}
public class SubClass extends SuperClass {
@Override
public void method1() {
System.out.println("subclass method1");
super.method1();
}
@Override
public void method2() {
System.out.println("subclass method2");
}
}
If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
var name = from r in MyTable
where r.ID == 0
select r.Name;
If the row is unique then you could even just do:
var row = DataContext.MyTable.SingleOrDefault(r => r.ID == 0);
var name = row != null ? row.Name : String.Empty;
for those who does not choose BASH HERE option. type sh in cmd then they should have ssh-keygen.exe accessible
you can use the following extension and I think it is really good:
/// <summary>
/// Simplifies null checking
/// </summary>
public static TR Get<TF, TR>(TF t, Func<TF, TR> f)
where TF : class
{
return t != null ? f(t) : default(TR);
}
/// <summary>
/// Simplifies null checking
/// </summary>
public static TR Get<T1, T2, TR>(T1 p1, Func<T1, T2> p2, Func<T2, TR> p3)
where T1 : class
where T2 : class
{
return Get(Get(p1, p2), p3);
}
/// <summary>
/// Simplifies null checking
/// </summary>
public static TR Get<T1, T2, T3, TR>(T1 p1, Func<T1, T2> p2, Func<T2, T3> p3, Func<T3, TR> p4)
where T1 : class
where T2 : class
where T3 : class
{
return Get(Get(Get(p1, p2), p3), p4);
}
And it is used like this:
int value = Nulify.Get(objectA, x=>x.PropertyA, x=>x.PropertyB, x=>x.PropertyC);
Ultimately, .keystore
and .jks
are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore
: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks
extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).
In Java, the word keystore can have either of the following meanings, depending on the context:
When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.
Java uses its KeyStore
class and related API to make use of a keystore (whether it's file based or not). JKS
is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:
.jks
for type "JKS"
,.p12
or .pfx
for type "PKCS12"
(the specification name is PKCS#12, but the #
is not used in the Java keystore type name).In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks
extension), which is frequently used for Android applications.
I have a better solution for this problem,
var searchparams = await Request.GetSearchParams();
I have created a static class with few extension methods
public static class HttpRequestExtension
{
public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
{
var parameters = await request.TupledParameters();
try
{
for (var i = 0; i < parameters.Count; i++)
{
if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
{
parameters[i] = new Tuple<string, string>("_summary", "count");
}
}
var searchCommand = SearchParams.FromUriParamList(parameters);
return searchCommand;
}
catch (FormatException formatException)
{
throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
}
}
public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
var list = new List<Tuple<string, string>>();
var query = request.Query;
foreach (var pair in query)
{
list.Add(new Tuple<string, string>(pair.Key, pair.Value));
}
if (!request.HasFormContentType)
{
return list;
}
var getContent = await request.ReadFormAsync();
if (getContent == null)
{
return list;
}
foreach (var key in getContent.Keys)
{
if (!getContent.TryGetValue(key, out StringValues values))
{
continue;
}
foreach (var value in values)
{
list.Add(new Tuple<string, string>(key, value));
}
}
return list;
}
}
in this way you can easily access all your search parameters. I hope this will help many developers :)
You can elegantly add readonly in the widget:
class SurveyModaForm(forms.ModelForm):
class Meta:
model = Survey
fields = ['question_no']
widgets = {
'question_no':forms.NumberInput(attrs={'class':'form-control','readonly':True}),
}
It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations
You need to make sure that no other users of this repository are fetching the incorrect changes or trying to build on top of the commits that you want removed because you are about to rewind history.
Then you need to 'force' push the old reference.
git push -f origin last_known_good_commit:branch_name
or in your case
git push -f origin cc4b63bebb6:alpha-0.3.0
You may have receive.denyNonFastForwards
set on the remote repository. If this is the case, then you will get an error which includes the phrase [remote rejected]
.
In this scenario, you will have to delete and recreate the branch.
git push origin :alpha-0.3.0
git push origin cc4b63bebb6:refs/heads/alpha-0.3.0
If this doesn't work - perhaps because you have receive.denyDeletes
set, then you have to have direct access to the repository. In the remote repository, you then have to do something like the following plumbing command.
git update-ref refs/heads/alpha-0.3.0 cc4b63bebb6 83c9191dea8
Use below code:
// Variable to check
$email = "[email protected]";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("Email is a valid email address");
} else {
echo("Oppps! Email is not a valid email address");
}
IF EXIST "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" (
rmdir "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" /s /q
)
This will delete everything from the folder (and the folder itself).
The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText
, contains a string value.
In that constelation, the value cannot be displayed (it would get blank)
Example: http://jsfiddle.net/BmhNL/2/
My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type
= number
. If there is "only" a white-space issue, you can try to implicitly call the Number()
constructor, like
document.getElementById("points").value = +request.responseText;
The compiler looks for each symbol being used in the current translation unit is previously declared or not in the current unit. It is just a matter of style providing all method signatures at the beginning of a source file while definitions are provided later. The significant use of it is when you use a pointer to a class as member variable of another class.
//foo.h
class bar; // This is useful
class foo
{
bar* obj; // Pointer or even a reference.
};
// foo.cpp
#include "bar.h"
#include "foo.h"
So, use forward-declarations in classes when ever possible. If your program just has functions( with ho header files), then providing prototypes at the beginning is just a matter of style. This would be anyhow the case had if the header file was present in a normal program with header that has only functions.
psql -U username -d mydatabase -c 'SELECT * FROM mytable'
If you're new to postgresql and unfamiliar with using the command line tool psql
then there is some confusing behaviour you should be aware of when you've entered an interactive session.
For example, initiate an interactive session:
psql -U username mydatabase
mydatabase=#
At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;
For example:
mydatabase=# SELECT * FROM mytable;
If you forget the semicolon then when you hit enter you will get nothing on your return line because psql
will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.
As an experiment, try typing any garble you want at the psql prompt then hit enter. psql
will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:
mydatabase=# asdfs
mydatabase=# ;
ERROR: syntax error at or near "asdfs"
LINE 1: asdfs
^
The rule of thumb is:
If you received no response from psql
but you were expecting at least SOMETHING, then you forgot the semicolon ;
Apparently, the compiler thinks NSSearchPathDirectory:0
is an array, and of course it expects the type NSSearchPathDirectory
instead. Certainly not a helpful error message.
But as to the reasons:
First, you are confusing the argument names and types. Take a look at the function definition:
func NSSearchPathForDirectoriesInDomains(
directory: NSSearchPathDirectory,
domainMask: NSSearchPathDomainMask,
expandTilde: Bool) -> AnyObject[]!
directory
and domainMask
are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.So that leaves us with (updated for Swift 2.0):
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
and for Swift 3:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
<?php
$sessionDetails = $this->Session->read('Auth.User');
if (!empty($sessionDetails)) {
$loginFlag = 1;
# code...
}else{
$loginFlag = 0;
}
?>
<script type="text/javascript">
var sessionValue = '<?php echo $loginFlag; ?>';
if (sessionValue = 0) {
//model show
}
</script>
@Amirali
console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");
throws:
Uncaught TypeError: document.getElementById(...).attribute is not a function
in chrome.
Element exists and is dumped in console;
Explicitly Target IE versions without hacks using HTML and CSS
Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html>
element so you can select based on browser later.
Example
<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head></head>
<body></body>
</html>
Then in your CSS you can very strictly access your target browser.
Example
.ie6 body {
border:1px solid red;
}
.ie7 body {
border:1px solid blue;
}
For more information check out http://html5boilerplate.com/
Target IE versions with CSS "Hacks"
More to your point, here are the hacks that let you target IE versions.
Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.
Example:
body {
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}
Update: Target IE10
IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html>
element
<!doctype html>
<html lang="en">
<!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
<head></head>
<body></body>
</html>
(EXCEL 2016 and later, actually I have not tried in older versions)
You can truncate all information after the month using date_trunc(text, timestamp)
:
select date_trunc('month',created_at)::date as date
from orders
order by date DESC;
created_at = '2019-12-16 18:28:13'
Output 1:
date_trunc('day',created_at)
// 2019-12-16 00:00:00
Output 2:
date_trunc('day',created_at)::date
// 2019-12-16
Output 3:
date_trunc('month',created_at)::date
// 2019-12-01
Output 4:
date_trunc('year',created_at)::date
// 2019-01-01
Service
extends ContextWrapper
ContextWrapper
extends Context
So....
Context context = this;
(in Service or Activity Class)
It seems that k8s expects us to provide a different image tag for every deployment. My default strategy would be to make the CI system generate and push the docker images, tagging them with the build number: xpmatteo/foobar:456
.
For local development it can be convenient to use a script or a makefile, like this:
# create a unique tag
VERSION:=$(shell date +%Y%m%d%H%M%S)
TAG=xpmatteo/foobar:$(VERSION)
deploy:
npm run-script build
docker build -t $(TAG) .
docker push $(TAG)
sed s%IMAGE_TAG_PLACEHOLDER%$(TAG)% foobar-deployment.yaml | kubectl apply -f - --record
The sed
command replaces a placeholder in the deployment document with the actual generated image tag.
Create Procedure in MYsql.
delimiter //
create procedure SP_Dasboarddata(fromdate date, todate date)
begin
select count(Id) as count,date,status,sum(amount) as amount from
details
where (Emidate between fromdate and todate)
group by date ,status;
END;
//
Create class which contains stored procedure return result set values
[Table("SP_reslutclass")]
public class SP_reslutclass
{
[Key]
public int emicount { get; set; }
public DateTime Emidate { get; set; }
public int ? Emistatus { get; set; }
public int emiamount { get; set; }
}
Add Class in Dbcontext
public class ABCDbContext:DbContext
{
public ABCDbContext(DbContextOptions<ABCDbContext> options)
: base(options)
{
}
public DbSet<SP_reslutclass> SP_reslutclass { get; set; }
}
Call entity in repository
var counts = _Dbcontext.SP_reslutclass.FromSql("call SP_Dasboarddata
('2019-12-03','2019-12-31')").ToList();
Just put your file.exe in the \bin\Debug folder and use:
Process.Start("File.exe");
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
I've worked with excel jetcell for a long time and can really recommend it. http://www.devtriogroup.com/exceljetcell
Android Studio -> Device File Explorer (right bottom corner) -> data -> data -> {package.id} -> shared-prefs
Note: You need to connect mobile device to android studio and selected application should be in debug mode
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
For best performance I recommend doing DataFrame.drop_duplicates
followed up aggfunc='count'
.
Others are correct that aggfunc=pd.Series.nunique
will work. This can be slow, however, if the number of index
groups you have is large (>1000).
So instead of (to quote @Javier)
df2.pivot_table('X', 'Y', 'Z', aggfunc=pd.Series.nunique)
I suggest
df2.drop_duplicates(['X', 'Y', 'Z']).pivot_table('X', 'Y', 'Z', aggfunc='count')
This works because it guarantees that every subgroup (each combination of ('Y', 'Z')
) will have unique (non-duplicate) values of 'X'
.
Pandas has the itertuples
method to do exactly this:
list(df[['lat', 'long']].itertuples(index=False, name=None))
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
This is your adapter
class yourAdapter extends BaseAdapter {
Context context;
String[] data;
private static LayoutInflater inflater = null;
public yourAdapter(Context context, String[] data) {
// TODO Auto-generated constructor stub
this.context = context;
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.row, null);
TextView text = (TextView) vi.findViewById(R.id.text);
text.setText(data[position]);
return vi;
}
}
public class StackActivity extends Activity {
ListView listview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(new yourAdapter(this, new String[] { "data1",
"data2" }));
}
}
There's actually quite a simple native method for this:
if( $('#myfav')[0].hasChildNodes() ) { ... }
Note that this also includes simple text nodes, so it will be true for a <div>text</div>
.
You can just check for null
:
if(Request.QueryString["aspxerrorpath"]!=null)
{
//your code that depends on aspxerrorpath here
}
function parsehhmmsst(arg) {_x000D_
var result = 0, arr = arg.split(':')_x000D_
if (arr[0] < 12) {_x000D_
result = arr[0] * 3600 // hours_x000D_
}_x000D_
result += arr[1] * 60 // minutes_x000D_
result += parseInt(arr[2]) // seconds_x000D_
if (arg.indexOf('P') > -1) { // 8:00 PM > 8:00 AM_x000D_
result += 43200_x000D_
}_x000D_
return result_x000D_
}_x000D_
$('body').append(parsehhmmsst('12:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('1:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('2:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('3:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('4:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('5:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('6:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('7:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('8:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('9:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('10:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('11:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('12:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('1:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('2:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('3:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('4:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('5:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('6:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('7:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('8:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('9:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('10:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('11:00:00 PM') + '<br>')
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
whatever you all do, the best way is to take the short_name for the specified language, i.e.: fr, en, nl, de, it, etc... and assign the same to a global value.
make a picker view to pop up like a drop down menu (combination of a button on click of which a picker view appears from below with a list of languages) and select the language you desire. let the short name be stored internally. make a .h + .m file named LocalisedString.
Set the global value of short_name to be equal to the obtained value in LocalisedString.m When the required language is selected assign the NSBundlePath to create project sub-directories for the needed language. for eg, nl.proj, en.proj.
When the particular proj folder is selected call the localised string for the respective language and change the language dynamically.
no rules broken.
After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element
But I found new to do this using default_structure_element like following...
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef struct subject {
string name;
int marks;
int credits;
}subject;
int main(){
subject default_subject;
default_subject.name="NONE";
default_subject.marks = 0;
default_subject.credits = 0;
vector <subject> sub(10,default_subject); // default_subject to initialize
//to check is it initialised
for(ll i=0;i<sub.size();i++) {
cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
}
}
Then I think its good to way to initialize a vector of the struct, isn't it?
Quick and simple, but not good for production:
(in a view)
request.scheme # http or https
request.META['HTTP_HOST'] # example.com
request.path # /some/content/1/
(in a template)
{{ request.scheme }} :// {{ request.META.HTTP_HOST }} {{ request.path }}
Be sure to use a RequestContext, which is the case if you're using render.
Don't trust request.META['HTTP_HOST']
in production: that info comes from the browser. Instead, use @CarlMeyer's answer
Since it is bypassing CORS and CSP, this is to keep in the toolbox. Here is a variation.
This will POST a base64 encoded object at localhost:8080
, and will clean up the DOM after usage.
const theOBJECT = {message: 'Hello world!', target: 'local'}_x000D_
_x000D_
document.body.innerHTML += '<iframe id="postframe" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe><form id="dynForm" target="hiddenFrame" action="http://localhost:8080/" method="post"><input type="hidden" name="somedata" value="'+btoa(JSON.stringify(theOBJECT))+'"></form>';_x000D_
document.getElementById("dynForm").submit();_x000D_
dynForm.outerHTML = ""_x000D_
postframe.outerHTML = ""
_x000D_
From the network debugger tab, we can observe a successful POST to a http://
unencrypted server from a tls/https
page.
Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely
and up:
# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely
# Options
$option1 = New-ScheduledJobOption –StartIfIdle
$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"
Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
Timestamp is a Date: https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
java.lang.Object
java.util.Date
java.sql.Timestamp
Saty described the differences between them. For your practice, you can use datetime
in order to keep the output of NOW()
.
For example:
CREATE TABLE Orders
(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (OrderId)
)
You can read more at w3schools.
In answer to the further question -
"is there anyway to apply this within the Visual Studio project? In a multi-developer environment, if someone else check's out the code on their machine, then their local IIS Express wouldn't be configured with the virtual directory and cause runtime errors wouldn't it?"
I never found a consistant answer to this anywhere but then figured out you could do it with a post build event using the XmlPoke task in the project file for the website -
<Target Name="AfterBuild">
<!-- Get the local directory root (and strip off the website name) -->
<PropertyGroup>
<LocalTarget>$(ProjectDir.Replace('MyWebSite\', ''))</LocalTarget>
</PropertyGroup>
<!-- Now change the virtual directories as you need to -->
<XmlPoke XmlInputPath="..\..\Source\Assemblies\MyWebSite\.vs\MyWebSite\config\applicationhost.config"
Value="$(LocalTarget)AnotherVirtual"
Query="/configuration/system.applicationHost/sites/site[@name='MyWebSite']/application[@path='/']/virtualDirectory[@path='/AnotherVirtual']/@physicalPath"/>
</Target>
You can use this technique to repoint anything in the file before IISExpress starts up. This would allow you to initially force an applicationHost.config file into GIT (assuming it is ignored by gitignore) then subsequently repoint all the paths at build time. GIT will ignore any changes to the file so it's now easy to share them around.
In answer to the futher question about adding other applications under one site:
You can create the site in your application hosts file just like the one on your server. For example:
<site name="MyWebSite" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\MyWebSite\Main" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<application path="/AppSubSite" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\AppSubSite\" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:4076:localhost" />
</bindings>
</site>
Then use the above technique to change the folder locations at build time.
In XSLT 1.0 the upper-case()
and lower-case()
functions are not available.
If you're using a 1.0 stylesheet the common method of case conversion is translate()
:
<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:template match="/">
<xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>
KeyedCollection works like dictionary and is serializable.
First create a class containing key and value:
/// <summary>
/// simple class
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCulture
{
/// <summary>
/// culture
/// </summary>
public string culture;
/// <summary>
/// word list
/// </summary>
public List<string> list;
/// <summary>
/// status
/// </summary>
public string status;
}
then create a class of type KeyedCollection, and define a property of your class as key.
/// <summary>
/// keyed collection.
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCultures : System.Collections.ObjectModel.KeyedCollection<string, cCulture>
{
protected override string GetKeyForItem(cCulture item)
{
return item.culture;
}
}
Usefull to serialize such type of datas.
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;
Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.
2 steps to check if a cronjob is working :
Manually run php command :
/usr/bin/php /mydomain.in/cromail.php
And check if any error is displayed
Just use HTML anchor tag <a>
and start the attribute href
with tel:
. I suggest starting the phone number with the country code. pay attention to the following example:
<a href="tel:+989123456789">NO Different What it is</a>
For this example, the country code is +98
.
Hint: It is so suitable for cellphones, I know tel:
prefix calls FaceTime
on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.
For more information: you can visit the list of URL schemes supported by browsers to know all href
values prefixes.
Ruby FTW:
ls | ruby -e 'puts STDIN.readlines.shuffle'
in Global.asax add
public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
give it a shot ;)
use - !important - to override default black
.fa-heart:hover{_x000D_
color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
In Kotlin:
recyclerView.viewTreeObserver.addOnGlobalLayoutListener { scrollToEnd() }
private fun scrollToEnd() =
(adapter.itemCount - 1).takeIf { it > 0 }?.let(recyclerView::smoothScrollToPosition)
Here's a fairly unconventional (but fast) approach: use fwrite
from data.table
to "paste" the columns together, and fread
to read it back in. For convenience, I've written the steps as a function called fpaste
:
fpaste <- function(dt, sep = ",") {
x <- tempfile()
fwrite(dt, file = x, sep = sep, col.names = FALSE)
fread(x, sep = "\n", header = FALSE)
}
Here's an example:
d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i'))
cols = c("b", "c", "d")
fpaste(d[cols], "-")
# V1
# 1: a-d-g
# 2: b-e-h
# 3: c-f-i
How does it perform?
d2 <- d[sample(1:3,1e6,TRUE),]
library(microbenchmark)
microbenchmark(
docp = do.call(paste, c(d2[cols], sep="-")),
tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
fpaste = fpaste(d2[cols], "-")$V1,
dt2 = as.data.table(d2)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols][],
times=10)
# Unit: milliseconds
# expr min lq mean median uq max neval
# docp 215.34536 217.22102 220.3603 221.44104 223.27224 225.0906 10
# tidr 215.19907 215.81210 220.7131 220.09636 225.32717 229.6822 10
# docs 281.16679 285.49786 289.4514 286.68738 290.17249 312.5484 10
# appl 2816.61899 3106.19944 3259.3924 3266.45186 3401.80291 3804.7263 10
# fpaste 88.57108 89.67795 101.1524 90.59217 91.76415 197.1555 10
# dt2 301.95508 310.79082 384.8247 316.29807 383.94993 874.4472 10
I hacked together another way to do it without having to manipulate list view. Unfortunately, regular Android Animations seem to manipulate the contents of the row, but are ineffectual at actually shrinking the view. So, first consider this handler:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
Bundle bundle = message.getData();
View view = listView.getChildAt(bundle.getInt("viewPosition") -
listView.getFirstVisiblePosition());
int heightToSet;
if(!bundle.containsKey("viewHeight")) {
Rect rect = new Rect();
view.getDrawingRect(rect);
heightToSet = rect.height() - 1;
} else {
heightToSet = bundle.getInt("viewHeight");
}
setViewHeight(view, heightToSet);
if(heightToSet == 1)
return;
Message nextMessage = obtainMessage();
bundle.putInt("viewHeight", (heightToSet - 5 > 0) ? heightToSet - 5 : 1);
nextMessage.setData(bundle);
sendMessage(nextMessage);
}
Add this collection to your List adapter:
private Collection<Integer> disabledViews = new ArrayList<Integer>();
and add
public boolean isEnabled(int position) {
return !disabledViews.contains(position);
}
Next, wherever it is that you want to hide a row, add this:
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("viewPosition", listView.getPositionForView(view));
message.setData(bundle);
handler.sendMessage(message);
disabledViews.add(listView.getPositionForView(view));
That's it! You can change the speed of the animation by altering the number of pixels that it shrinks the height at once. Not real sophisticated, but it works!
In SQL Server 2005 and later use ROW_NUMBER()
:
SELECT * FROM
( SELECT p.*,
ROW_NUMBER() OVER(PARTITION BY Partid ORDER BY PriceDate DESC) AS rn
FROM MyPrice AS p ) AS t
WHERE rn=1
form.onsubmit = function(){
return textarea.value.match(/^\d+(\.\d+)?$/);
}
Is this what you're looking for?
I hope it helps.
EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
You are improperly declaring your main module, it requires a second dependencies array argument when creating a module, otherwise it is a reference to an existing module
Change:
var app = angular.module("MesaViewer");
To:
var app = angular.module("MesaViewer",[]);
request.POST is just a dictionary-like object, so just index into it with dict syntax.
Assuming your form field is fred, you could do something like this:
if 'fred' in request.POST:
mydata = request.POST['fred']
Alternately, use a form object to deal with the POST data.
Fot people who have tried EVERYTHING and just CANNOT get the error details to show, like me, it's a good idea to check the different levels of configuration. I have a config file on Website level and on Application level (inside the website) check both. Also, as it turned out, I had Detailed Errors disabled on the highest node in IIS (just underneath Start Page, it has the name that is the same as the webservers computername). Check the Error Pages there.
You can send a prop from the parent and use it in child component so you will base child's state changes on the sent prop changes and you can handle this by using getDerivedStateFromProps in the child component.
For anyone using entity framework core ending up here. This is how you do it.
# Powershell / Package manager console
Script-Migration
# Cli
dotnet ef migrations script
You can use the -From
and -To
parameter to generate an update script to update a database to a specific version.
Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts
There are several options to this command.
The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify
0
(this is the default).The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.
An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
I have finally found a working code - try this:
document.getElementById("button").style.background='#000000';
For Apache, you can use mod_ssl
to force SSL with the SSLRequireSSL Directive
:
This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.
This will not do a redirect to https though. To redirect, try the following with mod_rewrite
in your .htaccess file
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
or any of the various approaches given at
You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}
What about this simple code, works for me and on Windows 7
set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin
:end
Swift version:
If you are in a Navigation Controller:
let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.navigationController?.pushViewController(viewController, animated: true)
Or if you just want to present a new view:
let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.presentViewController(viewController, animated: true, completion: nil)
An almost git command-free approach was given in this answer:
To ignore certain files for every local repo:
~/.gitignore_global
, e.g. by touch ~/.gitignore_global
in your terminal. git config --global core.excludesfile ~/.gitignore_global
for once.~/.gitignore_global
. e.g. modules/*.H
, which will be assumed to be in your working directory, i.e. $WORK_DIR/modules/*.H
.To ignore certain files for a single local repo:
.git/info/exclude
within the repo, that is write the file/dir paths you want to ignore into .git/info/exclude
. e.g. modules/*.C
, which will be assumed to be in your working directory, i.e. $WORK_DIR/modules/*.C
.No, it's not possible.
It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".
Surprisingly, all other answers only say half the truth or are actually wrong!
e.stopImmediatePropagation()
stops any further handler from being called for this event, no exceptionse.stopPropagation()
is similar, but does still call all handlers for this phase on this element if not called alreadyWhat phase?
E.g. a click event will always first go all the way down the DOM (called “capture phase”), finally reach the origin of the event (“target phase”) and then bubble up again (“bubble phase”). And with addEventListener()
you can register multiple handlers for both capture and bubble phase independently. (Target phase calls handlers of both types on the target without distinguishing.)
And this is what the other answers are incorrect about:
A fiddle and mozilla.org event phase explanation with demo.
The map()
function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.
Let's look at an example:
map()
can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.
Imagine you have a function that takes a number, adds 1 to that number and returns it:
def add_one(num):
new_num = num + 1
return new_num
You also have a list of numbers:
my_list = [1, 3, 6, 7, 8, 10]
if you want to increment every number in the list, you can do the following:
>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]
Note: At minimum map()
needs two arguments. First a function name and second something like a list.
Let's see some other cool things map()
can do.
map()
can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.
We have three lists:
list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]
map()
can make you a new list that holds the addition of elements at a specific index.
Now remember map()
, needs a function. This time we'll use the builtin sum()
function. Running map()
gives the following result:
>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]
REMEMBER:
In Python 2 map()
, will iterate (go through the elements of the lists) according to the longest list, and pass None
to the function for the shorter lists, so your function should look for None
and handle them, otherwise you will get errors. In Python 3 map()
will stop after finishing with the shortest list. Also, in Python 3, map()
returns an iterator, not a list.
If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
And in the Java class, use these below lines of code:
class MyActivity extends Activity {
public void myClickHandler(View target) {
// Do stuff
}
}
select DATEDIFF(dd, '12/30/1899', mydatefield)
Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.
It may be better to use REAL type, to save storage space.
Quote from 1.2 section of Datatypes In SQLite Version 3
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t REAL DEFAULT (datetime('now', 'localtime'))
);
see column-constraint .
And insert a row without providing any value.
INSERT INTO "test" DEFAULT VALUES;
@joe : Many thanks, this was a good heads up!
I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file
So that's how I did it (using JQuery to handle the AJAX request):
Initial post request:
var parameters = {
pid : "mypid",
"files[]": ["file1.jpg","file2.jpg","file3.jpg"]
}
var options = {
url: "request/url",//replace with your request url
type: "POST",//replace with your request type
data: parameters,//see above
context: document.body,//replace with your contex
success: function(data){
if (data) {
if (data.path) {
//Create an hidden iframe, with the 'src' attribute set to the created ZIP file.
var dlif = $('<iframe/>
',{'src':data.path}).hide();
//Append the iFrame to the context
this.append(dlif);
} else if (data.error) {
alert(data.error);
} else {
alert('Something went wrong');
}
}
}
};
$.ajax(options);
The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:
//Code to create the zip file
//......
//Id of the file
$zipid = "myzipfile.zip"
//Download Link - it can be prettier
$dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
//JSON response to be handled on the client side
$result = '{"success":1,"path":"'.$dlink.'","error":null}';
header('Content-type: application/json;');
echo $result;
The "request/download" can perform some security checks, if needed, and generate the file transfer:
$fn = $_GET['file'];
if ($fn) {
//Perform security checks
//.....check user session/role/whatever
$result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
if (file_exists($result)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($result));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($result));
ob_clean();
flush();
readfile($result);
@unlink($result);
}
}
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid
Unfortunately it's not just about reading uncommitted data. In the background you may end up reading pages twice (in the case of a page split), or you may miss the pages altogether. So your results may be grossly skewed.
Check out Itzik Ben-Gan's article. Here's an excerpt:
" With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice. "
.circle {_x000D_
background-color:#fff;_x000D_
border:1px solid red; _x000D_
height:100px;_x000D_
border-radius:50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius:50%;_x000D_
width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
Maybe you're looking for something like this:
def tableize(df):
if not isinstance(df, pd.DataFrame):
return
df_columns = df.columns.tolist()
max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0])
align_center = lambda st, sz: "{0}{1}{0}".format(" "*(1+(sz-len(st))//2), st)[:sz] if len(st) < sz else st
align_right = lambda st, sz: "{0}{1} ".format(" "*(sz-len(st)-1), st) if len(st) < sz else st
max_col_len = max_len_in_lst(df_columns)
max_val_len_for_col = dict([(col, max_len_in_lst(df.iloc[:,idx].astype('str'))) for idx, col in enumerate(df_columns)])
col_sizes = dict([(col, 2 + max(max_val_len_for_col.get(col, 0), max_col_len)) for col in df_columns])
build_hline = lambda row: '+'.join(['-' * col_sizes[col] for col in row]).join(['+', '+'])
build_data = lambda row, align: "|".join([align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)]).join(['|', '|'])
hline = build_hline(df_columns)
out = [hline, build_data(df_columns, align_center), hline]
for _, row in df.iterrows():
out.append(build_data(row.tolist(), align_right))
out.append(hline)
return "\n".join(out)
df = pd.DataFrame([[1, 2, 3], [11111, 22, 333]], columns=['a', 'b', 'c'])
print tableize(df)
Output: +-------+----+-----+ | a | b | c | +-------+----+-----+ | 1 | 2 | 3 | | 11111 | 22 | 333 | +-------+----+-----+
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
I am using the springframework android artifact as an example
open build.gradle
Then add the following at the same level as apply plugin: 'android'
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.springframework.android', name: 'spring-android-rest-template', version: '1.0.1.RELEASE'
}
you can also use this notation for maven artifacts
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
Your IDE should show the jar and its dependencies under 'External Libraries' if it doesn't show up try to restart the IDE (this happened to me quite a bit)
here is the example that you provided that works
buildscript {
repositories {
maven {
url 'repo1.maven.org/maven2';
}
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile files('libs/android-support-v4.jar')
compile group:'com.squareup.picasso', name:'picasso', version:'1.0.1'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 17
}
}
I had the same problem too.Follow these steps if you are on Windows. Go to: 1.My Computer 2.System Properties 3.Advance System Settings 4. Under the "Advanced" tab click the button that says "Environment Variables" 5. Then under System Variables you have to add / change the following variables: PYTHONPATH and Path. Here is a paste of what my variables look like: python path:
C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
path:
C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
See this link for reference
Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.
Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.
There are different ways for this:
1.Building C# Applications Using csc.exe
While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.
2.Building .NET Applications Using Notepad++
Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports
3.Building .NET Applications Using SharpDevelop
As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.
Use StringBuilder
:
var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
...
}
return sb.ToString();