Faced this exact problem,
for me it worked by
deleting
package-lock.json
and re runnpm install
if it doesn't resolve try
package-lock.json
You don't need to add '.' in your class name. This will do
document.getElementsByClassName('col1')
Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.
Here is a working example
Did you try InputMethodManager.SHOW_IMPLICIT
in first window.
and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY
EDIT :
If its still not working then probably you are putting it at the wrong place. Override onFinishInflate()
and show/hide there.
@override
public void onFinishInflate() {
/* code to show keyboard on startup */
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}
string s2 = s1.Replace(",", ",\r\n");
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
Sometimes i use this: http://closure-compiler.appspot.com/home
Default, registry api return 100 entries of catalog, there is the code:
When you curl the registry api:
curl --cacert domain.crt https://your.registry:5000/v2/_catalog
it equivalents with:
curl --cacert domain.crt https://your.registry:5000/v2/_catalog?n=100
This is a pagination methond.
When the sum of entries beyond 100, you can do in two ways:
First: give a bigger number
curl --cacert domain.crt https://your.registry:5000/v2/_catalog?n=2000
Sencond: parse the next linker url
curl --cacert domain.crt https://your.registry:5000/v2/_catalog
A link element contained in response header:
curl --cacert domain.crt https://your.registry:5000/v2/_catalog
response header:
Link: </v2/_catalog?last=pro-octopus-ws&n=100>; rel="next"
The link element have the last entry of this request, then you can request the next 'page':
curl --cacert domain.crt https://your.registry:5000/v2/_catalog?last=pro-octopus-ws
If the response header contains link element, you can do it in a loop.
When you get the result of catalog, it like follows:
{
"repositories": [
"busybox",
"ceph/mds"
]
}
you can get the images in every catalog:
curl --cacert domain.crt https://your.registry:5000/v2/busybox/tags/list
returns:
{"name":"busybox","tags":["latest"]}
Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )
public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
{
//variables
string pathin = inputPdfPath;
string pathout = outputPdfPath;
//create PdfReader object to read from the existing document
using (PdfReader reader = new PdfReader(pathin))
//create PdfStamper object to write to get the pages from reader
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
{
//select two pages from the original document
reader.SelectPages("1-2");
//gettins the page size in order to substract from the iTextSharp coordinates
var pageSize = reader.GetPageSize(1);
// PdfContentByte from stamper to add content to the pages over the original content
PdfContentByte pbover = stamper.GetOverContent(1);
//add content to the page using ColumnText
Font font = new Font();
font.Size = 45;
//setting up the X and Y coordinates of the document
int x = point.X;
int y = point.Y;
y = (int) (pageSize.Height - y);
ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
}
}
With the requests
lib JSONDecodeError
can happen when you have an http error code like 404 and try to parse the response as JSON !
You must first check for 200 (OK) or let it raise on error to avoid this case. I wish it failed with a less cryptic error message.
NOTE: as Martijn Pieters stated in the comments servers can respond with JSON in case of errors (it depends on the implementation), so checking the Content-Type
header is more reliable.
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.
An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
error : function(req, status, error) {
// do something with error
}
});
You can try this:
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabBackground">@drawable/background</item>
</style>
In your background xml file:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/white" />
<item android:drawable="@color/black" />
</selector>
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
Based on other answers and my tries, best experience would be first installing, pillow and scipy, then using the following starting code on your jupyter notebook:
%matplotlib inline
from matplotlib.pyplot import imshow
from scipy.misc import imread
imshow(imread('image.jpg', 1))
What are you going to do with the URI?
If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.
HttpGet get = new HttpGet("http://stackoverflow.com");
If all you want to do is read the same information more than once, and the input data is small enough to fit into memory, you can copy the data from your InputStream
to a ByteArrayOutputStream.
Then you can obtain the associated array of bytes and open as many "cloned" ByteArrayInputStreams as you like.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Code simulating the copy
// You could alternatively use NIO
// And please, unlike me, do something about the Exceptions :D
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush();
// Open new InputStreams using recorded bytes
// Can be repeated as many times as you wish
InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
InputStream is2 = new ByteArrayInputStream(baos.toByteArray());
But if you really need to keep the original stream open to receive new data, then you will need to track the external call to close()
. You will need to prevent close()
from being called somehow.
Since Java 9 the the middle bits can be replaced with InputStream.transferTo
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
input.transferTo(baos);
InputStream firstClone = new ByteArrayInputStream(baos.toByteArray());
InputStream secondClone = new ByteArrayInputStream(baos.toByteArray());
If you prefer using column names, you could do something like this as an alternative:
min(data$column_name)
Some lines end with \n
.
Some other lines end with \r\n
.
Visual Studio suggests you to make all lines end the same.
You can also use the void operator to obtain an undefined value:
if (input !== void 0) {
// do stuff
}
(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0
for testing global variables or adding var input
.)
Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/
Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.
You could do:
chcon -R -t httpd_sys_rw_content_t storage
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
This type of issue crops up for me now that I've moved to Python 3. I had no idea Python 2 was simply steam rolling any issues with file encoding.
I found this nice explanation of the differences and how to find a solution after none of the above worked for me.
http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html
In short, to make Python 3 behave as similarly as possible to Python 2 use:
with open(filename, encoding="latin-1") as datafile:
# work on datafile here
However, read the article, there is no one size fits all solution.
You're looking for this on the command line (for a class called MyClass):
On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
You want the major version from the results. Here are some example values:
I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)
if (location.hash) { // do the test straight away
window.scrollTo(0, 0); // execute it straight away
setTimeout(function() {
window.scrollTo(0, 0); // run it a bit later also for browser compatibility
}, 1);
}
I always supposed avg
is omitted from the builtins/stdlib because it is as simple as
sum(L)/len(L) # L is some list
and any caveats would be addressed in caller code for local usage already.
Notable caveats:
non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L)
or from __future__ import division
division by zero: the list may be empty. to resolve:
if not L:
raise WhateverYouWantError("foo")
avg = float(sum(L))/len(L)
You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:
I had this, but, it was because I had added a NuGet package that had updated the binding redirects. Once I removed the package, the redirects were still there. I removed all of them, and then ran update-package -reinstall. This added the correct redirects.
By changing proxy settings to "no proxy" in netbeans the tomcat prbolem got solved.Try this it's seriously working.
Set objShell = WScript.CreateObject("WScript.Shell")
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
end with
if bFound then
msgbox "exists"
else
msgbox "not exists"
End If
#include <stdio.h>
int main()
{
int a, b;
printf("Enter A :");
scanf("%d",&a);
printf("Enter B :");
scanf("%d",&b);
a ^= b;
b ^= a;
a ^= b;
printf("\nValue of A=%d B=%d ",a,b);
return 1;
}
@Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:
(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)
canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();
The correct answer, from all above, is to run the commands below:
sudo cp /etc/kubernetes/admin.conf $HOME/
sudo chown $(id -u):$(id -g) $HOME/admin.conf
export KUBECONFIG=$HOME/admin.conf
If you're not using jQuery... you need to access one of the event's TouchList
s to get a Touch
object which has pageX/Y
clientX/Y
etc.
Here are links to the relevant docs:
I'm using e.targetTouches[0].pageX
in my case.
Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.
I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).
Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.
(Still looking for a better way to do it)
package com.christianfries.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class UNCPathTest {
public static void main(String[] args) throws MalformedURLException, URISyntaxException {
UNCPathTest upt = new UNCPathTest();
upt.testURL("file://server/dir/file.txt"); // Windows UNC Path
upt.testURL("file:///Z:/dir/file.txt"); // Windows drive letter path
upt.testURL("file:///dir/file.txt"); // Unix (absolute) path
}
private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
URL url = new URL(urlString);
System.out.println("URL is: " + url.toString());
URI uri = url.toURI();
System.out.println("URI is: " + uri.toString());
if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
// Hack for UNC Path
uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
}
File file = new File(uri);
System.out.println("File is: " + file.toString());
String parent = file.getParent();
System.out.println("Parent is: " + parent);
System.out.println("____________________________________________________________");
}
}
Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.
CSS
.blank_row
{
height: 10px !important; /* overwrites any other rules */
background-color: #FFFFFF;
}
HTML
<tr class="blank_row">
<td colspan="3"></td>
</tr>
Since I have no idea what your current stylesheet looks like I added the !important
property just in case. If possible, though, you should remove it as one rarely wants to rely on !important
declarations in a stylesheet considering the big possibility that they will mess it up later on.
If you're using C++11 or above, I'd suggest using std::snprintf
over std::strcpy
or std::strncpy
because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:
#include <string>
#include <cstdio>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());
In C++17, you have this alternative:
#include <string>
#include <cstdio>
#include <iterator>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());
Use Ant script and make target deploy.
The deploy target should:
==> No caching + also no out of memory issues after subsequent deploys during testing.
document.getElementById("address_box").value =
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
As mentioned by several others, the Eclipse Window → Preferences... → Java → Installed JREs should point to the JDK you installed, not to the JRE. Only then it can find the ../lib
folder mentioned in the error message.
Even with this, the problem may recur. My way out in Eclipse v4.2 (Juno) is to do a menu Maven → Update project... after which the problem disappears.
I suspect the reason is that some of the Eclipse generated files (.classpath, .project, .preferences) are in Subversion for the project in which I'm having these problems. Thus, an SVN update introduces the problem, and an configuration update from Maven in Eclipse resolves it again.
Real solution: omit Eclipse generated .files from version control, and let the Maven Eclipse plugin handle project configuration. (Additional pointers/suggestions are welcome).
Here is what I use since I am not running > 5.2
function getCurrentOrParentDirectory($type='current')
{
if ($type == 'current') {
$path = dirname(__FILE__);
} else {
$path = dirname(dirname(__FILE__));
}
$position = strrpos($path, '/') + 1;
return substr($path, $position);
}
Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.
Note this function only returns the NAME, slashes have to be added afterwards.
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
server: "localhost\\SQL2K14",_x000D_
database: "SampleDb",_x000D_
user: "sa",_x000D_
password: "sql2014",_x000D_
port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
var conn = new sql.Connection(dbConfig);_x000D_
_x000D_
conn.connect().then(function () {_x000D_
var req = new sql.Request(conn);_x000D_
req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
console.log(recordset);_x000D_
conn.close();_x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
conn.close();_x000D_
}); _x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
});_x000D_
_x000D_
//--> another way_x000D_
//var req = new sql.Request(conn);_x000D_
//conn.connect(function (err) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// return;_x000D_
// }_x000D_
// req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// }_x000D_
// else { _x000D_
// console.log(recordset);_x000D_
// }_x000D_
// conn.close();_x000D_
// });_x000D_
//});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
A small variation but nothing new infact. It's really missing a feature...
select info->>'name' from rabbits
where '"carrots"' = ANY (ARRAY(
select * from json_array_elements(info->'food'))::text[]);
I know there are several answers, but i think the best and most simple is using a state "To change" is the state purpose.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
style: {
backgroundColor: "white"
}
};
}
onPress = function() {
this.setState({style: {backgroundColor: "red"}});
}
render() {
return (
...
<View style={this.state.style}></View>
...
)
}
}
Instead of Tick
event, use Elapsed
event.
timer.Elapsed += new EventHandler(TimerEventProcessor);
and change the signiture of TimerEventProcessor method;
private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
label1.Text = _counter.ToString();
_counter += 1;
}
In my case, the issue was that I was running two other SQL Server instances which were (or at least one of them was) causing a conflict.
The solution was simply to stop the other SQL Server instance and its accompanying SQL Server Agent.
While I'm at it, I'll also recommend making sure Named Pipes
is enabled in your server's protocol settings
Citing the quote from Robertiano above again - because this is by far the most versatile and localization adaptive version. It deserves a full post!
Another option:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.
I faced with the same issue. I just added credentials config:
aws_access_key_id = your_aws_access_key_id
aws_secret_access_key = your_aws_secret_access_key
into "~/.aws/credentials" + restart terminal for default profile.
In the case of multi profiles --profile arg needs to be added:
aws s3 sync ./localDir s3://bucketName --profile=${PROFILE_NAME}
where PROFILE_NAME:
.bash_profile ( or .bashrc) -> export PROFILE_NAME="yourProfileName"
More info about how to config credentials and multi profiles can be found here
string cat = "cat";
string human = "human";
cout << cat.compare(human) << endl;
This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.
I find the return value described in cplusplus.com is more accurate which are-:
0 : They compare equal
<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.
negative value if
*this
appears before the character sequence specified by the arguments, in lexicographical orderzero if both character sequences compare equivalent
positive value if
*this
appears after the character sequence specified by the arguments, in lexicographical order
` Please include either of these:
`#include<sstream>`
using std::istringstream;
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:
export DJANGO_SETTINGS_MODULE=mysite.settings
Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name>
In my specific case I ran these two and everything worked out:
export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal
Edit
I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings
to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
Execute the following query in MYSQL Workbench
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
Where root
as your user
localhost
as your URL
and password
as your password
Then run this query to refresh privileges:
flush privileges;
Try connecting using node after you do so.
If that doesn't work, try it without @'localhost'
part.
You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
you could use awk. like this...
cat <yourFile> | awk '/word1/ && /word2/'
Order is not important. So if you have a file and...
a file named , file1 contains:
word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2
then,
/tmp$ cat file1| awk '/word1/ && /word2/'
will result in,
word1 is in this file as well as word2
word2 is in this file as well as word1
yes, awk is slower.
Node manages dependencies ie; third party code using package.json so that 3rd party modules names and versions can be kept stable for all installs of the project. This also helps keep the file be light-weight as only actual program code is present in the code repository. Whenever repository is cloned, for it to work(as 3rd party modules may be used in the code), you would need to install all dependencies.
Use npm install
on CMD within root of the project structure to complete installing all dependencies. This should resolve all dependencies issues if dependencies get properly installed.
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);
What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:
var newUL = $('<ul><li>test</li></ul>');
$(this).append(newUL);
// Later ...
newUL.remove();
If you want upload big size image or data in database. Just change the data type to 'BIG BLOB'
.
This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.
When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.
As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.
Caching example:
102 [C:\Users\leeholm]
>> $r1 = [Console]::Out
103 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
105 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
Scaffold(
backgroundColor: Constants.defaulBackground,
body: new Container(
child: Center(yourtext)
)
)
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
Maybe this is an XY problem, and what you are really trying to do is to highlight occurrences of words as they appear in your shell. If so, you may be able to use your terminal emulator for this. For instance, in Konsole, start Find (ctrl+shift+F) and type your word. The word will then be highlighted whenever it occurs in new or existing output until you cancel the function.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
You can just use following git command which can revert back all the uncommitted changes made in your repository:
git checkout .
Example:
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: application/controllers/Drivers.php
modified: application/views/drivers/add.php
modified: application/views/drivers/load_driver_info.php
modified: uploads/drivers/drivers.xlsx
no changes added to commit (use "git add" and/or "git commit -a")
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git checkout .
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean
Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.
for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below
System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Instead of using a ServletContextListener, use a HttpSessionListener
.
In the sessionCreated()
method, you can set the session timeout programmatically:
public class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event){
event.getSession().setMaxInactiveInterval(15 * 60); // in seconds
}
public void sessionDestroyed(HttpSessionEvent event) {}
}
And don't forget to define the listener in the deployment descriptor:
<webapp>
...
<listener>
<listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>
</webapp>
(or since Servlet version 3.0 you can use @WebListener
annotation instead).
Still, I would recommend creating different web.xml files for each application and defining the session timeout there:
<webapp>
...
<session-config>
<session-timeout>15</session-timeout> <!-- in minutes -->
</session-config>
</webapp>
On ubuntu
sudo apt-get install librxtx-java then
add RXTX jars to the project which are in
usr/share/java
If you want to use it in testing/TDD context, I'd say this is a standard way:
from nose.tools import assert_almost_equals
assert_almost_equals(x, y, places=7) #default is 7
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
I use the following code which seems to be working fine:
function _bot_detected() {
return (
isset($_SERVER['HTTP_USER_AGENT'])
&& preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
);
}
update 16-06-2017 https://support.google.com/webmasters/answer/1061943?hl=en
added mediapartners
I tried this code to find out if a customer is logged in or anonymous. I did using the th:if
and th:unless
conditional expressions. Pretty simple way to do it.
<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
<div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
<div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>
This can be done by implementing an inset box shadow. eg:
select.decorated option:hover {
box-shadow: 0 0 10px 100px #1882A8 inset;
}
Here, .decorated
is a class assigned to the select box.
Hope you got the point.
I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.
Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None)
)
Inspired by Roger Pate:
import datetime
def todayAt (hr, min=0, sec=0, micros=0):
now = datetime.datetime.now()
return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)
# Usage demo1:
print todayAt (17), todayAt (17, 15)
# Usage demo2:
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
print "Too Early"
Just do the following change
echo off
cls
echo Would you like to do a backup?
pause
copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
pause
You could use these functions:
sp_help TableName
sp_helptext ProcedureName
I've concluded this is some kind of Visual Studio bug. Perhaps C Johnson is right - perhaps the build process keeps the file locked.
I do have a workaround which works - each time this happens - I change the Target Name of the executable under the Project's properties (right click the project, then Properties\Configuration Properties\General\Target Name).
In this fashion VS creates a new executable and the problem is worked around. Every few times I do this I return to the original name, thus cycling through ~3 names.
If someone will find the reason for this and a solution, please do answer and I may move the answer to yours, as mine is a workaround.
Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.
my_form_post
).request.form
.templates/my-form.html
:
<form method="POST">
<input name="text">
<input type="submit">
</form>
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('my-form.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
return processed_text
This is the Flask documentation about accessing request data.
If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.
Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).
Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").
When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.
Install these 2 packages
<packages>
<package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
<package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>
Helper function
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelToCsv
{
public class ExcelFileHelper
{
public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
{
using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
IExcelDataReader reader = null;
if (excelFilePath.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (excelFilePath.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
if (reader == null)
return false;
var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = false
}
});
var csvContent = string.Empty;
int row_no = 0;
while (row_no < ds.Tables[0].Rows.Count)
{
var arr = new List<string>();
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
}
row_no++;
csvContent += string.Join(",", arr) + "\n";
}
StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
csv.Write(csvContent);
csv.Close();
return true;
}
}
}
}
Usage :
var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);
Just to enhance @adivis12 answer, you don't need to do the if
statement. Put it like this:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)
The previous answers come close, but to meet the actual requirement that the @
symbol stay close, you'd want that to be str.Replace("@", "@" + System.Environment.NewLine)
. That will keep the @
symbol and add the appropriate newline character(s) for the current platform.
This comes very late, but there is a class in the JDK just for the purpose of having a sorted list. It is named (somewhat out of order with the other Sorted*
interfaces) "java.util.PriorityQueue
". It can sort either Comparable<?>
s or using a Comparator
.
The difference with a List
sorted using Collections.sort(...)
is that this will maintain a partial order at all times, with O(log(n)) insertion performance, by using a heap data structure, whereas inserting in a sorted ArrayList
will be O(n) (i.e., using binary search and move).
However, unlike a List
, PriorityQueue
does not support indexed access (get(5)
), the only way to access items in a heap is to take them out, one at a time (thus the name PriorityQueue
).
Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.
Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:
As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the
CreateThread
function will not setup the stack correctly for the C runtime library. You should use_beginthreadex
instead, which is (almost) completely compatible withCreateThread
.
The best thing I can currently think of (within the list of "simple" tools) is Ghostscript (current version is v.8.71) and the PostScript utility program ps2ascii.ps
. Ghostscript ships it in its lib
subdirectory. Try this (on Windows):
gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dCOMPLEX ^
-f ps2ascii.ps ^
-dFirstPage=3 ^
-dLastPage=7 ^
input.pdf ^
-dQUIET ^
-c quit
This command processes pages 3-7 of input.pdf
. Read the comments in the ps2ascii.ps
file itself to see what the "weird" numbers and additional infos mean (they indicate strings, positions, widths, colors, pictures, rectangles, fonts and page breaks...). To get a "simple" text output, replace the -dCOMPLEX
part by -dSIMPLE
.
There is a problem with pylint, which I do not completely understood yet.
You can just import OpenCV with:
from cv2 import cv2
As an alternative (if you don't want to use background), you can easily do it by making a view as follows:
<View
android:layout_width="2dp"
android:layout_height="match_parent"
android:background="#000000" />
For having a right border only, place this after the layout (where you want to have the border):
<View
android:layout_width="2dp"
android:layout_height="match_parent"
android:background="#000000" />
For having a left border only, place this before the layout (where you want to have the border):
Worked for me...Hope its of some help....
It depends on how Jenkins has been started.
As a service: sudo service jenkins restart
, sudo /etc/init.d/jenkins restart
, etc.
As a web application in a Tomcat installation: restart your Tomcat, or just restart the application in Tomcat. Go to http://<tomcat-server>:8080/manager/list
or after authentication hit http://<tomcat-server>:8080/manager/stop?path=/myapp
+ http://<tomcat-server>:8080/manager/start?path=/myapp
.
Launched with just java -jar
: kill it (kill -9 <pid>
), and relaunch it.
Launched with java -jar
, but from a supervisor: supervisorctl restart jenkins
On Ubuntu, You can follow these steps to resolve the issue:
$HOME/.mozilla
, if it doesn't exist alreadyCreate a symlink to libnpjp2.so inside this directory using this command:
ln -s $JAVA_HOME/jre/lib/i386/libnpjp2.so $MOZILLA_HOME/plugins
-or-
ln -s $JAVA_HOME/jre/lib/amd64/libnpjp2.so $MOZILLA_HOME/plugins
depending on whether you're using a 32 or 64 bit JVM installation. Moreover, $JAVA_HOME is the location of your JVM installation.
More detailed instructions can be found here.
This solution helped me to skip the number of lines specified by the linetostart
variable.
You get the index (int) and the line (string) if you want to keep track of those too.
In your case, you substitute linetostart with 18, or assign 18 to linetostart variable.
f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
#Your code
How about this,
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
}
});
Ref: http://erlend.oftedal.no/blog/?blogid=118
To pass CSRF
as parameter,
$.ajax({
type: "POST",
url: "file",
data: { CSRF: getCSRFTokenValue()}
})
.done(function( msg ) {
alert( "Data: " + msg );
});
In my case, the problem was that the new library (gradle dependency) that I had added was relying on some other dependencies and two of those underlying dependencies were conflicting/clashing with some dependencies of other libraries/dependencies in my build script. Specifically, I added Apache Commons Validator
(for email validation), and two of its dependencies (Apache Commons Logging
and Apache Commons Collections
) were conflicting with those used by Robolectric (because different versions of same libraries were present in my build path). So I excluded those conflicting versions of dependencies (modules
) when adding the new dependency (the Validator
):
compile ('commons-validator:commons-validator:1.4.1') {
exclude module: 'commons-logging'
exclude module: 'commons-collections'
}
You can see the dependencies of your gradle module(s) (you might have only one module in your project) using the following gradle command (I use the gradle wrapper that gets created for you if you have created your project in Android Studio/Intellij Idea). Run this command in your project's root directory:
./gradlew :YOUR-MODULE-NAME:dependencies
After adding those exclude
directives and retrying to run, I got a duplicate file
error for NOTICE.txt
that is used by some apache commons libraries like Logging and Collections. I had to exclude that text file when packaging. In my build.gradle, I added:
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/notice.txt'
exclude 'META-INF/NOTICE.txt'
}
It turned out that the new library (the Validator
) can work with slightly older versions of its dependencies/modules (which are already imported into my build path by another library (Robolectric)). This was the case with this specific library, but other libraries might be using the latest API of the underlying dependencies (in which case you have to try to see if the other libraries that rely on the conflicting module/dependency are able to work with the newer version (by excluding the older version of the module/dependecy under those libraries's entries)).
I made some tests to compare database performance between UTF-8 and UTF-16 in MySQL.
You can use attribute selectors but they won't work in IE6 like meder said, there are javascript workarounds to that tho. Check Selectivizr
More detailed into on attribute selectors: http://www.css3.info/preview/attribute-selectors/
/* turns all input fields that have a name that starts with "go" red */
input[name^="go"] { color: red }
:goto 21490
will take you to the 21490th byte in the buffer.
From the answers it appears that there is no official API support for this (as in a direct and explicit check). Many of the answers say to use stat, however they are not strict. We can't assume for example that any error thrown by stat means that something doesn't exist.
Lets say we try it with something that doesn't exist:
$ node -e 'require("fs").stat("god",err=>console.log(err))'
{ Error: ENOENT: no such file or directory, stat 'god' errno: -2, code: 'ENOENT', syscall: 'stat', path: 'god' }
Lets try it with something that exists but that we don't have access to:
$ mkdir -p fsm/appendage && sudo chmod 0 fsm
$ node -e 'require("fs").stat("fsm/appendage",err=>console.log(err))'
{ Error: EACCES: permission denied, stat 'access/access' errno: -13, code: 'EACCES', syscall: 'stat', path: 'fsm/appendage' }
At the very least you'll want:
let dir_exists = async path => {
let stat;
try {
stat = await (new Promise(
(resolve, reject) => require('fs').stat(path,
(err, result) => err ? reject(err) : resolve(result))
));
}
catch(e) {
if(e.code === 'ENOENT') return false;
throw e;
}
if(!stat.isDirectory())
throw new Error('Not a directory.');
return true;
};
The question is not clear on if you actually want it to be syncronous or if you only want it to be written as though it is syncronous. This example uses await/async so that it is only written syncronously but runs asyncronously.
This means you have to call it as such at the top level:
(async () => {
try {
console.log(await dir_exists('god'));
console.log(await dir_exists('fsm/appendage'));
}
catch(e) {
console.log(e);
}
})();
An alternative is using .then and .catch on the promise returned from the async call if you need it further down.
If you want to check if something exists then it's a good practice to also ensure it's the right type of thing such as a directory or file. This is included in the example. If it's not allowed to be a symlink you must use lstat instead of stat as stat will automatically traverse links.
You can replace all of the async to sync code in here and use statSync instead. However expect that once async and await become universally supports the Sync calls will become redundant eventually to be depreciated (otherwise you would have to define them everywhere and up the chain just like with async making it really pointless).
I create this program:
import pygame, sys, time, random, easygui
skier_images = ["skier_down.png", "skier_right1.png",
"skier_right2.png", "skier_left2.png",
"skier_left1.png"]
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0
def turn(self, direction):
self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed
def move(self,speed):
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self,image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
def scroll(self, t_ptr):
self.rect.centery = self.location[1] - t_ptr
def create_map(start, end):
obstacles = pygame.sprite.Group()
gates = pygame.sprite.Group()
locations = []
for i in range(10):
row = random.randint(start, end)
col = random.randint(0, 9)
location = [col * 64 + 20, row * 64 + 20]
if not (location in locations) :
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles
def animate():
screen.fill([255,255,255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10,10])
pygame.display.flip()
def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0: obstacles.add(ob)
for ob in map1: obstacles.add(ob)
return obstacles
pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)
a = True
while a:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1]
if map_position >= 640 and activeMap == 0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1] - 1280
map_position = map_position - 1280
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0, map1)
for obstacle in obstacles:
obstacle.scroll(map_position)
hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit[0].type == "tree" and not hit[0].passed:
skier.image = pygame.image.load("skier_crash.png")
easygui.msgbox(msg="OOPS!!!")
choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
if choice == "Yes":
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
elif choice == "No":
a = False
quit()
elif hit[0].type == "flag" and not hit[0].passed:
points += 10
obstacles.remove(hit[0])
score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
animate()
Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit
I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:
test:
( NODE_ENV=test mocha --harmony --reporter spec test )
All I did is go to my project directory from the cmd (command prompt) I typed java -version.it told me what version it was looking for. so I Installed that version and I changed the path to were the jdk of that version was located .
If you are trying to bind is a Model class, you can add a new readonly property to it like:
public string FormattedPercentage
{
get
{
If(this.Percentage < 50)
return "0 %";
else
return string.Format("{0} %", this.Percentage)
}
}
Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself
Before initializing map check for is the map is already initiated or not
var container = L.DomUtil.get('map');
if(container != null){
container._leaflet_id = null;
}
as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.
Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.
def convert(o):
if isinstance(o, np.generic): return o.item()
raise TypeError
json.dumps({'value': numpy.int64(42)}, default=convert)
Referencing Qwerty's answer, if the destRow isnot null, sheet.shiftRows() will change the destRow's reference to the next row; so we should always create a new row:
if (destRow != null) {
sheet.shiftRows(destination, sheet.getLastRowNum(), 1);
}
destRow = sheet.createRow(destination);
I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)
ALLOWED_HOSTS = ['*']
then ran the server with:
python manage.py runserver 0.0.0.0:9595
Also ensure that the firewall allows connections to that port
A struct (without a typedef) often needs to (or should) be with the keyword struct when used.
struct A; // forward declaration
void function( struct A *a ); // using the 'incomplete' type only as pointer
If you typedef your struct you can leave out the struct keyword.
typedef struct A A; // forward declaration *and* typedef
void function( A *a );
Note that it is legal to reuse the struct name
Try changing the forward declaration to this in your code:
typedef struct context context;
It might be more readable to do add a suffix to indicate struct name and type name:
typedef struct context_s context_t;
I had this problem when I got the latest on TFS while other projects were open in multiple instances of VS. I already have all the fixes above. Reopening VS fixed the problem.
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
It happens because Build Tools revision 24.4.1 doesn't exist.
The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/
directory.
Don't confuse the Android SDK Tools with SDK Build Tools.
Change in your build.gradle
android {
buildToolsVersion "23.0.2"
// ...
}
You can set this globally for all read.csv/read.*
commands with
options(stringsAsFactors=F)
Then read the file as follows:
my.tab <- read.table( "filename.csv", as.is=T )
The keydown
event will work fine for Escape and has the benefit of allowing you to use keyCode
in all browsers. Also, you need to attach the listener to document
rather than the body.
Update May 2016
keyCode
is now in the process of being deprecated and most modern browsers offer the key
property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key
is now supported by all modern browsers.
document.onkeydown = function(evt) {_x000D_
evt = evt || window.event;_x000D_
var isEscape = false;_x000D_
if ("key" in evt) {_x000D_
isEscape = (evt.key === "Escape" || evt.key === "Esc");_x000D_
} else {_x000D_
isEscape = (evt.keyCode === 27);_x000D_
}_x000D_
if (isEscape) {_x000D_
alert("Escape");_x000D_
}_x000D_
};
_x000D_
Click me then press the Escape key
_x000D_
If you would like to use StoryBoard and wouldnt like to keep typing in runtime attributes, you can easily create an extension to views and make them usable in storyboard.
Step 1. create extension
extension UIView {
@IBInspectable var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable var maskToBound: Bool {
get {
return layer.masksToBounds
}
set {
layer.masksToBounds = newValue
}
}
}
In my case, it was not only necessary add jenkins
user to docker
group, but make that group the primary group of the jenkins
user.
# usermod -g docker jenkins
# usermod -a -G jenkins jenkins
Don't forget to reconnect the jenkins slave node or restart the jenkins server, depend on your case.
You could use negative lookahead, or something like this:
^([^A]|A([^B]|B([^C]|$)|$)|$).*$
Maybe it could be simplified a bit.
As stated in Date and Time Literals:
MySQL recognizes
DATE
values in these formats:
As a string in either
'YYYY-MM-DD'
or'YY-MM-DD'
format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example,'2012-12-31'
,'2012/12/31'
,'2012^12^31'
, and'2012@12@31'
are equivalent.As a string with no delimiters in either
'YYYYMMDD'
or'YYMMDD'
format, provided that the string makes sense as a date. For example,'20070523'
and'070523'
are interpreted as'2007-05-23'
, but'071332'
is illegal (it has nonsensical month and day parts) and becomes'0000-00-00'
.As a number in either
YYYYMMDD
orYYMMDD
format, provided that the number makes sense as a date. For example,19830905
and830905
are interpreted as'1983-09-05'
.
Therefore, the string '08/25/2012'
is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField
together with its altFormat
option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD
format, simply set the dateFormat
option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE()
function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime
object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME()
function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_*
functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME
or TIMESTAMP
column for holding a date value; I recommend you consider using MySQL's DATE
type instead. As explained in The DATE
, DATETIME
, and TIMESTAMP
Types:
The
DATE
type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in'YYYY-MM-DD'
format. The supported range is'1000-01-01'
to'9999-12-31'
.The
DATETIME
type is used for values that contain both date and time parts. MySQL retrieves and displaysDATETIME
values in'YYYY-MM-DD HH:MM:SS'
format. The supported range is'1000-01-01 00:00:00'
to'9999-12-31 23:59:59'
.The
TIMESTAMP
data type is used for values that contain both date and time parts.TIMESTAMP
has a range of'1970-01-01 00:00:01'
UTC to'2038-01-19 03:14:07'
UTC.
Huffman coding generally works okay for this.
What browser are you using?
alert(typeof document.getElementById('myform').onsubmit);
This gives me "function
" in IE7 and FireFox.
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.
The right tool exists, it's SVG <text>
The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too,
filter: progid:DXImageTransform
can be used or IE < 10 but often doesn't work as expected.
To me the best solution remains SVG with a fallback in not-stroked text for older browser:
This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9
Compared to text-shadow
whose supports are:
Chrome 4.0,
FF 3.5,
IE 10,
Safari 4.0,
Opera 9, it results even more compatible.
.stroke {_x000D_
margin: 0;_x000D_
font-family: arial;_x000D_
font-size:70px;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
svg {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
text {_x000D_
fill: black;_x000D_
stroke: red;_x000D_
stroke-width: 3;_x000D_
}
_x000D_
<p class="stroke">_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
<text x="0" y="70">Stroked text</text>_x000D_
</svg>_x000D_
</p>
_x000D_
In Addition you also need to be sure that you have
<context:annotation-config/>
in your SPring configuration xml.
I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0
Update:
just checked my working code where I have @RequestBody
working correctly.
I also have this bean in my config:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
May be it would be nice to see what Log4j
is saying. it usually gives more information and from my experience the @RequestBody
will fail if your request's content type is not Application/JSON
. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.
The most common answer to that is simple: Bundle few apps (busybox?) with your APK (assuming you want to use it within an application). As far as I know, the /data partition is not mounted noexec, and even if you don't want to deploy a fully-fledged APK, you could modify ConnectBot sources to build an APK with a set of command line tools included.
For command line tools, I recommend using crosstool-ng and building a set of statically-linked tools (linked against uClibc). They might be big, but they'll definitely work.
You're looking for
git diff --staged
Depending on your exact situation, there are three useful ways to use git diff
:
git diff [filename]
--staged
does exactly the same thing, use what you like):git diff --cached [filename]
git diff HEAD [filename]
git diff
works recursively on directories, and if no paths are given, it shows all changes.
As stated here: Why use Fragment#setRetainInstance(boolean)?
you can also use fragments method setRetainInstance(true)
like this:
public class MyFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
}
This is an old question, but you can now write using statements without needing to block each one. They will be disposed of in reverse order when the containing block is finished.
using var responseStream = response.GetResponseStream();
using var reader = new StreamReader(responseStream);
using var writer = new StreamWriter(filename);
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%s\n' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%s\n' "word1 word2" "line2" | { read -r first _; printf '%s\n' "$first"; }
second case: you want the first word of each line:
printf '%s\n' "word1 word2" "worda wordb" | while read -r first _; do printf '%s\n' "$first"; done
These work if there are leading spaces:
printf '%s\n' " word1 word2" | { read -r first _; printf '%s\n' "$first"; }
I think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
Sometimes it's easier to think in terms of which fields to exclude.
If the number of fields not being cut (not being retained in the output) is small, it may be easier to use the --complement
flag, e.g. to include all fields 1-20 except not 3, 7, and 12 -- do this:
cut -d, --complement -f3,7,12 <inputfile
Rather than
cut -d, -f-2,4-6,8-11,13-
I did the truncation with new java8 API. I faced up with one strange thing but in general it's truncate...
Instant instant = date.toInstant();
instant = instant.truncatedTo(ChronoUnit.DAYS);
date = Date.from(instant);
Note: all the examples here are using the OpenCV 2.X API.
In OpenCV 3.X, you need to use:
Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);
See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers
For anyone reading this who is using EclipseLink for JPA 2.0, here are the two annotations I had to use to get JPA to persist data, where "MySequenceGenerator" is whatever name you want to give the generator, "myschema" is the name of the schema in your database that contains the sequence object, and "mysequence" is the name of the sequence object in the database.
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="MySequenceGenerator")
@SequenceGenerator(allocationSize=1, schema="myschema", name="MySequenceGenerator", sequenceName = "mysequence")
For those using EclipseLink (and possibly other JPA providers), it is CRITICAL that you set the allocationSize attribute to match the INCREMENT value defined for your sequence in the database. If you don't, you'll get a generic persistence failure, and waste a good deal of time trying to track it down, like I did. Here is the reference page that helped me overcome this challenge:
http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey#Using_Sequence_Objects
Also, to give context, here is what we're using:
Java 7 Glassfish 3.1 PostgreSQL 9.1 PrimeFaces 3.2/JSF 2.1
Also, for laziness' sake, I built this in Netbeans with the wizards for generating Entities from DB, Controllers from Entities, and JSF from Entities, and the wizards (obviously) do not know how to deal with sequence-based ID columns, so you'll have to manually add these annotations.
You can also use Projections:
ProjectionList projection = Projections.projectionList();
projection.add(Projections.rowCount());
criteria.setProjection(projection);
Long totalRows = (Long) criteria.list().get(0);
If an immutable map fits your needs then there is a library by google called guava (see also guava questions)
Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.
ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.
This is a simple way to do it!
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script>
function notificationme(){
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"preventDuplicates": true,
"onclick": null,
"showDuration": "100",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "show",
"hideMethod": "hide"
};
toastr.info('MY MESSAGE!');
}
</script>
Used to this
input[type="radio"]{
vertical-align:top;
}
p{
font-size:10px;line-height: 18px;
}
existing_list = range(0, 1001)
filtered_list = [i for i in existing_list if i % 10 == 0]
((KidsStoryDashboard)getActivity()).values(title_txt,bannerImgUrl);
public void values(String title_txts, String bannerImgUrl) {
if (!title_txts.isEmpty()) {
//Do something to set text
}
imageLoader.displayImage(bannerImgUrl, htab_header_image, doption);
}
I had the same problem on localhost.
Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files
works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
and enter your password (if you have one).
Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>
. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
With my mercurial background I was going to use:
git log --patch -1 $ID > $file
But I am considering using git format-patch -1 $ID
now.
Given this example url:
http://www.example.com/some-dir/yourpage.php?q=bogus&n=10
$_SERVER['REQUEST_URI']
will give you:
/some-dir/yourpage.php?q=bogus&n=10
Whereas $_GET['q']
will give you:
bogus
In other words, $_SERVER['REQUEST_URI']
will hold the full request path including the querystring. And $_GET['q']
will give you the value of parameter q
in the querystring.
{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
console.dir()
will do what you need. It will give you a hierarchical structure of the data.
success:function(data){
console.dir(data);
}
like so
> Object
> input_data: Object
price-row_122: " 35.1 "
quantity-row_122: "1"
success: true
I don't think you need console.log(JSON.stringify(data))
.
To get the data you can do this without stringify
:
console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "
Note
The value from input_data
Object will be typeof "1"
: String
, but you can convert to number(Int or Float)
using ParseInt or ParseFloat, like so:
typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
parseFloat(data.input_data['price-row_122'], 10) // 35.1
This worked for me:
COPY (SELECT * FROM table)
TO E'C:\\Program Files (x86)\\PostgreSQL\\8.4\\data\\try.csv';
In my case the problem was with the writing permission to a special folder (though I work as administrator), after changing the path to the original data folder under PostgreSQL I had success.
The other answers are correct: You don't have a default value. However, you have another problem in your logic:
You read the same file twice. After reading it once, the cursor is at the end of the file. To solve this, you can do two things: Either open/close the file upon each function call:
def temp_sky(lreq, breq):
with open("/home/path/to/file",'r') as tfile:
# do your stuff
This hase the disadvantage of having to open the file each time. The better way would be:
tfile.seek(0)
You do this after your for line in tfile:
loop. It resets the cursor to the beginning to the next call will start from there again.
Using start
works fine, unless you are using a scripting language. Fortunately, there's a way out for Python - just use pythonw.exe
instead of python.exe
:
:: Title not needed:
start pythonw.exe application.py
In case you need quotes, do this:
:: Title needed
start "Great Python App" pythonw.exe "C:\Program Files\Vendor\App\application.py"
The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:
v2 = v1 ?? default(int);
Any Nullable<T>
is implicitly convertible to its T
, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ??
is just syntax sugar for the ternary operator:
v2 = v1 == null ? default(int) : v1;
...which is in turn syntax sugar for an if/else:
if(v1==null)
v2 = default(int);
else
v2 = v1;
Also, as of .NET 4.0, Nullable<T>
has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:
v2 = v1.GetValueOrDefault();
With Bootstrap 4 Class:
text-nowrap
Ref: https://getbootstrap.com/docs/4.0/utilities/text/#text-wrapping-and-overflow
In ggplot2 you can do smooths in a number of ways, for example:
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
geom_smooth(method = "gam", formula = y ~ poly(x, 2))
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
geom_smooth(method = "loess", span = 0.3, se = FALSE)
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com");
could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
It can be caused by a classpath contamination. Check that you /WEB-INF/lib
doesn't contain something like jsp-api-*.jar
.
Common sense works here: os
is a module, and os.path
is a module, too. So just import the module you want to use:
If you want to use functionalities in the os
module, then import os
.
If you want to use functionalities in the os.path
module, then import os.path
.
If you want to use functionalities in both modules, then import both modules:
import os
import os.path
For reference:
Lib/idlelib/rpc.py uses os
and imports os
.
Lib/idlelib/idle.py uses os.path
and imports os.path
.
Lib/ensurepip/init.py uses both and imports both.
While you should ideally highlight the code which is causing an error and post that within your question, the error is because you are trying to get the inner HTML of the 'status' element:
var idPost=document.getElementById("status").innerHTML;
However the 'status' element does not exist within your HTML - either add the necessary element or change the ID you are trying to locate to point to a valid element.
This works - https://stackoverflow.com/a/5437720/10219008.....but if you run into an issue 'Error Code: 1265. Data truncated for column 'id' at row 1'...Then run the following. Adding ignore on the update query.
SET @count = 0;
set sql_mode = 'STRICT_ALL_TABLES';
UPDATE IGNORE web_keyword SET id = @count := (@count+1);
Like it's already mentioned, I would highly recommend using regular expression (in System.Text) to get this kind of job done.
In combo with a solid tool like RegexBuddy, you are looking at handling any complex text record parsing situations, as well as getting results quickly. The tool makes it real easy.
Hope that helps.
They can also provide a kind of naming collision protection for plugin data. For example, the new Change Data Capture feature in SQL Server 2008 puts the tables it uses in a separate cdc schema. This way, they don't have to worry about a naming conflict between a CDC table and a real table used in the database, and for that matter can deliberately shadow the names of the real tables.
Credits to https://www.dotnetperls.com/property.
private setters are same as read-only fields. They can only be set in constructor. If you try to set from outside you get compile time error.
public class MyClass
{
public MyClass()
{
// Set the private property.
this.Name = "Sample Name from Inside";
}
public MyClass(string name)
{
// Set the private property.
this.Name = name;
}
string _name;
public string Name
{
get
{
return this._name;
}
private set
{
// Can only be called in this class.
this._name = value;
}
}
}
class Program
{
static void Main()
{
MyClass mc = new MyClass();
Console.WriteLine(mc.name);
MyClass mc2 = new MyClass("Sample Name from Outside");
Console.WriteLine(mc2.name);
}
}
Please see below screen shot when I tried to set it from outside of the class.
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>
Are you targeting the android.R or the one in your own project?
Are you sure your own R.java file is generated? Mistakes in your xml views could cause the R.java not to be generated. Go through your view files and make sure all the xml is right!
You could try this:
string input = "lala.bla";
output = input.Split('.').Last();
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
In your project .plist
file in add this permission :
<key>NSAppTransportSecurity</key>
<dict>
<!--Connect to anything (this is probably BAD)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Well, PHP json_encode() returns a string.
You can use parseFloat() or parseInt() in the js code though:
parseFloat('122.5'); // returns 122.5
parseInt('22'); // returns 22
parseInt('22.5'); // returns 22
This XPath is specific to the code snippet you've provided. To select <child>
with id as #grand
you can write //child[@id='#grand']
.
To get age //child[@id='#grand']/@age
Hope this helps
The API changed again. It can be now found in:
tf.config.experimental.set_memory_growth(
device,
enable
)
Aliases:
References:
See also: Tensorflow - Use a GPU: https://www.tensorflow.org/guide/gpu
for Tensorflow 2.0 Alpha see: this answer
Try this:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var deferred= $q.defer();
this.user = {
access: false
};
try
{
this.isAuthenticated = function() {
this.user = {
first_name: 'First',
last_name: 'Last',
email: '[email protected]',
access: 'institution'
};
deferred.resolve();
};
}
catch
{
deferred.reject();
}
return deferred.promise;
]);
You can set Default attribute in Model also>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
You can find the details in these links
1.) How to set a default attribute value for a Laravel / Eloquent model?
You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
Yes, but not with that version of the constructor. You can do this:
>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}
There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."
This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/
(or with table-layout: fixed
for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)
This won't work in IE7.
#horizontal-style {
display: table;
width: 100%;
/*table-layout: fixed;*/
}
#horizontal-style li {
display: table-cell;
}
#horizontal-style a {
display: block;
border: 1px solid red;
text-align: center;
margin: 0 5px;
background: #999;
}
Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/
Missing space between elif
and [
rest your program is correct. you need to correct it an check it out. here is fixed program:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
useful link related to this bash if else statement
Please refer here https://code.google.com/p/selenium/issues/detail?id=6756 In crux
Please open the system display settings and ensure that font size is set to 100% It worked surprisingly
(source: jfrog.com)
or
Just use Maven repository servers like Sonatype Nexus http://www.sonatype.org/nexus/ or JFrog Artifactory https://www.jfrog.com/artifactory/.
After one developer builds a project, build by next developers or Jenkins CI will not require Internet access.
Maven repository server also can have proxies configured to access Maven Central (or more needed public repositories), and they can have cynch'ed list of artifacts in remote repositories.
@Entity
class Employee {
@OneToOne(orphanRemoval=true)
private Address address;
}
See here.
use this function http://www.codingforums.com/showthread.php?t=71882
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = @opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
and call the function like that
getDirectory( "." );
// Get the current directory
getDirectory( "./files/includes" );
// Get contents of the "files/includes" folder
Just a piece of advice. Instead of writing
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
as suggested above, write a:
for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
cout << *it << '\n';
}
to use iterators. If you have C++11
support, you can declare i
as auto i=Main.begin()
(just a handy shortcut though)
This avoids the nasty one-position-out-of-bound error caused by leaving out a -1
unintentionally.
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
On Github, <p>
and <br/>
solves the problem.
<p>
I want to this to appear in a new line. Introduces extra line above
or
<br/>
another way
You can use Decimal format if you want to format number into a string, for example:
String a = "123455";
System.out.println(new
DecimalFormat(".0").format(Float.valueOf(a)));
The output of this code will be:
123455.0
You can add more zeros to the decimal format, depends on the output that you want.
Add this line to dependencies in build.gradle
:
dependencies {
compile 'com.android.support:appcompat-v7:18.0.+'
}
First give or check permissions like
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
If these two permissions are OK, then check your output streams are in correct format.
Example:
FileOutputStream fos=new FileOutputStream(Environment.getExternalStorageDirectory()+"/rahul1.jpg");
In normal situations the following should work:
var can = CanvasElement.getContext('2d'); //get context
var lineHeight = /[0-9]+(?=pt|px)/.exec(can.font); //get height from font variable
/// Determine the number of digits for a 64 bit integer.
/// - Uses at most 5 comparisons.
/// - (cX) 2014 [email protected]
/// - \see http://stackoverflow.com/questions/1489830/#27670035
/** #d == Number length vs Number of comparisons == #c
\code
#d | #c #d | #c #d | #c #d | #c
---+--- ---+--- ---+--- ---+---
20 | 5 15 | 5 10 | 5 5 | 5
19 | 5 14 | 5 9 | 5 4 | 5
18 | 4 13 | 4 8 | 4 3 | 4
17 | 4 12 | 4 7 | 4 2 | 4
16 | 4 11 | 4 6 | 4 1 | 4
\endcode
*/
unsigned NumDigits64bs(uint64_t x) {
return // Num-># Digits->[0-9] 64->bits bs->Binary Search
( x >= 10000000000ul // [11-20] [1-10]
?
( x >= 1000000000000000ul // [16-20] [11-15]
? // [16-20]
( x >= 100000000000000000ul // [18-20] [16-17]
? // [18-20]
( x >= 1000000000000000000ul // [19-20] [18]
? // [19-20]
( x >= 10000000000000000000ul // [20] [19]
? 20
: 19
)
: 18
)
: // [16-17]
( x >= 10000000000000000ul // [17] [16]
? 17
: 16
)
)
: // [11-15]
( x >= 1000000000000ul // [13-15] [11-12]
? // [13-15]
( x >= 10000000000000ul // [14-15] [13]
? // [14-15]
( x >= 100000000000000ul // [15] [14]
? 15
: 14
)
: 13
)
: // [11-12]
( x >= 100000000000ul // [12] [11]
? 12
: 11
)
)
)
: // [1-10]
( x >= 100000ul // [6-10] [1-5]
? // [6-10]
( x >= 10000000ul // [8-10] [6-7]
? // [8-10]
( x >= 100000000ul // [9-10] [8]
? // [9-10]
( x >= 1000000000ul // [10] [9]
? 10
: 9
)
: 8
)
: // [6-7]
( x >= 1000000ul // [7] [6]
? 7
: 6
)
)
: // [1-5]
( x >= 100ul // [3-5] [1-2]
? // [3-5]
( x >= 1000ul // [4-5] [3]
? // [4-5]
( x >= 10000ul // [5] [4]
? 5
: 4
)
: 3
)
: // [1-2]
( x >= 10ul // [2] [1]
? 2
: 1
)
)
)
);
}
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html
You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html
Your timeit
is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit
You can use below code on onSuccess(LoginResult loginResult)
loginResult.getAccessToken().getUserId();
It works when you set the display value of your menu items from display: inline-block;
to display: block;
See your updated code here:
#menu {
clear: both;
height: auto;
font-family: Arial, Tahoma, Verdana;
font-size: 1em;
/*padding:10px;*/
margin: 5px;
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
justify-content: center;
-webkit-box-align: center;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;fffff
font-style: normal;
font-weight: 400px;
}
#menu a:link {
display: block; //here you need to change the display property
width: 100px;
height: 50px;
padding: 5px;
background-color: yellow;
/*border: 1px solid #cccccc;*/
margin: 5px;
display: flex;
flex-grow: 1;
align-items: center;
text-align: center;
justify-content: center;
font-weight: bold;
color: #1689D6;
font-size: 85%;
}
#menu a:visited {
//no display property here
width: 100px;
height: 50px;
padding: 5px;
background-color: yellow;
/*border: 1px solid #cccccc;*/
margin: 5px;
display: flex;
flex-grow: 1;
align-items: center;
text-align: center;
justify-content: center;
font-weight: bold;
color: #1689D6;
font-size: 85%;
}
#menu a:hover {
//no display property here
color: #fff;
width: 100px;
height: 50px;
padding: 5px;
background-color: red;
/*border: 1px solid #cccccc;*/
margin: 5px;
display: flex;
flex-grow: 1;
align-items: center;
text-align: center;
justify-content: center;
font-weight: bold;
font-size: 85%;
}
#menu a:active {
//no display property here
color: #fff;
width: 100px;
height: 50px;
padding-top: 5px;
padding-right: 5px;
padding-left: 5px;
padding-bottom: 5px;
background-color: red;
/*border: 1px solid #cccccc;*/
margin: 5px;
display: flex;
flex-grow: 1;
align-items: center;
text-align: center;
justify-content: center;
font-style: normal;
font-weight: bold;
font-size: 85%;
}
If you read the bootstrap 4 documentation, Color schemes, it will answer your questions.
This is a improve code from @MiFi. This one order in abs but not excluding the negative values.
def top_correlation (df,n):
corr_matrix = df.corr()
correlation = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
.stack()
.sort_values(ascending=False))
correlation = pd.DataFrame(correlation).reset_index()
correlation.columns=["Variable_1","Variable_2","Correlacion"]
correlation = correlation.reindex(correlation.Correlacion.abs().sort_values(ascending=False).index).reset_index().drop(["index"],axis=1)
return correlation.head(n)
top_correlation(ANYDATA,10)
These two schools are not really excluding.
Here is the scenario where you simply have to use
Task.Run(() => AsyncOperation()).Wait();
or something like
AsyncContext.Run(AsyncOperation);
I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.
The library I need is async as it is expected to run async.
The only option. Run it as a normal sync call.
I am just saying to each its own.
Another thing to try is to re-install ca-certificates
as detailed here.
# yum reinstall ca-certificates
...
# update-ca-trust force-enable
# update-ca-trust extract
And another thing to try is to explicitly allow the one site's certificate in question as described here (especially if the one site is your own server and you already have the .pem in reach).
# cp /your/site.pem /etc/pki/ca-trust/source/anchors/
# update-ca-trust extract
I was running into this exact SO error after upgrading to PHP 5.6 on CentOS 6 trying to access the server itself which has a cheapsslsecurity certificate which maybe it needed to be updated, but instead I installed a letsencrypt certificate and with these two steps above it did the trick. I don't know why the second step was necessary.
Useful Commands
View openssl version:
# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
View PHP cli ssl current settings:
# php -i | grep ssl
openssl
Openssl default config => /etc/pki/tls/openssl.cnf
openssl.cafile => no value => no value
openssl.capath => no value => no value
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10
. The result of the query will be a List
of array of Object
. The first element in each array is the value of i.foo
and the second element is the value i.bar
. See the relevant section of JPQL reference.
Use this Layout in your xml file
<LinearLayout
android:id="@+id/contacts_type"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</LinearLayout>
Define your layout in .class file
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);
Now if you want to display this layout just write
linearLayout.setVisibility(View.VISIBLE);
and if you want to hide layout just write
linearLayout.setVisibility(View.INVISIBLE);
Following is a summarization and curation from many different sources on this topic including code example and quotes from selected blog posts. The complete list of best practices can be found here
TL;DR: Handling async errors in callback style is probably the fastest way to hell (a.k.a the pyramid of doom). The best gift you can give to your code is using instead a reputable promise library which provides much compact and familiar code syntax like try-catch
Otherwise: Node.JS callback style, function(err, response), is a promising way to un-maintainable code due to the mix of error handling with casual code, excessive nesting and awkward coding patterns
Code example - good
doWork()
.then(doWork)
.then(doError)
.then(doWork)
.catch(errorHandler)
.then(verify);
code example anti pattern – callback style error handling
getData(someParameter, function(err, result){
if(err != null)
//do something like calling the given callback function and pass the error
getMoreData(a, function(err, result){
if(err != null)
//do something like calling the given callback function and pass the error
getMoreData(b, function(c){
getMoreData(d, function(e){
...
});
});
});
});
});
Blog quote: "We have a problem with promises" (From the blog pouchdb, ranked 11 for the keywords "Node Promises")
"…And in fact, callbacks do something even more sinister: they deprive us of the stack, which is something we usually take for granted in programming languages. Writing code without a stack is a lot like driving a car without a brake pedal: you don’t realize how badly you need it, until you reach for it and it’s not there. The whole point of promises is to give us back the language fundamentals we lost when we went async: return, throw, and the stack. But you have to know how to use promises correctly in order to take advantage of them."
TL;DR: It pretty common to see code that throws errors as string or as a custom type – this complicates the error handling logic and the interoperability between modules. Whether you reject a promise, throw exception or emit error – using Node.JS built-in Error object increases uniformity and prevents loss of error information
Otherwise: When executing some module, being uncertain which type of errors come in return – makes it much harder to reason about the coming exception and handle it. Even worth, using custom types to describe errors might lead to loss of critical error information like the stack trace!
Code example - doing it right
//throwing an Error from typical function, whether sync or async
if(!productToAdd)
throw new Error("How can I add new product when no value provided?");
//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
//'throwing' an Error from a Promise
return new promise(function (resolve, reject) {
DAL.getProduct(productToAdd.id).then((existingProduct) =>{
if(existingProduct != null)
return reject(new Error("Why fooling us and trying to add an existing product?"));
code example anti pattern
//throwing a String lacks any stack trace information and other important properties
if(!productToAdd)
throw ("How can I add new product when no value provided?");
Blog quote: "A string is not an error" (From the blog devthought, ranked 6 for the keywords “Node.JS error object”)
"…passing a string instead of an error results in reduced interoperability between modules. It breaks contracts with APIs that might be performing instanceof Error checks, or that want to know more about the error. Error objects, as we’ll see, have very interesting properties in modern JavaScript engines besides holding the message passed to the constructor.."
TL;DR: Operations errors (e.g. API received an invalid input) refer to known cases where the error impact is fully understood and can be handled thoughtfully. On the other hand, programmer error (e.g. trying to read undefined variable) refers to unknown code failures that dictate to gracefully restart the application
Otherwise: You may always restart the application when an error appear, but why letting ~5000 online users down because of a minor and predicted error (operational error)? the opposite is also not ideal – keeping the application up when unknown issue (programmer error) occurred might lead unpredicted behavior. Differentiating the two allows acting tactfully and applying a balanced approach based on the given context
Code example - doing it right
//throwing an Error from typical function, whether sync or async
if(!productToAdd)
throw new Error("How can I add new product when no value provided?");
//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
//'throwing' an Error from a Promise
return new promise(function (resolve, reject) {
DAL.getProduct(productToAdd.id).then((existingProduct) =>{
if(existingProduct != null)
return reject(new Error("Why fooling us and trying to add an existing product?"));
code example - marking an error as operational (trusted)
//marking an error object as operational
var myError = new Error("How can I add new product when no value provided?");
myError.isOperational = true;
//or if you're using some centralized error factory (see other examples at the bullet "Use only the built-in Error object")
function appError(commonType, description, isOperational) {
Error.call(this);
Error.captureStackTrace(this);
this.commonType = commonType;
this.description = description;
this.isOperational = isOperational;
};
throw new appError(errorManagement.commonErrors.InvalidInput, "Describe here what happened", true);
//error handling code within middleware
process.on('uncaughtException', function(error) {
if(!error.isOperational)
process.exit(1);
});
Blog Quote: "Otherwise you risk the state" (From the blog debugable, ranked 3 for the keywords "Node.JS uncaught exception")
"…By the very nature of how throw works in JavaScript, there is almost never any way to safely “pick up where you left off”, without leaking references, or creating some other sort of undefined brittle state. The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else. The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker"
TL;DR: Error handling logic such as mail to admin and logging should be encapsulated in a dedicated and centralized object that all end-points (e.g. Express middleware, cron jobs, unit-testing) call when an error comes in.
Otherwise: Not handling errors within a single place will lead to code duplication and probably to errors that are handled improperly
Code example - a typical error flow
//DAL layer, we don't handle errors here
DB.addDocument(newCustomer, (error, result) => {
if (error)
throw new Error("Great error explanation comes here", other useful parameters)
});
//API route code, we catch both sync and async errors and forward to the middleware
try {
customerService.addNew(req.body).then(function (result) {
res.status(200).json(result);
}).catch((error) => {
next(error)
});
}
catch (error) {
next(error);
}
//Error handling middleware, we delegate the handling to the centrzlied error handler
app.use(function (err, req, res, next) {
errorHandler.handleError(err).then((isOperationalError) => {
if (!isOperationalError)
next(err);
});
});
Blog quote: "Sometimes lower levels can’t do anything useful except propagate the error to their caller" (From the blog Joyent, ranked 1 for the keywords “Node.JS error handling”)
"…You may end up handling the same error at several levels of the stack. This happens when lower levels can’t do anything useful except propagate the error to their caller, which propagates the error to its caller, and so on. Often, only the top-level caller knows what the appropriate response is, whether that’s to retry the operation, report an error to the user, or something else. But that doesn’t mean you should try to report all errors to a single top-level callback, because that callback itself can’t know in what context the error occurred"
TL;DR: Let your API callers know which errors might come in return so they can handle these thoughtfully without crashing. This is usually done with REST API documentation frameworks like Swagger
Otherwise: An API client might decide to crash and restart only because he received back an error he couldn’t understand. Note: the caller of your API might be you (very typical in a microservices environment)
Blog quote: "You have to tell your callers what errors can happen" (From the blog Joyent, ranked 1 for the keywords “Node.JS logging”)
…We’ve talked about how to handle errors, but when you’re writing a new function, how do you deliver errors to the code that called your function? …If you don’t know what errors can happen or don’t know what they mean, then your program cannot be correct except by accident. So if you’re writing a new function, you have to tell your callers what errors can happen and what they mea
TL;DR: When an unknown error occurs (a developer error, see best practice number #3)- there is uncertainty about the application healthiness. A common practice suggests restarting the process carefully using a ‘restarter’ tool like Forever and PM2
Otherwise: When an unfamiliar exception is caught, some object might be in a faulty state (e.g an event emitter which is used globally and not firing events anymore due to some internal failure) and all future requests might fail or behave crazily
Code example - deciding whether to crash
//deciding whether to crash when an uncaught exception arrives
//Assuming developers mark known operational errors with error.isOperational=true, read best practice #3
process.on('uncaughtException', function(error) {
errorManagement.handler.handleError(error);
if(!errorManagement.handler.isTrustedError(error))
process.exit(1)
});
//centralized error handler encapsulates error-handling related logic
function errorHandler(){
this.handleError = function (error) {
return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
}
this.isTrustedError = function(error)
{
return error.isOperational;
}
Blog quote: "There are three schools of thoughts on error handling" (From the blog jsrecipes)
…There are primarily three schools of thoughts on error handling: 1. Let the application crash and restart it. 2. Handle all possible errors and never crash. 3. Balanced approach between the two
TL;DR: A set of mature logging tools like Winston, Bunyan or Log4J, will speed-up error discovery and understanding. So forget about console.log.
Otherwise: Skimming through console.logs or manually through messy text file without querying tools or a decent log viewer might keep you busy at work until late
Code example - Winston logger in action
//your centralized logger object
var logger = new winston.Logger({
level: 'info',
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
//custom code somewhere using the logger
logger.log('info', 'Test Log Message with some parameter %s', 'some parameter', { anything: 'This is metadata' });
Blog quote: "Lets identify a few requirements (for a logger):" (From the blog strongblog)
…Lets identify a few requirements (for a logger): 1. Time stamp each log line. This one is pretty self explanatory – you should be able to tell when each log entry occured. 2. Logging format should be easily digestible by humans as well as machines. 3. Allows for multiple configurable destination streams. For example, you might be writing trace logs to one file but when an error is encountered, write to the same file, then into error file and send an email at the same time…
TL;DR: Monitoring and performance products (a.k.a APM) proactively gauge your codebase or API so they can auto-magically highlight errors, crashes and slow parts that you were missing
Otherwise: You might spend great effort on measuring API performance and downtimes, probably you’ll never be aware which are your slowest code parts under real world scenario and how these affects the UX
Blog quote: "APM products segments" (From the blog Yoni Goldberg)
"…APM products constitutes 3 major segments:1. Website or API monitoring – external services that constantly monitor uptime and performance via HTTP requests. Can be setup in few minutes. Following are few selected contenders: Pingdom, Uptime Robot, and New Relic 2. Code instrumentation – products family which require to embed an agent within the application to benefit feature slow code detection, exceptions statistics, performance monitoring and many more. Following are few selected contenders: New Relic, App Dynamics 3. Operational intelligence dashboard – these line of products are focused on facilitating the ops team with metrics and curated content that helps to easily stay on top of application performance. This is usually involves aggregating multiple sources of information (application logs, DB logs, servers log, etc) and upfront dashboard design work. Following are few selected contenders: Datadog, Splunk"
The above is a shortened version - see here more best practices and examples
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
As of git 2.9:
git pull --rebase --autostash
See https://git-scm.com/docs/git-rebase
Automatically create a temporary stash before the operation begins, and apply it after the operation ends. This means that you can run rebase on a dirty worktree. However, use with care: the final stash application after a successful rebase might result in non-trivial conflicts.