If the Data-set size is less the 25mb, The easiest way to upload a CSV file is from your GitHub repository.
Example:
import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()
In my case, forgot to define Primary Key to Table. So assign like shown in Picture and Refresh your table from "Update model from Database" from .edmx file. Hope it will help !!!
In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...
var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
if(sortAscending) {
qry = qry.OrderBy(x=>x.Property);
} else {
qry = qry.OrderByDescending(x=>x.Property);
}
Any use? You can create the entire "order" dynamically, but it is more involved...
Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.
Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR
When using functional components, you will often get the TypeError: Cannot add property myNewProp, object is not extensible
error when trying to set new properties on props.children
. There is a work around to this by cloning the props and then cloning the child itself with the new props.
const MyParentComponent = (props) => {
return (
<div className='whatever'>
{props.children.map((child) => {
const newProps = { ...child.props }
// set new props here on newProps
newProps.myNewProp = 'something'
const preparedChild = { ...child, props: newProps }
return preparedChild
})}
</div>
)
}
just set position: fixed
to the footer element (instead of relative)
Note that you may need to also set a margin-bottom
to the main
element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;
) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer
You need to render it as block level;
img {
display: block;
width: auto;
margin: auto;
}
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
Here is a neat and simple one. Can check git remote -v
, which shows you all the origin and upstream of current branch.
function showStuff(id, text, btn) {_x000D_
document.getElementById(id).style.display = 'block';_x000D_
// hide the lorem ipsum text_x000D_
document.getElementById(text).style.display = 'none';_x000D_
// hide the link_x000D_
btn.style.display = 'none';_x000D_
}
_x000D_
<td class="post">_x000D_
_x000D_
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>_x000D_
<span id="answer1" style="display: none;">_x000D_
<textarea rows="10" cols="115"></textarea>_x000D_
</span>_x000D_
_x000D_
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>_x000D_
</td>
_x000D_
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
Hope you realise, java.util.Enumeration
is different from the Java 1.5 Enum types.
You can simply use YourEnum.valueOf("String")
to get the equivalent enum type.
Thus if your enum is defined as so:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
You could do this:
String day = "SUNDAY";
Day dayEnum = Day.valueOf(day);
int strcmpInsensitive(char* a, char* b)
{
return strcmp(lowerCaseWord(a), lowerCaseWord(b));
}
char* lowerCaseWord(char* a)
{
char *b=new char[strlen(a)];
for (int i = 0; i < strlen(a); i++)
{
b[i] = tolower(a[i]);
}
return b;
}
good luck
Edit-lowerCaseWord function get a char* variable with, and return the lower case value of this char*. For example "AbCdE" for value of char*, will return "abcde".
Basically what it does is to take the two char* variables, after being transferred to lower case, and make use the strcmp function on them.
For example- if we call the strcmpInsensitive function for values of "AbCdE", and "ABCDE", it will first return both values in lower case ("abcde"), and then do strcmp function on them.
It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:
if (typeof varName == 'undefined')
do not tell you if varName
is a variable in scope, only that testing with typeof returned undefined. e.g.
var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true
In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in
:
var global = this;
...
'bar' in global; // false
But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.
The solution is to always declare variables in an appropriate context.
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
@tokland
tried your code and corrected it for 3.4 and windows dir.cmd is a simple dir command, saved as cmd-file
import subprocess
c = "dir.cmd"
def execute(command):
popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
lines_iterator = iter(popen.stdout.readline, b"")
while popen.poll() is None:
for line in lines_iterator:
nline = line.rstrip()
print(nline.decode("latin"), end = "\r\n",flush =True) # yield line
execute(c)
Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.
Try adding the following setting in your web.config's <appsettings>
block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001" />
</appSettings>
For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article
Its in the standard float.h include file. You want DBL_MAX
This works for me:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
To loop over the key/values, use a for in
loop:
for (let key in myDictionary) {
let value = myDictionary[key];
// Use `key` and `value`
}
//add this to your css
.myClass{
margin 0 auto;
}
// add the class to the span tag( could add it to the div and not using a span
// at all
<div class="row">
<div class="col-xs-1 center-block">
<span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
If you don't have permissions on the server to delete other people's workspaces, you can just change the name of the build definition. TFS will create a new workspace and map it to "C:\Build\ProductReleases\new build name here\Sources".
If you are working with maven project, then add following dependency to your pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
<?php if ($my_name == 'aboutme') { ?>
HTML_GOES_HERE
<?php } ?>
I was getting a similar problem in Eclipse STS when trying to run a Maven install on a project. I had changed some versions in the dependencies of my pom.xml file for that project and the projects that those dependencies pointed to. I solved it by running a Maven install on all the projects I changed and then running install on the original one again.
I timed all the methods in the current answers along with one extra.
With an input string of abc&def#ghi
and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#')
.
Timings for each function:
Here are the functions:
def a(text):
chars = "&#"
for c in chars:
text = text.replace(c, "\\" + c)
def b(text):
for ch in ['&','#']:
if ch in text:
text = text.replace(ch,"\\"+ch)
import re
def c(text):
rx = re.compile('([&#])')
text = rx.sub(r'\\\1', text)
RX = re.compile('([&#])')
def d(text):
text = RX.sub(r'\\\1', text)
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
esc(text)
def f(text):
text = text.replace('&', '\&').replace('#', '\#')
def g(text):
replacements = {"&": "\&", "#": "\#"}
text = "".join([replacements.get(c, c) for c in text])
def h(text):
text = text.replace('&', r'\&')
text = text.replace('#', r'\#')
def i(text):
text = text.replace('&', r'\&').replace('#', r'\#')
Timed like this:
python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"
Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):
def a(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
text = text.replace(c, "\\" + c)
def b(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
if ch in text:
text = text.replace(ch,"\\"+ch)
import re
def c(text):
rx = re.compile('([&#])')
text = rx.sub(r'\\\1', text)
RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
text = RX.sub(r'\\\1', text)
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
esc(text)
def f(text):
text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')
def g(text):
replacements = {
"\\": "\\\\",
"`": "\`",
"*": "\*",
"_": "\_",
"{": "\{",
"}": "\}",
"[": "\[",
"]": "\]",
"(": "\(",
")": "\)",
">": "\>",
"#": "\#",
"+": "\+",
"-": "\-",
".": "\.",
"!": "\!",
"$": "\$",
}
text = "".join([replacements.get(c, c) for c in text])
def h(text):
text = text.replace('\\', r'\\')
text = text.replace('`', r'\`')
text = text.replace('*', r'\*')
text = text.replace('_', r'\_')
text = text.replace('{', r'\{')
text = text.replace('}', r'\}')
text = text.replace('[', r'\[')
text = text.replace(']', r'\]')
text = text.replace('(', r'\(')
text = text.replace(')', r'\)')
text = text.replace('>', r'\>')
text = text.replace('#', r'\#')
text = text.replace('+', r'\+')
text = text.replace('-', r'\-')
text = text.replace('.', r'\.')
text = text.replace('!', r'\!')
text = text.replace('$', r'\$')
def i(text):
text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')
Here's the results for the same input string abc&def#ghi
:
And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$
):
Adding a couple of variants:
def ab(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
text = text.replace(ch,"\\"+ch)
def ba(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
if c in text:
text = text.replace(c, "\\" + c)
With the shorter input:
With the longer input:
So I'm going to use ba
for readability and speed.
Prompted by haccks in the comments, one difference between ab
and ba
is the if c in text:
check. Let's test them against two more variants:
def ab_with_check(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
if ch in text:
text = text.replace(ch,"\\"+ch)
def ba_without_check(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
text = text.replace(c, "\\" + c)
Times in µs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.
?-------------------------------------------------------------?
¦ Py, input ¦ ab ¦ ab_with_check ¦ ba ¦ ba_without_check ¦
¦------------+------+---------------+------+------------------¦
¦ Py2, short ¦ 8.81 ¦ 4.22 ¦ 3.45 ¦ 8.01 ¦
¦ Py3, short ¦ 5.54 ¦ 1.34 ¦ 1.46 ¦ 5.34 ¦
+------------+------+---------------+------+------------------¦
¦ Py2, long ¦ 9.3 ¦ 7.15 ¦ 6.85 ¦ 8.55 ¦
¦ Py3, long ¦ 7.43 ¦ 4.38 ¦ 4.41 ¦ 7.02 ¦
+-------------------------------------------------------------+
We can conclude that:
Those with the check are up to 4x faster than those without the check
ab_with_check
is slightly in the lead on Python 3, but ba
(with check) has a greater lead on Python 2
However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!
I'm sad to say: We are sh*t out of luck on this one.
I'd like to refer you to the author of WhichBrowser: Everybody lies.
Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:
or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.
Take your code, for example:
<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
Chrome says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
IE says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET
or Media Center
:P), and then match it against the rv:
at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.
l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)
Result
['abc', 'ba', 'cd', 'dc', 'xy']
XAMPP is an integrated package and you can not downgrade or change one of its component such as php. (There are some solutions that you can use but there is little chances that everything work fine.)
You can download the package from these links:
You had better to download the old package form sourceforge.net.
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
For an earlier version of junit, you can do
Class<Map<String, String>> mapClass = (Class) Map.class;
ArgumentCaptor<Map<String, String>> mapCaptor = ArgumentCaptor.forClass(mapClass);
If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile(req.params.filepath, function (err, content) {
if(!err) {
res.end(content);
} else {
res.end('404');
}
}
}).listen(3000);
But I suggest you to look into some frameworks like Express for more useful solutions.
XYZ couldn't be found because is not built yet....
Right click on the solution and check Project Dependencies, the Project Build Order should also change according to the dependencies that have been set.
With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.
You can download a full working demo from this post
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span
or div
, for example.
Short answer: Start with SQL and add NoSQL only when/if needed. (unless you don't need anything beyond very simple queries)
My personal experience: I haven't used MongoDB for queries but as of April 2015 DynamoDB is still very crippled when it comes to anything beyond the most basic key/value queries. I love it for the basic stuff but if you want query language then look to a real SQL database solution.
In DynamoDB you can query on a hash or on a hash and range key, and you can have multiple secondary global indexes. I'm doing queries on a single table with 4 possible filter parameters and sorting the results, this is supported (barely) through the use of the global secondary indexes with filter expressions. The problem comes in when you try to get the total results matching the filter, you can't just search for the first 10 items matching the filter, but rather it checks 10 items and you may get 0 valid results forcing you to keep re-scanning from the continue key - pain in the neck and consumes too much of your table read quota for a simple scenario.
To be specific about the limit problem with filters in the query, this is from the docs (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#ScanQueryLimit):
In a response, DynamoDB returns all the matching results within the scope of the Limit value. For example, if you issue a Query or a Scan request with a Limit value of 6 and without a filter expression, the operation returns the first six items in the table that match the request parameters. If you also supply a FilterExpression, the operation returns the items within the first six items in the table that match the filter requirements.
My conclusion is that queries involving FilterExpressions are only usable on very rare occasions and are not scalable because each query can easily read most or all of your of your table which consumes far too many DynamoDB read units. Once you use too many read units you'll get throttled and see poor performance.
Expert opinion: In the AWS summit on Apr 9, 2015 Brett Hollman, Manager, Solutions Architecture, AWS in his talk on scalling to your first 10 million users advocates starting with a SQL database and then using NoSQL only when and if it makes sense. Because sooner or later you'll probably need a SQL server somewhere in your stack. His slides are here: http://www.slideshare.net/AmazonWebServices/deep-dive-scaling-up-to-your-first-10-million-users See slide 28.
I think that all previous answers are correct, this below code is very valid specially if you have to update multiple rows at once, note: it's PL/SQL
DECLARE
CURSOR myCursor IS
Select contacts.BusinessCountry
From contacts c WHERE c.Key = t.Key;
---------------------------------------------------------------------
BEGIN
FOR resultValue IN myCursor LOOP
Update tblindiantime t
Set CountryName=resultValue.BusinessCountry
where t.key=resultValue.key;
END LOOP;
END;
I wish this could help.
this shows all the options: "%"
(see below)
The important thing is that you have to place it underneath the previous #example declaration, like in the example below. This took me a while to figure out.
$( "#example" ).autocomplete({
source: "countries.php",
minLength: 1,
selectFirst: true
});
$("#example").autocomplete( "search", "%" );
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);
TextView tekst = (TextView) findViewById(R.id.editText1);
You cannot cast EditText
to TextView
.
If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.
import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)
1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).
Remember that 2D array clone doesn't work due to shallow copy implementation of clone()
.
public static void main(String[] args) {
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
}
For Swift 5+
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let submodules = (
home: HomeRouter.createModule(),
search: SearchRouter.createModule(),
exoplanets: ExoplanetsRouter.createModule()
)
let tabBarController = TabBarModuleBuilder.build(usingSubmodules: submodules)
window.rootViewController = tabBarController
self.window = window
window.makeKeyAndVisible()
}
}
This is a common code adapted from another examples:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
# ... take the code from the options below
# Load a page
driver.get('http://bings.com')
# Make the tests...
# close the tab
driver.quit()
the possible ways were:
Sending <CTRL> + <T>
to one element
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
Sending <CTRL> + <T>
via Action chains
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Execute a javascript snippet
driver.execute_script('''window.open("http://bings.com","_blank");''')
In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 3)
fp.set_preference("browser.link.open_newwindow.restriction", 2)
driver = webdriver.Firefox(browser_profile=fp)
the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.
In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:
FirefoxOptions options = new FirefoxOptions().setProfile(fp);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 2);
FirefoxDriver driver = new FirefoxDriver(options);
The third option did stop working for python in selenium 3.4.0.
The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)
driver = webdriver.Firefox(browser_profile=fp)
... and then you can use successfully the first way.
console.log
is what I most often use when debugging.
I was able to find this jQuery extension
though.
These answers seem strangely convoluted. Unless I'm missing something...if you want to convert numbers to letters, you can just stock them all in an array using a for loop then call on the number associated with that column letter. Like so
For intloop = 1 To 26
colcheck(intloop) = Chr$(64 + intloop)
For lenloop = 1 To 26
colcheck((intloop * 26) + lenloop) = Chr$(64 + intloop) & Chr$(64 + lenloop)
For terloop = 1 To 26
colcheck((intloop * 676) + (lenloop * 26) + terloop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop)
For qualoop = 1 To 26
colcheck((intloop * 17576) + (lenloop * 676) + (terloop * 26) + qualoop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop) & Chr$(64 + qualoop)
Next qualoop
Next terloop
Next lenloop
Next intloop
Then just use colcheck(yourcolumnnumberhere) and you will get the column heading associated with that letter (i.e. colcheck(703) = AAA
table tr td:nth-child(2) {
background: #ccc;
}
Working example: http://jsfiddle.net/gqr3J/
You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).
Example 1:
Object a = new Object();
a = null; // after this, if there is no reference to the object,
// it will be deleted by the garbage collector
Example 2:
if (something) {
Object o = new Object();
} // as you leave the block, the reference is deleted.
// Later on, the garbage collector will delete the object itself.
Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()
Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:
hadoop dfsadmin -safemode leave
If you are using cloudera manager:
go to >>Actions>>Leave Safemode
But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.
free -m
If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)
you can also use DataFrame.head(x)
/ .tail(x)
to display the first / last x rows of the DataFrame.
You can use mongod
command instead of mongodb
, if you find any issue regarding dbpath in mongo you can use my answer in the link below.
Used this to start Xming, placed the bat file in the Start->Startup directory and now I have xming running on start up.
start "" "C:\Program Files (x86)\Xming\Xming.exe" -screen 0 -clipboard -multiwindow
In my case (Python 3.4, in a virtual environment, running under macOS 10.10.6) I could not even upgrade pip
itself. Help came from this SO answer in the form of the following one-liner:
curl https://bootstrap.pypa.io/get-pip.py | python
(If you do not use a virtual environment, you may need sudo python
.)
With this I managed to upgrade pip
from Version 1.5.6 to Version 10.0.0 (quite a jump!). This version does not use TLS 1.0 or 1.1 which are not supported any more by the Python.org site(s), and can install PyPI packages nicely. No need to specify --index-url=https://pypi.python.org/simple/
.
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
If you or another dev will not work on branchB further, I think it's better to keep commits in order to make reverts without headaches. So ;
git checkout branchA
git pull --rebase branchB
It's important that branchB shouldn't be used anymore.
For more ; https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the CultureInfo object returned by the InvariantCulture property.
The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.
The best easiest way I found to reset settings:
Open Settings page (Ctrl+Shift+P):
Go onto your desire setting section to reset, click on icon and then Reset Setting :
I had the same problem. It was because I had accidentally used a relative path with the symbolic link.
Are you sure you used full paths, e.g.:
ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf
Working with floats is bit messy:
This as many other 'trivial' layout tricks can be done with flexbox.
div.container {
display: flex;
justify-content: space-between;
}
In 2017 I think this is preferred solution (over float) if you don't have to support legacy browsers: https://caniuse.com/#feat=flexbox
Check fiddle how different float usages compares to flexbox ("may include some competing answers"): https://jsfiddle.net/b244s19k/25/. If you still need to stick with float I recommended third version of course.
I had the same problem.
Solution:
There's a static method in ToolStripRenderer
class, named CreateDisabledImage
.
Its usage is as simple as:
Bitmap c = new Bitmap("filename");
Image d = ToolStripRenderer.CreateDisabledImage(c);
It uses a little bit different matrix than the one in the accepted answer and additionally multiplies it by a transparency of value 0.7, so the effect is slightly different than just grayscale, but if you want to just get your image grayed, it's the simplest and best solution.
Download: https://remarkableapp.github.io/
Safer is to use lift
so you can extract the value if it exists and fail gracefully if it does not.
data.lift(2)
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None
Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.
Explanation:
This works because List's apply
(which sugars to just parentheses, e.g. l(index)
) is like a partial function that is defined wherever the list has an element. The List.lift
method turns the partial apply
function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.
Non-jQuery solution / pure JavaScript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
Since you are disabling it in the first place, the way to enable it is to set its disabled
property as false
.
To change its disabled
property in Javascript, you use this:
var btn = document.getElementById("Button");
btn.disabled = false;
And obviously to disable it again, you'd use true
instead.
Since you also tagged the question with jQuery, you could use the .prop
method. Something like:
var btn = $("#Button");
btn.prop("disabled", true); // Or `false`
This is in the newer versions of jQuery. The older way to do this is to add or remove an attribute like so:
var btn = $("#Button");
btn.attr("disabled", "disabled");
// or
btn.removeAttr("disabled");
The mere presence of the disabled
property disables the element, so you cannot set its value as "false". Even the following should disable the element
<input type="button" value="Submit" disabled="" />
You need to either remove the attribute completely or set its property.
You can set it at Property > Configuration Properties > Debugging > Environment
You should use method listName.isEmpty()
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require()
, do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
We can't get complete file path in FF3. The below might be useful for File component customization.
<script>
function setFileName()
{
var file1=document.forms[0].firstAttachmentFileName.value;
initFileUploads('firstFile1','fileinputs1',file1);
}
function initFileUploads(fileName,fileinputs,fileValue) {
var fakeFileUpload = document.createElement('div');
fakeFileUpload.className = 'fakefile';
var filename = document.createElement('input');
filename.type='text';
filename.value=fileValue;
filename.id=fileName;
filename.title='Title';
fakeFileUpload.appendChild(filename);
var image = document.createElement('input');
image.type='button';
image.value='Browse File';
image.size=5100;
image.style.border=0;
fakeFileUpload.appendChild(image);
var x = document.getElementsByTagName('input');
for (var i=0; i<x.length;i++) {
if (x[i].type != 'file') continue;
if (x[i].parentNode.className != fileinputs) continue;
x[i].className = 'file hidden';
var clone = fakeFileUpload.cloneNode(true);
x[i].parentNode.appendChild(clone);
x[i].relatedElement = clone.getElementsByTagName('input')[0];
x[i].onchange= function () {
this.relatedElement.value = this.value;
}}
if(document.forms[0].firstFile != null && document.getElementById('firstFile1') != null)
{
document.getElementById('firstFile1').value= document.forms[0].firstFile.value;
document.forms[0].firstAttachmentFileName.title=document.forms[0].firstFile.value;
}
}
function submitFile()
{
alert( document.forms[0].firstAttachmentFileName.value);
}
</script>
<style>div.fileinputs1 {position: relative;}div.fileinputs2 {position: relative;}
div.fakefile {position: absolute;top: 0px;left: 0px;z-index: 1;}
input.file {position: relative;text-align: right;-moz-opacity:0 ;filter:alpha(opacity: 0);
opacity: 0;z-index: 2;}</style>
<html>
<body onLoad ="setFileName();">
<form>
<div class="fileinputs1">
<INPUT TYPE=file NAME="firstAttachmentFileName" styleClass="file" />
</div>
<INPUT type="button" value="submit" onclick="submitFile();" />
</form>
</body>
</html>
With spring-boot 2.x you can configure in application.properties:
spring.mvc.servlet.path=/api
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
if it is standalone program, download mysql connector jar and add it to your classpath.
if it is a maven project, add below dependency and run your program.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
I think what you are looking for, if you are looking for something in a dictionary, is the setdefault
method:
(Pdb) we=dict()
(Pdb) we.setdefault('e',14)
14
(Pdb) we['e']
14
(Pdb) we['r']="p"
(Pdb) we.setdefault('r','jeff')
'p'
(Pdb) we['r']
'p'
(Pdb) we[e]
*** NameError: name 'e' is not defined
(Pdb) we['e']
14
(Pdb) we['q2']
*** KeyError: 'q2' (Pdb)
The important thing to note in my example is that the setdefault
method changes the dictionary if and only if the key that the setdefault
method refers to is not present.
You can use Math:
int x = Math.abs(-5);
Here is a method To print over images: taken from here. Use a different layer for your text you're putting over the images, and also make sure to use the GetOverContent() method.
string oldFile = "FileWithImages.pdf";
string watermarkedFile = "Layers.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(oldFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("Layer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetOverContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.RED);
cb.SetFontAndSize(bf, 100);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some random blablablabla...", rect.Width / 2, rect.Height / 2, - 90);
cb.EndText();
// Close the layer
cb.EndLayer();
}
}
Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:
exestub.sh:
#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
case $1 in
-Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
-D*) JAVA_OPT="$JAVA_OPT $1" ;;
*) PROG_OPT="$PROG_OPT $1" ;;
esac
shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT
Then you create your runnable file from your jar:
$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable
It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>
, as <myexe>
is a valid zip/jar file.
if used ubuntu operating system then check chmod of /Practice folder change read write permission
Open terminal press shortcut key
Ctrl+Alt+T
Goto
$ cd /opt/lampp/htdocs/
and change folder read write and execute permission by using chmod
command
e.g folder name is practice and path of folder /opt/lampp/htdocs/practice
Type command
$ sudo chmod 777 -R Practice
what is chmod
and 777
? visit this link
http://linuxcommand.org/lts0070.php
Here's a solution (and it has some quirks, but let me know if you notice them and that they're a concern):
<div>
<div style="width:200px;float:left;display:inline-block;">
Hello world
</div>
<div style="margin-left:200px;">
Hello world
</div>
</div>
None of the answer provided solved my issue. I am using an animation between views and the scrolling would always happen after the animation. The solution I found so that the scrolling to the top happen before the animation is the following directive:
yourModule.directive('scrollToTopBeforeAnimation', ['$animate', function ($animate) {
return {
restrict: 'A',
link: function ($scope, element) {
$animate.on('enter', element, function (element, phase) {
if (phase === 'start') {
window.scrollTo(0, 0);
}
})
}
};
}]);
I inserted it on my view as follows:
<div scroll-to-top-before-animation>
<div ng-view class="view-animation"></div>
</div>
I had this issue when I added react-router-dom
to the new CRA app using typescript. After I added @types/react-router
, the issue was fixed.
"I understand both are server cluster management software."
This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).
Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).
Try an OUTER APPLY
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC
Alternatively, you could GROUP BY
the results
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC
The OUTER APPLY
selects a single row (or none) that matches each row from the left table.
The GROUP BY
performs the entire join, but then collapses the final result rows on the provided columns.
If you don't want to create a new primary key you can use the TOP command in SQL Server:
declare @ID int
while EXISTS(select count(*) from Employee group by EmpId having count(*)> 1)
begin
select top 1 @ID = EmpId
from Employee
group by EmpId
having count(*) > 1
DELETE TOP(1) FROM Employee WHERE EmpId = @ID
end
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
Have a read of pedjaradenkovic's comment.
Further to the link he provides, the reason this isn't working is that @Value
processing requires a PropertySourcesPlaceholderConfigurer
instead of a PropertyPlaceholderConfigurer
.
I resolved my problem doing this:
json_encode($array, JSON_UNESCAPED_UNICODE)
to encode the data;The result is a .json file encoded to ANSI as UTF-8.
It seams that missing dependency of python-dev, install python-dev and then try to install seaborn, if you are using Ubuntu:
sudo apt-get install python-dev -y
pip install seaborn
One thing that (surprisingly) hasn't been mentioned is that a request can explicitly indicate that it will accept stale data, using the max-stale
directive. In that case, if the server responded with max-age=0
, the cache would merely consider the response stale, and would be free to use it to satisfy the client's request [which asked for potentially-stale data]. By contrast, if the server sends no-cache
that really does trump any request by the client (with max-stale
) for stale data, as the cache MUST revalidate.
Given a POM file for a maven project you can remove all its dependencies in the local repository (by default ~/.m2/respository) using the Apache Maven Dependency Plugin.
It includes the dependency:purge-local-repository
functionality that removes the project dependencies from the local repository, and optionally re-resolve them.
To clean the local dependencies you just have to used the optional parameter reResolve and set it to false since it is set to true by default.
This command line call should work:
mvn dependency:purge-local-repository -DreResolve=false
Define a constructor in the abstract class which sets the field so that the concrete implementations are per the specification required to call/override the constructor.
E.g.
public abstract class AbstractTable {
protected String name;
public AbstractTable(String name) {
this.name = name;
}
}
When you extend AbstractTable
, the class won't compile until you add a constructor which calls super("somename")
.
public class ConcreteTable extends AbstractTable {
private static final String NAME = "concreteTable";
public ConcreteTable() {
super(NAME);
}
}
This way the implementors are required to set name
. This way you can also do (null)checks in the constructor of the abstract class to make it more robust. E.g:
public AbstractTable(String name) {
if (name == null) throw new NullPointerException("Name may not be null");
this.name = name;
}
I solved this problem in accordance with the figure:
run in cmd
npm install -g @angular/cli
and then
( open in Windows 10) Control Panel\All Control Panel Items\System or accordance with the figure
step 1:
step 2 :
step3:
step4:
step5: add missing ng path
Finally, restart all opened command prompts, or you can also restart the computer.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
Roll back the most recent migration:
rake db:rollback
Roll back the n
most recent migrations:
rake db:rollback STEP=n
You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.
Here's some more:
rake db:migrate
- Run all migrations that haven't been run alreadyrake db:migrate VERSION=20080906120000
- Run all necessary migrations (up or down) to get to the given versionrake db:migrate RAILS_ENV=test
- Run migrations in the given environmentrake db:migrate:redo
- Roll back one migration and run it againrake db:migrate:redo STEP=n
- Roll back the last n
migrations and run them againrake db:migrate:up VERSION=20080906120000
- Run the up
method for the given migrationrake db:migrate:down VERSION=20080906120000
- Run the down
method for the given migrationAnd to answer your question about where you get a migration's version number from:
The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run
$ rake db:migrate VERSION=20080906120000
(From Running Migrations in the Rails Guides)
Statement
interface executes static SQL statements without parameters
PreparedStatement
interface (extending Statement) executes a precompiled SQL statement with/without parameters
Efficient for repeated executions
It is precompiled so it's faster
Specifying inheritance in the FileSystemAccessRule()
constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl"
and "Allow"
).
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
According to this topic
"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."
I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
First of all, try to estimate peak performance - examine https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf, in particular, Appendix C.
In your case, it's table C-10 that shows POPCNT instruction has latency = 3 clocks and throughput = 1 clock. Throughput shows your maximal rate in clocks (multiply by core frequency and 8 bytes in case of popcnt64 to get your best possible bandwidth number).
Now examine what compiler did and sum up throughputs of all other instructions in the loop. This will give best possible estimate for generated code.
At last, look at data dependencies between instructions in the loop as they will force latency-large delay instead of throughput - so split instructions of single iteration on data flow chains and calculate latency across them then naively pick up maximal from them. it will give rough estimate taking into account data flow dependencies.
However, in your case, just writing code the right way would eliminate all these complexities. Instead of accumulating to the same count variable, just accumulate to different ones (like count0, count1, ... count8) and sum them up at the end. Or even create an array of counts[8] and accumulate to its elements - perhaps, it will be vectorized even and you will get much better throughput.
P.S. and never run benchmark for a second, first warm up the core then run loop for at least 10 seconds or better 100 seconds. otherwise, you will test power management firmware and DVFS implementation in hardware :)
P.P.S. I heard endless debates on how much time should benchmark really run. Most smartest folks are even asking why 10 seconds not 11 or 12. I should admit this is funny in theory. In practice, you just go and run benchmark hundred times in a row and record deviations. That IS funny. Most people do change source and run bench after that exactly ONCE to capture new performance record. Do the right things right.
Not convinced still? Just use above C-version of benchmark by assp1r1n3 (https://stackoverflow.com/a/37026212/9706746) and try 100 instead of 10000 in retry loop.
My 7960X shows, with RETRY=100:
Count: 203182300 Elapsed: 0.008385 seconds Speed: 12.505379 GB/s
Count: 203182300 Elapsed: 0.011063 seconds Speed: 9.478225 GB/s
Count: 203182300 Elapsed: 0.011188 seconds Speed: 9.372327 GB/s
Count: 203182300 Elapsed: 0.010393 seconds Speed: 10.089252 GB/s
Count: 203182300 Elapsed: 0.009076 seconds Speed: 11.553283 GB/s
with RETRY=10000:
Count: 20318230000 Elapsed: 0.661791 seconds Speed: 15.844519 GB/s
Count: 20318230000 Elapsed: 0.665422 seconds Speed: 15.758060 GB/s
Count: 20318230000 Elapsed: 0.660983 seconds Speed: 15.863888 GB/s
Count: 20318230000 Elapsed: 0.665337 seconds Speed: 15.760073 GB/s
Count: 20318230000 Elapsed: 0.662138 seconds Speed: 15.836215 GB/s
P.P.P.S. Finally, on "accepted answer" and other mistery ;-)
Let's use assp1r1n3's answer - he has 2.5Ghz core. POPCNT has 1 clock throuhgput, his code is using 64-bit popcnt. So math is 2.5Ghz * 1 clock * 8 bytes = 20 GB/s for his setup. He is seeing 25Gb/s, perhaps due to turbo boost to around 3Ghz.
Thus go to ark.intel.com and look for i7-4870HQ: https://ark.intel.com/products/83504/Intel-Core-i7-4870HQ-Processor-6M-Cache-up-to-3-70-GHz-?q=i7-4870HQ
That core could run up to 3.7Ghz and real maximal rate is 29.6 GB/s for his hardware. So where is another 4GB/s? Perhaps, it's spent on loop logic and other surrounding code within each iteration.
Now where is this false dependency? hardware runs at almost peak rate. Maybe my math is bad, it happens sometimes :)
P.P.P.P.P.S. Still people suggesting HW errata is culprit, so I follow suggestion and created inline asm example, see below.
On my 7960X, first version (with single output to cnt0) runs at 11MB/s, second version (with output to cnt0, cnt1, cnt2 and cnt3) runs at 33MB/s. And one could say - voila! it's output dependency.
OK, maybe, the point I made is that it does not make sense to write code like this and it's not output dependency problem but dumb code generation. We are not testing hardware, we are writing code to unleash maximal performance. You could expect that HW OOO should rename and hide those "output-dependencies" but, gash, just do the right things right and you will never face any mystery.
uint64_t builtin_popcnt1a(const uint64_t* buf, size_t len)
{
uint64_t cnt0, cnt1, cnt2, cnt3;
cnt0 = cnt1 = cnt2 = cnt3 = 0;
uint64_t val = buf[0];
#if 0
__asm__ __volatile__ (
"1:\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"subq $4, %0\n\t"
"jnz 1b\n\t"
: "+q" (len), "=q" (cnt0)
: "q" (val)
:
);
#else
__asm__ __volatile__ (
"1:\n\t"
"popcnt %5, %1\n\t"
"popcnt %5, %2\n\t"
"popcnt %5, %3\n\t"
"popcnt %5, %4\n\t"
"subq $4, %0\n\t"
"jnz 1b\n\t"
: "+q" (len), "=q" (cnt0), "=q" (cnt1), "=q" (cnt2), "=q" (cnt3)
: "q" (val)
:
);
#endif
return cnt0;
}
I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)
Try this
<client>
<endpoint>
<identity>
<servicePrincipalName value="" />
</identity>
</endpoint>
</client>
I've encountered this error before when working in a webfarm and this fixed it for me.
My solution works with MySQL date time formats and provides a callback function. on complition. Disclaimer: works only with minutes and seconds, as this is what I needed.
jQuery.fn.countDownTimer = function(futureDate, callback){
if(!futureDate){
throw 'Invalid date!';
}
var currentTs = +new Date();
var futureDateTs = +new Date(futureDate);
if(futureDateTs <= currentTs){
throw 'Invalid date!';
}
var diff = Math.round((futureDateTs - currentTs) / 1000);
var that = this;
(function countdownLoop(){
// Get hours/minutes from timestamp
var m = Math.floor(diff % 3600 / 60);
var s = Math.floor(diff % 3600 % 60);
var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);
$(that).text(text);
if(diff <= 0){
typeof callback === 'function' ? callback.call(that) : void(0);
return;
}
diff--;
setTimeout(countdownLoop, 1000);
})();
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}
// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})
I used su and it started working. When I use Jetbrains with regular user, I see this problem but after restarting Jetbrains in su mode, I can see my device without doing anything.
I am using Ubuntu 13.04 and Jetbrains 12.1.4
You could get the array of elements by name the old fashioned way and pass that array to jQuery.
function toggleByName() {_x000D_
var arrChkBox = document.getElementsByName("chName");_x000D_
$(arrChkBox).toggle();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
<title>sandBox</title>_x000D_
</head>_x000D_
<body>_x000D_
<input type="radio" name="chName"/><br />_x000D_
<input type="radio" name="chName"/><br />_x000D_
<input type="radio" name="chName"/><br />_x000D_
<input type="radio" name="chName"/><br />_x000D_
<input type="button" onclick="toggleByName();" value="toggle"/>_x000D_
</body>_x000D_
</html>
_x000D_
note: the only time you would have a reason to use the "name" attribute should be for checkbox or radio inputs.
Or you could just add another class to the elements for selection.(This is what I would do)
function toggleByClass(bolShow) {_x000D_
if (bolShow) {_x000D_
$(".rowToToggle").show();_x000D_
} else {_x000D_
$(".rowToToggle").hide();_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
<title>sandBox</title>_x000D_
</head>_x000D_
<body>_x000D_
<table>_x000D_
<tr>_x000D_
<td>data1</td>_x000D_
<td class="bold rowToToggle">data2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data1</td>_x000D_
<td class="bold rowToToggle">data2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data1</td>_x000D_
<td class="bold rowToToggle">data2</td>_x000D_
</tr>_x000D_
</table>_x000D_
<input type="button" onclick="toggleByClass(true);" value="show"/>_x000D_
<input type="button" onclick="toggleByClass(false);" value="hide"/>_x000D_
</body>_x000D_
</html>
_x000D_
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
For me, simply adding the current directory worked.
Using the following structure:
+-- myproject
+-- a.py
+-- b.py
a.py:
from b import some_object
# returns ModuleNotFound error
from myproject.b import some_object
# works
node -v
v9.10.1
If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value
So I would suggest use JSON.stringify
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname, query = parsedUrl.query;
const method = req.method;
res.end("hello world\n");
console.log(`Request received on: ${path} + method: ${method} + query:
${JSON.stringify(query)}`);
console.log('query: ', query);
});
server.listen(3000, () => console.log("Server running at port 3000"));
So doing curl http://localhost:3000/foo\?fizz\=buzz
will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
Try this awesome ink-html library
import print from 'ink-html'
// const print = require('ink-html').default
// js
print(window.querySelector('#printable'))
// Vue.js
print(this.$refs.printable.$el)
What's this "other information"? An IP address?
In PHP, you use $_SERVER['REMOTE_ADDR']
to get the IP address of the remote client, then you can use gethostbyaddr()
to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.
Wherever you want vertically center style means you can try display:table-cell
and vertical-align:middle
.
Example:
#box_x000D_
{_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
height: 90px;_x000D_
width: 270px;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
font-style: oblique;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
margin-top: 20px;_x000D_
margin-left: 5px;_x000D_
}
_x000D_
<div Id="box">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</div>
_x000D_
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors
The best way I found which gives custom themes and no action bar, is to create a SuperClass for all activities in my project and in it's onCreate() call the following line of code -
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
It always work for me. The only issue in this approach is, you'll see action bar for a fraction of second when starting the app (Not the activity, the complete app).
Just use the killall command:
killall taskname
for more info and more advanced options, type "man killall".
I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:
Stream.of(objects)
.filter(c -> c instanceof Client)
.map(c -> (Client) c)
.map(Client::getID)
.forEach(System.out::println);
or, as suggested in the comments, you could use the cast
method - the former may be easier to read though:
Stream.of(objects)
.filter(Client.class::isInstance)
.map(Client.class::cast)
.map(Client::getID)
.forEach(System.out::println);
You forgot to define the default value for left
so it doesn't know how to animate.
.test {
left: 0;
transition:left 1s linear;
}
See here: http://jsfiddle.net/shomz/yFy5n/5/
If you want to increase the height of the input field, you can specify line-height
css property for the input field.
input {
line-height: 2em; // 2em is (2 * default line height)
}
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
Try using String.Split Method:
string text = @"First line
second line
third line";
foreach (string line in text.Split('\n'))
{
// do something
}
Just saying...here is a more simple approach to this:
declare @sdate date = '2017-06-25'
, @edate date = '2017-07-24';
with dates_CTE (date) as (
select @sdate
Union ALL
select DATEADD(day, 1, date)
from dates_CTE
where date < @edate
)
select *
from dates_CTE;
One of the fundamental principles behind the original C language is that memory is composed of a sequence of bytes, and code need only care about what those bytes mean at the exact moment that they are being used. Modern C allows compilers to impose additional restrictions, but C includes--and C++ retains--the ability to decompose a pointer into a sequence of bytes, assemble any sequence of bytes containing the same values into a pointer, and then use that pointer to access the earlier object.
While that ability can be useful--or even indispensable--in some kinds of applications, a language that includes that ability will be very limited in its ability to support any kind of useful and reliable garbage collection. If a compiler doesn't know everything that has been done with the bits that made up a pointer, it will have no way of knowing whether information sufficient to reconstruct the pointer might exist somewhere in the universe. Since it would be possible for that information to be stored in ways that the computer wouldn't be able to access even if it knew about them (e.g. the bytes making up the pointer might have been shown on the screen long enough for someone to write them down on a piece of paper), it may be literally impossible for a computer to know whether a pointer could possibly be used in the future.
An interesting quirk of many garbage-collected frameworks is that an object reference not defined by the bit patterns contained therein, but by the relationship between the bits held in the object reference and other information held elsewhere. In C and C++, if the bit pattern stored in a pointer identifies an object, that bit pattern will identify that object until the object is explicitly destroyed. In a typical GC system, an object may be represented by a bit pattern 0x1234ABCD at one moment in time, but the next GC cycle might replace all references to 0x1234ABCD with references to 0x4321BABE, whereupon the object would be represented by the latter pattern. Even if one were to display the bit pattern associated with an object reference and then later read it back from the keyboard, there would be no expectation that the same bit pattern would be usable to identify the same object (or any object).
The varStatus
references to LoopTagStatus
which has a getIndex()
method.
So:
<c:forEach var="tableEntity" items='${requestScope.tables}' varStatus="outer">
<c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="inner">
<c:out value="${(outer.index * fn:length(tableEntity.rows)) + inner.index}" />
</c:forEach>
</c:forEach>
import inspect
def whoami():
return inspect.stack()[1][3]
def whosdaddy():
return inspect.stack()[2][3]
def foo():
print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
bar()
def bar():
print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
foo()
bar()
In IDE the code outputs
hello, I'm foo, daddy is
hello, I'm bar, daddy is foo
hello, I'm bar, daddy is
Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r
.
So here in your case it'd be something like
local> scp -r [email protected]:/path/to/dir local/path
If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
This is my version (simple and easy):
uses memory only twice the size of original array.
[ a is the left array ] [ b is the right array ] [ c used to merge a and b ] [ p is counter for c ]
void MergeSort(int list[], int size)
{
int blockSize = 1, p;
int *a, *b;
int *c = new int[size];
do
{
for (int k = 0; k < size; k += (blockSize * 2))
{
a = &list[k];
b = &list[k + blockSize];
p = 0;
for (int i = 0, j = 0; i < blockSize || j < blockSize;)
{
if ((j < blockSize) && ((k + j + blockSize) >= size))
{
++j;
}
else if ((i < blockSize) && ((k + i) >= size))
{
++i;
}
else if (i >= blockSize)
{
c[p++] = b[j++];
}
else if (j >= blockSize)
{
c[p++] = a[i++];
}
else if (a[i] >= b[j])
{
c[p++] = b[j++];
}
else if (a[i] < b[j])
{
c[p++] = a[i++];
}
}
for (int i = 0; i < p; i++)
{
a[i] = c[i];
}
}
blockSize *= 2;
} while (blockSize < size);
}
I wasn't able to remotely connect to the SQL server either. Both SQL server and remote server where in the same domain. And I had been requested a password change some days before. Restarting both the SQL server and the remote server I was trying to access SQL server from did the trick for me.
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
Just wanted to drop a note. I was having trouble formatting a text 4000 field that had a mind of its own and the text would seeming wrap (or not wrap) randomly on the report. When I updated the column using the replace chr(10) noted above. My report finally formatted as I wanted. Many Thanx!
Another alternative altogether is to use the printf function.
printf -v str 'hello'
Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.
My "disappeared" folder was libraries/fof
.
If I deleted it, then ran an update, it wouldn't show up.
cd libaries
svn up
(nothing happens).
But updating with the actual name:
svn update fof
did the trick and it was updated. So I exploded my (manually tar-archived) working copy over it and recommitted. Easiest solution.
CancelAsync
doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending
. Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.
The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool
), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx
http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx
ReSharper - Ctrl + Alt + F
Visual Studio 2010 - Ctrl + K, Ctrl + D
shutil.copy
and shutil.copy2
are copying files.
shutil.copytree
copies a folder with all the files and all subfolders. shutil.copytree
is using shutil.copy2
to copy the files.
So the analog to cp -r
you are saying is the shutil.copytree
because cp -r
targets and copies a folder and its files/subfolders like shutil.copytree
. Without the -r
cp
copies files like shutil.copy
and shutil.copy2
do.
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple
As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4
_.startsWith([string=''], [target], [position=0])
TL;DR: Use the utility method Iterables.size(Iterable)
of the great Guava library.
Of your two code snippets, you should use the first one, because the second one will remove all elements from values
, so it is empty afterwards. Changing a data structure for a simple query like its size is very unexpected.
For performance, this depends on your data structure. If it is for example in fact an ArrayList
, removing elements from the beginning (what your second method is doing) is very slow (calculating the size becomes O(n*n) instead of O(n) as it should be).
In general, if there is the chance that values
is actually a Collection
and not only an Iterable
, check this and call size()
in case:
if (values instanceof Collection<?>) {
return ((Collection<?>)values).size();
}
// use Iterator here...
The call to size()
will usually be much faster than counting the number of elements, and this trick is exactly what Iterables.size(Iterable)
of Guava does for you.
I would vote for jamtoday's answer if I had the "reputation"
If your data is coming by way of PHP, this might help
$str = str_replace(array("\r", "\n"), '', $str);
Short and simple:
Function.prototype.clone = function() {
return new Function('return ' + this.toString())();
};
You can use a BehaviorSubject
for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject
to which you can subscribe and emit changes.
Define a data sharing service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
Add the DataSharingService
in your AppModule
providers entry.
Next, import the DataSharingService
in your <app-header>
and in the component where you perform the sign-in operation. In <app-header>
subscribe to the changes to isUserLoggedIn
subject:
import { DataSharingService } from './data-sharing.service';
export class AppHeaderComponent {
// Define a variable to use for showing/hiding the Login button
isUserLoggedIn: boolean;
constructor(private dataSharingService: DataSharingService) {
// Subscribe here, this will automatically update
// "isUserLoggedIn" whenever a change to the subject is made.
this.dataSharingService.isUserLoggedIn.subscribe( value => {
this.isUserLoggedIn = value;
});
}
}
In your <app-header>
html template, you need to add the *ngIf
condition e.g.:
<button *ngIf="!isUserLoggedIn">Login</button>
<button *ngIf="isUserLoggedIn">Sign Out</button>
Finally, you just need to emit the event once the user has logged in e.g:
someMethodThatPerformsUserLogin() {
// Some code
// .....
// After the user has logged in, emit the behavior subject changes.
this.dataSharingService.isUserLoggedIn.next(true);
}
Here's yet another idea - this method allows to specify any working week and holidays.
The idea here is that we find the core of the date range from the first first working day of the week to the last weekend day of the week. This enables us to calculate the whole weeks easily (without iterating over all of the dates). All we need to do then is to add the working days that fall before the start and end of this core range.
public static int CalculateWorkingDays(
DateTime startDate,
DateTime endDate,
IList<DateTime> holidays,
DayOfWeek firstDayOfWeek,
DayOfWeek lastDayOfWeek)
{
// Make sure the defined working days run contiguously
if (lastDayOfWeek < firstDayOfWeek)
{
throw new Exception("Last day of week cannot fall before first day of week!");
}
// Create a list of the days of the week that make-up the weekend by working back
// from the firstDayOfWeek and forward from lastDayOfWeek to get the start and end
// the weekend
var weekendStart = lastDayOfWeek == DayOfWeek.Saturday ? DayOfWeek.Sunday : lastDayOfWeek + 1;
var weekendEnd = firstDayOfWeek == DayOfWeek.Sunday ? DayOfWeek.Saturday : firstDayOfWeek - 1;
var weekendDays = new List<DayOfWeek>();
var w = weekendStart;
do {
weekendDays.Add(w);
if (w == weekendEnd) break;
w = (w == DayOfWeek.Saturday) ? DayOfWeek.Sunday : w + 1;
} while (true);
// Force simple dates - no time
startDate = startDate.Date;
endDate = endDate.Date;
// Ensure a progessive date range
if (endDate < startDate)
{
var t = startDate;
startDate = endDate;
endDate = t;
}
// setup some working variables and constants
const int daysInWeek = 7; // yeah - really!
var actualStartDate = startDate; // this will end up on startOfWeek boundary
var actualEndDate = endDate; // this will end up on weekendEnd boundary
int workingDaysInWeek = daysInWeek - weekendDays.Count;
int workingDays = 0; // the result we are trying to find
int leadingDays = 0; // the number of working days leading up to the firstDayOfWeek boundary
int trailingDays = 0; // the number of working days counting back to the weekendEnd boundary
// Calculate leading working days
// if we aren't on the firstDayOfWeek we need to step forward to the nearest
if (startDate.DayOfWeek != firstDayOfWeek)
{
var d = startDate;
do {
if (d.DayOfWeek == firstDayOfWeek || d >= endDate)
{
actualStartDate = d;
break;
}
if (!weekendDays.Contains(d.DayOfWeek))
{
leadingDays++;
}
d = d.AddDays(1);
} while(true);
}
// Calculate trailing working days
// if we aren't on the weekendEnd we step back to the nearest
if (endDate >= actualStartDate && endDate.DayOfWeek != weekendEnd)
{
var d = endDate;
do {
if (d.DayOfWeek == weekendEnd || d < actualStartDate)
{
actualEndDate = d;
break;
}
if (!weekendDays.Contains(d.DayOfWeek))
{
trailingDays++;
}
d = d.AddDays(-1);
} while(true);
}
// Calculate the inclusive number of days between the actualStartDate and the actualEndDate
var coreDays = (actualEndDate - actualStartDate).Days + 1;
var noWeeks = coreDays / daysInWeek;
// add together leading, core and trailing days
workingDays += noWeeks * workingDaysInWeek;
workingDays += leadingDays;
workingDays += trailingDays;
// Finally remove any holidays that fall within the range.
if (holidays != null)
{
workingDays -= holidays.Count(h => h >= startDate && (h <= endDate));
}
return workingDays;
}
I use this function (it only checks if the y is inscreen since most of the time the x is not needed)
function elementInViewport(el) {
var elinfo = {
"top":el.offsetTop,
"height":el.offsetHeight,
};
if (elinfo.top + elinfo.height < window.pageYOffset || elinfo.top > window.pageYOffset + window.innerHeight) {
return false;
} else {
return true;
}
}
further to S.Lott's reply, class variables get passed to metaclass new method and can be accessed through the dictionary when a metaclass is defined. So, class variables can be accessed even before classes are created and instantiated.
for example:
class meta(type):
def __new__(cls,name,bases,dicto):
# two chars missing in original of next line ...
if dicto['class_var'] == 'A':
print 'There'
class proxyclass(object):
class_var = 'A'
__metaclass__ = meta
...
...
this worked for me inside a directive and works without refreshing the baseurl (just adds the endpoint).Good for Single Page Apps with routing mechanism.
$(location).attr('href', 'http://localhost:10005/#/endpoint')
The corporate HTTP proxy behind which I currently am sporadically gives this error. I can fix it by simply visiting bitbucket.org in a browser, then retyring the command. Have no idea why this works, but it does fix it for me (at least temporarily).
html:
<form method="post" name="form1" id="form1">
<input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>
Javascript: to submit the form using javascript
function eatFood() {
document.getElementById('form1').submit();
}
to show onclick message
function eatFood() {
alert('Form has been submitted');
}
Happend to me after I've installed some updates in eclipse but forgot to restart afterwards. So maybe restarting eclipse might help.
I faced the same problem and did the filtering false like below working for me. You can try the same...
<testResources>
<testResource>
<directory>src/test/java</directory>
<filtering>false</filtering>
</testResource>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
</testResource>
</testResources>
Converting already utf-8 encoded text by using mb_convert_encoding
is not needed. Just add three characters in front of the original content:
$newContent = chr(239) . chr(187) . chr(191) . $originalContent
For me this resolved the problem of special characters in csv files.
VB.net translation
Module MyWpfExtensions
Public Function GetIWin32Window(this As Object, visual As System.Windows.Media.Visual) As System.Windows.Forms.IWin32Window
Dim source As System.Windows.Interop.HwndSource = System.Windows.PresentationSource.FromVisual(Visual)
Dim win As System.Windows.Forms.IWin32Window = New OldWindow(source.Handle)
Return win
End Function
Private Class OldWindow
Implements System.Windows.Forms.IWin32Window
Public Sub New(handle As System.IntPtr)
_handle = handle
End Sub
Dim _handle As System.IntPtr
Public ReadOnly Property Handle As IntPtr Implements Forms.IWin32Window.Handle
Get
End Get
End Property
End Class
End Module
distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).
distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]
hope that this helps
i've used distanceTo to get the distance from point A to B i think that is the way to go.
You're looking for keydown/press/up
$("#inputID").keydown(function(event) {
alert(event.keyCode);
});
or using bind $("#inputID").bind('onkeydown', ...
Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
change key Cache to something like C:\Windows\Temp
My similar problem was solved like this.
Regards,
Ripley
x_file = open(os.path.join(direct, '5_1.txt'), 'r')
Timing with random strings of ASCII printables:
from inspect import getsource
from random import sample
import re
from string import printable
from timeit import timeit
pattern_single = re.compile(r'[\W]')
pattern_repeat = re.compile(r'[\W]+')
translation_tb = str.maketrans('', '', ''.join(c for c in map(chr, range(256)) if not c.isalnum()))
def generate_test_string(length):
return ''.join(sample(printable, length))
def main():
for i in range(0, 60, 10):
for test in [
lambda: ''.join(c for c in generate_test_string(i) if c.isalnum()),
lambda: ''.join(filter(str.isalnum, generate_test_string(i))),
lambda: re.sub(r'[\W]', '', generate_test_string(i)),
lambda: re.sub(r'[\W]+', '', generate_test_string(i)),
lambda: pattern_single.sub('', generate_test_string(i)),
lambda: pattern_repeat.sub('', generate_test_string(i)),
lambda: generate_test_string(i).translate(translation_tb),
]:
print(timeit(test), i, getsource(test).lstrip(' lambda: ').rstrip(',\n'), sep='\t')
if __name__ == '__main__':
main()
Result (Python 3.7):
Time Length Code
6.3716264850008880 00 ''.join(c for c in generate_test_string(i) if c.isalnum())
5.7285426190064750 00 ''.join(filter(str.isalnum, generate_test_string(i)))
8.1875841680011940 00 re.sub(r'[\W]', '', generate_test_string(i))
8.0002205439959650 00 re.sub(r'[\W]+', '', generate_test_string(i))
5.5290945199958510 00 pattern_single.sub('', generate_test_string(i))
5.4417179649972240 00 pattern_repeat.sub('', generate_test_string(i))
4.6772285089973590 00 generate_test_string(i).translate(translation_tb)
23.574712151996210 10 ''.join(c for c in generate_test_string(i) if c.isalnum())
22.829975890002970 10 ''.join(filter(str.isalnum, generate_test_string(i)))
27.210196289997840 10 re.sub(r'[\W]', '', generate_test_string(i))
27.203713296003116 10 re.sub(r'[\W]+', '', generate_test_string(i))
24.008979928999906 10 pattern_single.sub('', generate_test_string(i))
23.945240008994006 10 pattern_repeat.sub('', generate_test_string(i))
21.830899796994345 10 generate_test_string(i).translate(translation_tb)
38.731336012999236 20 ''.join(c for c in generate_test_string(i) if c.isalnum())
37.942474347000825 20 ''.join(filter(str.isalnum, generate_test_string(i)))
42.169366310001350 20 re.sub(r'[\W]', '', generate_test_string(i))
41.933375883003464 20 re.sub(r'[\W]+', '', generate_test_string(i))
38.899814646996674 20 pattern_single.sub('', generate_test_string(i))
38.636144253003295 20 pattern_repeat.sub('', generate_test_string(i))
36.201238164998360 20 generate_test_string(i).translate(translation_tb)
49.377356811004574 30 ''.join(c for c in generate_test_string(i) if c.isalnum())
48.408927293996385 30 ''.join(filter(str.isalnum, generate_test_string(i)))
53.901889764994850 30 re.sub(r'[\W]', '', generate_test_string(i))
52.130339455994545 30 re.sub(r'[\W]+', '', generate_test_string(i))
50.061149017004940 30 pattern_single.sub('', generate_test_string(i))
49.366573111998150 30 pattern_repeat.sub('', generate_test_string(i))
46.649754120997386 30 generate_test_string(i).translate(translation_tb)
63.107938601999194 40 ''.join(c for c in generate_test_string(i) if c.isalnum())
65.116287978999030 40 ''.join(filter(str.isalnum, generate_test_string(i)))
71.477421126997800 40 re.sub(r'[\W]', '', generate_test_string(i))
66.027950693998720 40 re.sub(r'[\W]+', '', generate_test_string(i))
63.315361931003280 40 pattern_single.sub('', generate_test_string(i))
62.342320287003530 40 pattern_repeat.sub('', generate_test_string(i))
58.249303059004890 40 generate_test_string(i).translate(translation_tb)
73.810345625002810 50 ''.join(c for c in generate_test_string(i) if c.isalnum())
72.593953348005020 50 ''.join(filter(str.isalnum, generate_test_string(i)))
76.048324580995540 50 re.sub(r'[\W]', '', generate_test_string(i))
75.106637657001560 50 re.sub(r'[\W]+', '', generate_test_string(i))
74.681338128997600 50 pattern_single.sub('', generate_test_string(i))
72.430461594005460 50 pattern_repeat.sub('', generate_test_string(i))
69.394243567003290 50 generate_test_string(i).translate(translation_tb)
str.maketrans
& str.translate
is fastest, but includes all non-ASCII characters.
re.compile
& pattern.sub
is slower, but is somehow faster than ''.join
& filter
.
On Mac OS - Installing tensorflow 1.3 - it will automatically remove other protobuf installs and install protobuf 3.4. However, this does not work and neither does installing or downgrading to any other protobuf version.
However I found a solution. Not sure why this works - but on Mac OS this solved it.
pip install google
You can just redirect in your success
handler, like this:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
Well now will be different after angular 5:
{{ number | currency :'GBP':'symbol':'1.2-2' }}
If you use option 2 you are doing a Boolean check which is fast. In option one you are doing a method call (pushing stuff on the stack) and then doing a Boolean check which is still fast. The problem I see is consistency. If some of your debug and info statements are wrapped and some are not it is not a consistent code style. Plus someone later on could change the debug statement to include concatenate strings, which is still pretty fast. I found that when we wrapped out debug and info statement in a large application and profiled it we saved a couple of percentage points in performance. Not much, but enough to make it worth the work. I now have a couple of macros setup in IntelliJ to automatically generate wrapped debug and info statements for me.
This is a common problem with GoDaddy virtual server hosting when you bring up a new website.
Assuming you have SSH access to the server (you have to enable it on cPanel), login to your account. Upon successful login, you will be placed in the home directory for your account. The DocumentRoot for your website is located in a subdirectory named public_html. GoDaddy defaults the permissions for this directory to 750, but those permissions are inadequate to allow Apache to read the files for website. You need to change the permissions for this directory to 755 (chmod 755 public_html).
Copy the files for your website into the public_html directory (both scp and rsync work for copying files to a GoDaddy Linux server).
Next, make sure all of the files under public_html are world readable. To do this, use this command:
cd public_html
chmod -R o+r *
If you have other subdirectories (like css, js, and img), make sure they are world accessible by enabling both read and execute for world access:
chmod o+rx css
chmod o+rx img
chmod o+rx js
Last, you will need to have a .htaccess file in the public_html file. GoDaddy enforces a rule that prohibits the site for loading if you do not have a .htaccess file in your public_html directory. You can use vi to create this file ("vi .htaccess"). Enter the following lines in the file:
Order allow,deny
Allow from all
Require all granted
This config will work for both Apache 2.2 and Apache 2.4. Save the file (ZZ), and then make sure the file has permissions of 644:
chmod 644 .htaccess
Works like a charm.
I found that we can use color selector for tint attr:
mImageView.setEnabled(true);
activity_main.xml:
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_arrowup"
android:tint="@color/section_arrowup_color" />
section_arrowup_color.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/white" android:state_enabled="true"/>
<item android:color="@android:color/black" android:state_enabled="false"/>
<item android:color="@android:color/white"/>
</selector>
Java supports two methods for XML parsing out of the box.
SAXParser
You can use this parser if you want to parse large XML files and/or don't want to use a lot of memory.
http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html
Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
DOMParser
You can use this parser if you need to do XPath queries or need to have the complete DOM available.
http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html
Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
MySQL Workbench
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.
When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
Don't forget to hit "Apply" when you are done with all changes.
PhpMyAdmin:
If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.
I use printf, is shorter as it doesn't need flags to do the work:
printf "\rMy static $myvars composed text"
Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper
's convertValue
method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
No need to convert into JSON string or something else; direct conversion does much faster.
Most of the confusion in the question/answers here surrounds the definition of Inheritance.
Obviously, as @DigitalRoss explains an OBJECT of a subclass must contain its superclass's private fields. As he states, having no access to a private member doesn't mean its not there.
However. This is different than the notion of inheritance for a class. As is the case in the java world, where there is a question of semantics the arbiter is the Java Language Specification (currently 3rd edition).
As the JLS states (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):
Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
This addresses the exact question posed by the interviewer: "do subCLASSES inherit private fields". (emphasis added by me)
The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass.
Is it semantics of a pedantic nature? Yes. Is it a useful interview question? Probably not. But the JLS establishes the definition for the Java world, and it does so (in this case) unambiguously.
EDITED (removed a parallel quote from Bjarne Stroustrup which due to the differences between java and c++ probably only add to the confusion. I'll let my answer rest on the JLS :)
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
from the official python tutorial Modules
To speed up loading modules, Python caches the compiled version of each module in the
__pycache__
directory under the namemodule.version.pyc
, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.6 the compiled version of spam.py would be cached as__pycache__/spam.cpython-36.pyc
.
from Python doc Programming FAQs
When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a .pyc file containing the compiled code should be created in a
__pycache__
subdirectory of the directory containing the.py
file. The.pyc
file will have a filename that starts with the same name as the.py
file, and ends with.pyc
, with a middle component that depends on the particular python binary that created it.
Try something like this:
<div id="LoadingImage" style="display: none">
<img src="" />
</div>
<script>
function ajaxCall(){
$("#LoadingImage").show();
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
$("#LoadingImage").hide();
alert("Success");
},
error: function (xhr, status) {
$("#LoadingImage").hide();
alert('Unknown error ' + status);
}
});
}
</script>
Use [.]
instead of \.
and [0-9]
instead of \d
to avoid escaping issues in some languages (like Java).
Thanks to the nameless one for originally recognizing this.
One relatively simple pattern for matching a floating point number is
[+-]?([0-9]*[.])?[0-9]+
This will match:
123
123.456
.456
See a working example
If you also want to match 123.
(a period with no decimal part), then you'll need a slightly longer expression:
[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)
See pkeller's answer for a fuller explanation of this pattern
If you want to include non-decimal numbers, such as hex and octal, see my answer to How do I identify if a string is a number?.
If you want to validate that an input is a number (rather than finding a number within the input), then you should surround the pattern with ^
and $
, like so:
^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$
"Regular expressions", as implemented in most modern languages, APIs, frameworks, libraries, etc., are based on a concept developed in formal language theory. However, software engineers have added many extensions that take these implementations far beyond the formal definition. So, while most regular expression engines resemble one another, there is actually no standard. For this reason, a lot depends on what language, API, framework or library you are using.
(Incidentally, to help reduce confusion, many have taken to using "regex" or "regexp" to describe these enhanced matching languages. See Is a Regex the Same as a Regular Expression? at RexEgg.com for more information.)
That said, most regex engines (actually, all of them, as far as I know) would accept \.
. Most likely, there's an issue with escaping.
Some languages have built-in support for regexes, such as JavaScript. For those languages that don't, escaping can be a problem.
This is because you are basically coding in a language within a language. Java, for example, uses \
as an escape character within it's strings, so if you want to place a literal backslash character within a string, you must escape it:
// creates a single character string: "\"
String x = "\\";
However, regexes also use the \
character for escaping, so if you want to match a literal \
character, you must escape it for the regexe engine, and then escape it again for Java:
// Creates a two-character string: "\\"
// When used as a regex pattern, will match a single character: "\"
String regexPattern = "\\\\";
In your case, you have probably not escaped the backslash character in the language you are programming in:
// will most likely result in an "Illegal escape character" error
String wrongPattern = "\.";
// will result in the string "\."
String correctPattern = "\\.";
All this escaping can get very confusing. If the language you are working with supports raw strings, then you should use those to cut down on the number of backslashes, but not all languages do (most notably: Java). Fortunately, there's an alternative that will work some of the time:
String correctPattern = "[.]";
For a regex engine, \.
and [.]
mean exactly the same thing. Note that this doesn't work in every case, like newline (\\n
), open square bracket (\\[
) and backslash (\\\\
or [\\]
).
(Hint: It's harder than you think)
Matching a number is one of those things you'd think is quite easy with regex, but it's actually pretty tricky. Let's take a look at your approach, piece by piece:
[-+]?
Match an optional -
or +
[0-9]*
Match 0 or more sequential digits
\.?
Match an optional .
[0-9]*
Match 0 or more sequential digits
First, we can clean up this expression a bit by using a character class shorthand for the digits (note that this is also susceptible to the escaping issue mentioned above):
[0-9]
= \d
I'm going to use \d
below, but keep in mind that it means the same thing as [0-9]
. (Well, actually, in some engines \d
will match digits from all scripts, so it'll match more than [0-9]
will, but that's probably not significant in your case.)
Now, if you look at this carefully, you'll realize that every single part of your pattern is optional. This pattern can match a 0-length string; a string composed only of +
or -
; or, a string composed only of a .
. This is probably not what you've intended.
To fix this, it's helpful to start by "anchoring" your regex with the bare-minimum required string, probably a single digit:
\d+
Now we want to add the decimal part, but it doesn't go where you think it might:
\d+\.?\d* /* This isn't quite correct. */
This will still match values like 123.
. Worse, it's got a tinge of evil about it. The period is optional, meaning that you've got two repeated classes side-by-side (\d+
and \d*
). This can actually be dangerous if used in just the wrong way, opening your system up to DoS attacks.
To fix this, rather than treating the period as optional, we need to treat it as required (to separate the repeated character classes) and instead make the entire decimal portion optional:
\d+(\.\d+)? /* Better. But... */
This is looking better now. We require a period between the first sequence of digits and the second, but there's a fatal flaw: we can't match .123
because a leading digit is now required.
This is actually pretty easy to fix. Instead of making the "decimal" portion of the number optional, we need to look at it as a sequence of characters: 1 or more numbers that may be prefixed by a .
that may be prefixed by 0 or more numbers:
(\d*\.)?\d+
Now we just add the sign:
[+-]?(\d*\.)?\d+
Of course, those slashes are pretty annoying in Java, so we can substitute in our long-form character classes:
[+-]?([0-9]*[.])?[0-9]+
This has come up in the comments a couple times, so I'm adding an addendum on matching versus validating.
The goal of matching is to find some content within the input (the "needle in a haystack"). The goal of validating is to ensure that the input is in an expected format.
Regexes, by their nature, only match text. Given some input, they will either find some matching text or they will not. However, by "snapping" an expression to the beginning and ending of the input with anchor tags (^
and $
), we can ensure that no match is found unless the entire input matches the expression, effectively using regexes to validate.
The regex described above ([+-]?([0-9]*[.])?[0-9]+
) will match one or more numbers within a target string. So given the input:
apple 1.34 pear 7.98 version 1.2.3.4
The regex will match 1.34
, 7.98
, 1.2
, .3
and .4
.
To validate that a given input is a number and nothing but a number, "snap" the expression to the start and end of the input by wrapping it in anchor tags:
^[+-]?([0-9]*[.])?[0-9]+$
This will only find a match if the entire input is a floating point number, and will not find a match if the input contains additional characters. So, given the input 1.2
, a match will be found, but given apple 1.2 pear
no matches will be found.
Note that some regex engines have a validate
, isMatch
or similar function, which essentially does what I've described automatically, returning true
if a match is found and false
if no match is found. Also keep in mind that some engines allow you to set flags which change the definition of ^
and $
, matching the beginning/end of a line rather than the beginning/end of the entire input. This is typically not the default, but be on the lookout for these flags.
You can use:
element = driver.find_element_by_class_name("class_name").text
This will return the text within the element and will allow you to verify it after that.
Question: Check whether a $_POST value is empty.
Translation: Check to see if an array key/index has a value associated with it.
Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.
1. Some people say use empty().
From the PHP Manual:
"[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."
The following are thus considered empty.
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
If none of these values are valid for your input control, then empty()
would work. The problem here is that empty()
might be too broad to be used consistently (the same way, for the same reason, on different input control submissions to $_POST
or $_GET
). A good use of empty()
is to check if an entire array is empty (has no elements).
2. Some people say use isset().
isset()
(a language construct) cannot operate on entire arrays, as in isset($myArray)
. It can only operate on variables and array elements (via the index/key): isset($var)
and isset($_POST['username'])
. The isset()
language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.
In short, the most accurate check can be accomplished best with isset()
, as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset()
to check if a $_POST
key has no value associated with it (and that is not NULL). isset()
is a much stricter test of emptiness (in the sense of your question) than empty()
.
3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.
You can test anything that evaluates to true or false in an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with
empty()
, many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.--Doyle, Beginning PHP 5.3
In conclusion, use isset()
and consider combining it with other tests. Example:
May not work due to superglobal screwiness, but would work for other arrays without question.
if (is_array($_POST) && !empty($_POST)) {
// Now test for your successful controls in $_POST with isset()
}
Hence, why look for a value associated with a key before you even know for sure that $_POST
represents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POST
only has the allowed keys, but that conversation is for another day.
Useful reference:
This also happened to me on Ubuntu 16.04 using the nvidia-348
package (latest nvidia version on Ubuntu 16.04).
However I could resolve the problem by installing nvidia-390
through the Proprietary GPU Drivers PPA.
So a solution to the described problem on Ubuntu 16.04 is doing this:
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
sudo apt-get install nvidia-390
Note: This guide assumes a clean Ubuntu install. If you have previous drivers installed a reboot migh be needed to reload all the kernel modules.
Using .mvn/jvm.config worked for me plus has the added benefit of being linked with the project.
import ReactDOM from 'react-dom';
//...
componentDidMount() {
var n = ReactDOM.findDOMNode(this);
console.log(n.offsetTop);
}
You can just grab the offsetTop from the Node.
I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:
Add-PSSnapin Microsoft.Sharepoint.Powershell
in the Powershell console.
The isConnected
method won't help, it will return true
even if the remote side has closed the socket. Try this:
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.
In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).
A quick Google search brings up hash tables in JavaScript.
Example code for looping over values in a hash (from the aforementioned link):
var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
// Show the values stored
for (var i in myArray) {
alert('key is: ' + i + ', value is: ' + myArray[i]);
}
Objective - C
NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding];
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);
Swift
//This your data containing the string
let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)
//Use this method to convert the data into String
let myStringFromData = String(data:myStringData!, encoding: NSUTF8StringEncoding)
print("My string value:" + myStringFromData!)
http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html
I would suggest using inline CSS styling.
<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>
I don't quite follow what you need, but this is what I would do, assuming I understand you needs.
Check out this solution. It worked for me..... Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app. If yes, then change the id of them and then the app runs perfectly.
I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!! Hope it works
Match the whole line, so add a .*
at the beginning of your regex. This causes the entire line to be replaced with the contents of the group
echo "foo bar <foo> bla 1 2 3.4" |
sed -n 's/.*\([0-9][0-9]*[\ \t][0-9.]*[ \t]*$\)/\1/p'
2 3.4
https://firebase.google.com/docs/firestore/manage-data/transactions
Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.
As shown here, the second argument to substr
is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position
pos
and has a length ofn
characters.
Your line b = a.substr(i,i+1);
will generate, for values of i
:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45
due to the fact that you're using atoi()
on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Yes. You need to use the try/catch
block, but no need to catch the Exception
. As per the API it will throw NoResultException
if there is no result, and its up to you how you want to handle it.
DrawUnusedBalance drawUnusedBalance = null;
try{
drawUnusedBalance = (DrawUnusedBalance)query.getSingleResult()
catch (NoResultException nre){
//Ignore this because as per your logic this is ok!
}
if(drawUnusedBalance == null){
//Do your logic..
}
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
And we get:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Hope this helps someone!
You can use git cherry-pick
to just pick the commit that you want to copy over.
Probably the best way is to create the branch out of master, then in that branch use git cherry-pick
on the 2 commits from quickfix2 that you want.
on the form2.buttonclick put
this.close();
form1 should have object of form2.
you need to subscribe Closing event of form2.
and in closing method put
this.close();
php -v
yum search php-
yum install ea-php56-php-mbstring.x86_64
httpd -k restart
Package name - ea-php-php-mbstring.x86_64
What Google(search bot) needs is same content should be served to bot as it is served to user. Indenting text away (any text) gets bot to think it is a spam or you are serving different content to user and bot.
The best method is to directly use logo as an image inside your anchor tag. Give an 'alt' to your image. This will be perfect for bot to read & also will help in image searching.
This is straight from the horse's mouth: http://www.youtube.com/watch?v=fBLvn_WkDJ4
Save the bat file on "C:\WINDOWS\system32" and use below code it is working
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)
If errorCode = 0 Then
'Insert your code here
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
In addition to Eduard Void answer here's the addValidators
method:
declare module '@angular/forms' {
interface FormControl {
addValidators(validators: ValidatorFn[]): void;
}
}
FormControl.prototype.addValidators = function(this: FormControl, validators: ValidatorFn[]) {
if (!validators || !validators.length) {
return;
}
this.clearValidators();
this.setValidators( this.validator ? [ this.validator, ...validators ] : validators );
};
Using it you can set validators dynamically:
some_form_control.addValidators([ first_validator, second_validator ]);
some_form_control.addValidators([ third_validator ]);
Hope you are using Python 3 ,
Str are unicode by default, so please
Replace Unicode
function with String Str
function.
if isinstance(unicode_or_str, str): ##Replaces with str
text = unicode_or_str
decoded = False
Via here
Checking the owner of /dev/console seems to work well.
stat -f "%Su" /dev/console
I just used the following code, which removed all the punctuation:
tokens = nltk.wordpunct_tokenize(raw)
type(tokens)
text = nltk.Text(tokens)
type(text)
words = [w.lower() for w in text if w.isalpha()]