NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.
Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.
The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.
Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.
Two good examples are regarding how you manage templates and use progressive enhancements with it. You just need a few lightweight pieces of JavaScript code to make it work perfectly.
I strongly recommend that you watch and read these articles:
Pick up any language and try to remember how you would manage your HTML file templates and what you had to do to update a single CSS class name in your DOM structure (for instance, a user clicked on a menu item and you want that marked as "selected" and update the content of the page).
With Node.js it is as simple as doing it in client-side JavaScript code. Get your DOM node and apply your CSS class to that. Get your DOM node and innerHTML your content (you will need some additional JavaScript code to do this. Read the article to know more).
Another good example, is that you can make your web page compatible both with JavaScript turned on or off with the same piece of code. Imagine you have a date selection made in JavaScript that would allow your users to pick up any date using a calendar. You can write (or use) the same piece of JavaScript code to make it work with your JavaScript turned ON or OFF.
I just added the environment variable Boost_INCLUDE_DIR or add it to the cmake command -DBoost_INCLUDE_DIR and point to the include folder.
Those who installed node.js via the package manager can just run:
sudo apt-get purge nodejs
Optionally if you have installed it by adding the official NodeSource repository as stated in Installing Node.js via package manager, do:
sudo rm /etc/apt/sources.list.d/nodesource.list
If you want to clean up npm cache as well:
rm -rf ~/.npm
It is bad practice to try to remove things manually, as it can mess up the package manager, and the operating system itself. This answer is completely safe to follow
I would consider using something like:
function GetList
{
. {
$a = new-object Collections.ArrayList
$a.Add(5)
$a.Add('next 5')
} | Out-Null
$a
}
$x = GetList
Output from $a.Add
is not returned -- that holds for all $a.Add
method calls. Otherwise you would need to prepend [void]
before each the call.
In simple cases I would go with [void]$a.Add
because it is quite clear that output will not be used and is discarded.
By doing Question = new Question()
(I assume the new
is a typo) you are overwriting the Question model with an intance of Question
. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question()
.
I am using Angular 5.2 and RxJS 5.5.6
This code did not work:
import { Observable,of } from 'rxjs/Observable';
getHeroes(): Observable<Hero[]> {
return of(Hero[]) HEROES;
}
Below code worked:
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
getHeroes(): Observable<Hero[]>
{
return Observable.create((observer: Subscriber<any>) => {
observer.next(HEROES);
observer.complete();
});
}
Calling method:
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
I think they might moved/changed of() functionality in RxJS 5.5.2
Open the org.eclipse.wst.common.project.facet.core.xml file and change the jst.web version to 3.0. Also update the web.xml to version 3.0. Save and update the project. Hope this helps. I am using Eclipse Juno
There is a much easier way to run Java, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.I put everything into:
<location path="." inheritInChildApplications="false">
....
</location>
except: <configSections/>
, <connectionStrings/>
and <runtime/>
.
There are some cases when we don't want to inherit some secions from <configSections />
, but we can't put <section/>
tag into <location/>
, so we have to create a <secionGroup />
and put our unwanted sections into that group. Section groups can be later inserted into a location tag.
So we have to change this:
<configSections>
<section name="unwantedSection" />
</configSections>
Into:
<configSections>
<sectionGroup name="myNotInheritedSections">
<section name="unwantedSection" />
</sectionGroup>
</configSections>
<location path="." inheritInChildApplications="false">
<myNotInheritedSections>
<unwantedSection />
</myNotInheritedSections>
</location>
The safest way would be bitwise OR ing your double with 0. Look at this XORing two doubles in Java
Basically you should do if ((Double.doubleToRawLongBits(foo.x) | 0 ) )
(if it is really 0)
To switch to PHP 4.4:
AddHandler application/x-httpd-php4 .php .php4 .php3
To switch to PHP 5.0:
AddHandler application/x-httpd-php5 .php .php5 .php4 .php3
To switch to PHP 5.1:
AddHandler application/x-httpd-php51 .php .php5 .php4 .php3
To switch to PHP 5.2:
AddHandler application/x-httpd-php52 .php .php5 .php4 .php3
To switch to PHP 5.3:
AddHandler application/x-httpd-php53 .php .php5 .php4 .php3
To switch to PHP 5.4:
AddHandler application/x-httpd-php54 .php .php5 .php4 .php3
To switch to PHP 5.5:
AddHandler application/x-httpd-php55 .php .php5 .php4 .php3
To switch to the secure PHP 5.2 with Suhosin patch:
AddHandler application/x-httpd-php52s .php .php5 .php4 .php3
That file has a listen-port element - that should be what you need to change, although it is currently set to 8080, not 7001.
I just wrote up a quick test, try this:
IEnumerable<Object> myList = new List<Object>();
Stopwatch watch = new Stopwatch();
int x;
watch.Start();
for (var i = 0; i <= 1000000; i++)
{
if (myList.Count() == 0) x = i;
}
watch.Stop();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (var i = 0; i <= 1000000; i++)
{
if (!myList.Any()) x = i;
}
watch2.Stop();
Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
Console.ReadLine();
The second is almost three times slower :)
Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.
So I guess it depends on the type of list you're using!
(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)
With help from these answers, I finally got reverse proxy for Node-RED running on a Raspberry Pi with Ubuntu Mate and Apache2 working, using this Apache2 site config:
<VirtualHost *:80>
ServerName nodered.domain.com
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://localhost:1880/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule /(.*) http://localhost:1880/$1 [P,L]
</VirtualHost>
I also had to enable modules like this:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
It's been a while and I don't remember which book taught me this algorithm, but I thought it was quite ingenious and simple to understand:
char input[] = "moc.wolfrevokcats";
int length = strlen(input);
int last_pos = length-1;
for(int i = 0; i < length/2; i++)
{
char tmp = input[i];
input[i] = input[last_pos - i];
input[last_pos - i] = tmp;
}
printf("%s\n", input);
A visualization of this algorithm, courtesy of slashdottir:
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
The short answer for this is, "because that's what the C++ standard specifies".
Note that you can always specify a constructor that's different from the default, like so:
class Shape {
Shape() {...} //default constructor
Shape(int h, int w) {....} //some custom constructor
};
class Rectangle : public Shape {
Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call
}
The default constructor of the base class is called only if you don't specify which one to call.
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
It seems to work fine in Postgresql 9.5:
SELECT current_setting('TIMEZONE');
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:
DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
Use it like this:
for key, value in DICT_ITER_ITEMS(myDict):
# Do something with 'key' and/or 'value'.
you could also add a repeating requestAnimationFrame to your resizeIframe (e.g. from @BlueFish's answer) which would always be called before the browser paints the layout and you could update the height of the iframe when its content have changed their heights. e.g. input forms, lazy loaded content etc.
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
window.requestAnimationFrame(() => resizeIframe(iframe));
}
</script>
<iframe onload="resizeIframe(this)" ...
your callback should be fast enough to have no big impact on your overall performance
I had same problem about SaveChanges() in EF but in my case I forget to update my sql table then after I used migration my problem solved so maybe updating your tables will solve problem.
Remove-Item -LiteralPath "foldertodelete" -Force -Recurse
Update: Genymotion's 2.5.1 release (https://www.genymotion.com/#!/release-notes/251#251) seems to have fixed this issue. (thanks for the heads up @Roger!)
For those that may be stumbling upon this a bit later, I resolved this by installing VirtualBox 4.3.28 (https://www.virtualbox.org/wiki/Download_Old_Builds_4_3). The new 5.0.0 and 4.3.30 versions didn't work for me with Genymotion 2.5. None of the above solutions worked :(
It's also worth noting that at the time of writing, Genymotion's FAQ states the following:
However, for performance reasons, we recommend using version 4.3.12
This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.
This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
<!--/ lower-->
</form>
</div>
<!--/ container-->
<!-- End Page Content -->
</body>
</html>
I am using Windows 8.1 environment. I had the same problem while running my first java program after installing Eclipse recently. I had installed java on d drive at d:\java. But Eclipse was looking at the default installation c:\programfiles\java. I did the following:
Modified my eclipse.ini file and added the following after open:
-vm
d:\java\jdk1.8.0_161\bin
While creating the java program I have to unselect default build path and then select d:\java.
After this, the program ran well and got the hello world to work.
WARNING: Necromancing
Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.
In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like 	
for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).
//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
//string content = System.Xml.XmlConvert.EncodeName("\t");
//string content = System.Security.SecurityElement.Escape("\t");
//string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("	");
//strDelimiter = XmlUnescape(";");
//Console.WriteLine(strDelimiter);
//Console.WriteLine(string.Format("&#{0};", (int)';'));
//Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
//Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);
string strXmlText = "";
if (string.IsNullOrEmpty(input))
return input;
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; ++i)
{
sb.AppendFormat("&#{0};", (int)input[i]);
}
strXmlText = sb.ToString();
sb.Clear();
sb = null;
return strXmlText;
} // End Function SpecialXmlEscape
XML 1.0:
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
Get days between Current date to destination Date
SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;
output
335
You can set the default time out in the server.xml
<Connector URIEncoding="UTF-8"
acceptCount="100"
connectionTimeout="20000"
disableUploadTimeout="true"
enableLookups="false"
maxHttpHeaderSize="8192"
maxSpareThreads="75"
maxThreads="150"
minSpareThreads="25"
port="7777"
redirectPort="8443"/>
if you got troubles with windows cmd command and .bat just escape percents like that
git show -s --format=%%ct
The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%
If it's a phantom breakpoint:
1 Delete the offending line of code
2 Run the code again
3 Repaste the line
I found this laughably simple solution after spending a couple days wading through all the answers here and elsewhere. I figured, if I link it to my original question it might help some other poor chap, since the question it's on is VBA break execution when there's no break key on keyboard and this is more applicable.
The data-reactid
attribute is a custom attribute used so that React can uniquely identify its components within the DOM.
This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).
{
id: '.1oqi7occu80',
node: DivRef,
children: [
{
id: '.1oqi7occu80.0',
node: SpanRef,
children: [
{
id: '.1oqi7occu80.0.0',
node: InputRef,
children: []
}
]
}
]
}
There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid
attributes.
<div data-reactid='.loqi70ccu80'>
<span data-reactid='.loqi70ccu80.0'>
<input data-reactid='.loqi70ccu80.0' />
</span>
</div>
It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid
attributes. This is called inflating the component tree.
You might also notice that if React renders at the client-side, it uses the data-reactid
attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML
then it inflates the component tree straight away, as a performance boost.
The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3
), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3
). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.
React 15 uses document.createElement
instead, so client rendered markup won't include these attributes anymore.
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
Try putting the call to axis
after all plotting commands.
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
If CURLOPT_FAILONERROR
is false
, http errors will not trigger curl
errors.
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
For the best measure of elapsed time (since Python 3.3), use time.perf_counter()
.
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic()
instead.
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
In many implementations, these may actually be the same thing.
Before 3.3, you're stuck with time.clock()
.
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.
Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.
Resolution starts breaking down on perf_counter()
after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.
time.clock
is now gone.
One command on the same row should always be faster than two on that same row. So the UPDATE only would be better.
EDIT set up the table:
create table YourTable
(YourName varchar(50) primary key
,Tag int
)
insert into YourTable values ('first value',1)
run this, which takes 1 second on my system (sql server 2005):
SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
UPDATE YourTable set YourName='new name'
while @x<10000
begin
Set @x=@x+1
update YourTable set YourName='new name' where YourName='new name'
SET @y=@y+@@ROWCOUNT
end
print @y
run this, which took 2 seconds on my system:
SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
while @x<10000
begin
Set @x=@x+1
DELETE YourTable WHERE YourName='new name'
insert into YourTable values ('new name',1)
SET @y=@y+@@ROWCOUNT
end
print @y
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.
Try using an Object, not an Array:
var test = new Object(); test[2300] = 'Some string';
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
Here's the map solution:
#include <iostream>
#include <map>
typedef std::map<char, char> BasePairMap;
int main()
{
BasePairMap m;
m['A'] = 'T';
m['T'] = 'A';
m['C'] = 'G';
m['G'] = 'C';
std::cout << "A:" << m['A'] << std::endl;
std::cout << "T:" << m['T'] << std::endl;
std::cout << "C:" << m['C'] << std::endl;
std::cout << "G:" << m['G'] << std::endl;
return 0;
}
Or you can use simply preload="none"
attribute to make VIDEO background visible. And you can use background-size: cover;
here.
video {
background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
}
<video preload="none" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
</video>
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
==> make sure you are getting the correct layout here. R.layout...
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
Here's a quick overview:
One last thing: If you declare Foo foo;
without assigning it you don't have to worry - nothing is leaked. If Foo is a reference type, nothing was created. If Foo is a value type, it is allocated on the stack and thus will automatically be cleaned up.
In some situations, it will be lighter weight to use this static method from Google Guava library: List<Integer> Ints.asList(int... backingArray)
Examples:
List<Integer> x1 = Ints.asList(0, 1, 2, 3)
List<Integer> x1 = Ints.asList(new int[] { 0, 1, 2, 3})
Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.
You can achieve this with the following code:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
counter[row[11]]+=1
You don't show what data
is, but apparently when you loop through its rows, row[11]
is turning out to be a list
. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11]
as a key causes the defaultdict
to complain that it is a mutable, i.e. unhashable, object.
The easiest fix is to change row[11]
from a list
to a tuple
. Either by doing
counter[tuple(row[11])] += 1
or by fixing it in the caller before data
is passed to medications_minimum3
. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.
The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).
Here is an example of how to set up a test for sorting:
>>> import timeit
>>> setup = '''
import random
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''
>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145
Note that the series of statements makes a fresh copy of the unsorted data on every pass.
Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.
Those are my tips for using timeit correctly. Hope this helps :-)
You can try this
$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i;
If you are using microsoft query, you can add "?" to your query...
select name from user where id= ?
that will popup a small window asking for the cell/data/etc when you go back to excel.
In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.
There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html
# simple binary tree
# in this implementation, a node is inserted between an existing node and the root
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def setNodeValue(self,value):
self.rootid = value
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.right = self.right
self.right = tree
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.left = self.left
self.left = tree
def printTree(tree):
if tree != None:
printTree(tree.getLeftChild())
print(tree.getNodeValue())
printTree(tree.getRightChild())
# test tree
def testTree():
myTree = BinaryTree("Maud")
myTree.insertLeft("Bob")
myTree.insertRight("Tony")
myTree.insertRight("Steven")
printTree(myTree)
Read more about it Here:-This is a very simple implementation of a binary tree.
This is a nice tutorial with questions in between
angular-charts is a library I wrote for creating charts with angular and D3.
It encapsulates basic charts that can be created using D3 in one angular directive. Also it offers features such as
There is a angular-charts demo available.
Use string concatenation. Try this:
$('div[imageId="'+imageN +'"]').each(function() {
$(this);
});
Quick version: .container
has one fixed width for each screen size in bootstrap (xs,sm,md,lg); .container-fluid
expands to fill the available width.
The difference between container
and container-fluid
comes from these lines of CSS:
@media (min-width: 568px) {
.container {
width: 550px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
Depending on the width of the viewport that the webpage is being viewed on, the container
class gives its div a specific fixed width. These lines don't exist in any form for container-fluid
, so its width changes every time the viewport width changes.
So for example, say your browser window is 1000px wide. As it's greater than the min-width of 992px, your .container
element will have a width of 970px. You then slowly widen your browser window. The width of your .container
won't change until you get to 1200px, at which it will jump to 1170px wide and stay that way for any larger browser widths.
Your .container-fluid
element, on the other hand, will constantly resize as you make even the smallest changes to your browser width.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
Just insert a ' before anything to be inserted. It will be like a escape character in sqlServer
Example: When you have a field as, I'm fine. you can do: UPDATE my_table SET row ='I''m fine.';
Here is an example that will show you the differences in storage size (bytes) and precision between smalldatetime, datetime, datetime2(0), and datetime2(7):
DECLARE @temp TABLE (
sdt smalldatetime,
dt datetime,
dt20 datetime2(0),
dt27 datetime2(7)
)
INSERT @temp
SELECT getdate(),getdate(),getdate(),getdate()
SELECT sdt,DATALENGTH(sdt) as sdt_bytes,
dt,DATALENGTH(dt) as dt_bytes,
dt20,DATALENGTH(dt20) as dt20_bytes,
dt27, DATALENGTH(dt27) as dt27_bytes FROM @temp
which returns
sdt sdt_bytes dt dt_bytes dt20 dt20_bytes dt27 dt27_bytes
------------------- --------- ----------------------- -------- ------------------- ---------- --------------------------- ----------
2015-09-11 11:26:00 4 2015-09-11 11:25:42.417 8 2015-09-11 11:25:42 6 2015-09-11 11:25:42.4170000 8
So if I want to store information down to the second - but not to the millisecond - I can save 2 bytes each if I use datetime2(0) instead of datetime or datetime2(7).
Use this as an example
https://www.w3schools.com/jquerymobile/tryit.asp?filename=tryjqmob_popup_image
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div data-role="page">_x000D_
<div data-role="header">_x000D_
<h1>Welcome To My Homepage</h1>_x000D_
</div>_x000D_
_x000D_
<div id="pageone" data-role="main" class="ui-content">_x000D_
<p>Click on the image to enlarge it.</p>_x000D_
<p>Notice that we have added a "back button" in the top right corner.</p>_x000D_
<a href="#myPopup" data-rel="popup" data-position-to="window">_x000D_
<img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" alt="Skaret View" style="width:200px;"></a>_x000D_
_x000D_
<div data-role="popup" id="myPopup">_x000D_
<p>This is my picture!</p> _x000D_
<a href="#pageone" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" style="width:800px;height:400px;" alt="Skaret View">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div data-role="footer">_x000D_
<h1>Footer Text</h1>_x000D_
</div>_x000D_
</div> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
You can modify your ViewModel as below:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
#include <fstream>
ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
getline(infile,data);
}
infile.close();
Here is example with only CSS for that. In example I'm using SASS and SLIM.
https://codepen.io/Darex1991/pen/zBxPxe
Slim:
a.btn.btn--joined-state
span joined
span leave
SASS:
=animate($property...)
@each $vendor in ('-webkit-', '')
#{$vendor}transition-property: $property
#{$vendor}transition-duration: .3s
#{$vendor}transition-timing-function: ease-in
=visible
+animate(opacity, max-height, visibility)
max-height: 150px
opacity: 1
visibility: visible
=invisible
+animate(opacity, max-height, visibility)
max-height: 0
opacity: 0
visibility: hidden
=transform($var)
@each $vendor in ('-webkit-', '-ms-', '')
#{$vendor}transform: $var
.btn
border: 1px solid blue
&--joined-state
position: relative
span
+animate(opacity)
span:last-of-type
+invisible
+transform(translateX(-50%))
position: absolute
left: 50%
&:hover
span:first-of-type
+invisible
span:last-of-type
+visible
border-color: blue
Try the following:
java -cp jar1:jar2:jar3:dir1:. HelloWorld
The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.
If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:
<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%; display: inline-block;">RIGHT</p>
Put your if condition inside resize
function:
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize > 440) {
//if the window is greater than 440px wide then turn on jScrollPane..
$('#pane1').jScrollPane({
scrollbarWidth:15,
scrollbarMargin:52
});
}
});
http://www.mail-archive.com/[email protected]/msg03998.html says:
...and .removeClass() would remove all classes...
It works for me ;)
cheers
Yes, that is the definition of raw pointer equality: they both point to the same location (or are pointer aliases); usually in the virtual address space of the process running your application coded in C++ and managed by some operating system (but C++ can also be used for programming embedded devices with micro-controllers having a Harward architecture: on such microcontrollers some pointer casts are forbidden and makes no sense - since read only data could sit in code ROM)
For C++, read a good C++ programming book, see this C++ reference website, read the documentation of your C++ compiler (perhaps GCC or Clang) and consider coding with smart pointers. Maybe read also some draft C++ standard, like n4713 or buy the official standard from your ISO representative.
The concepts and terminology of garbage collection are also relevant when managing pointers and memory zones obtained by dynamic allocation (e.g. ::operator new
), so read perhaps the GC handbook.
For pointers on Linux machines, see also this.
I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference. This works for me.
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:
.container {
display:block;
position:relative;
height:150px;
width:1024px;
margin:0 auto;
padding:0px;
border:0px;
background:#ececec;
margin-bottom:10px;
text-align:justify;
box-sizing:border-box;
white-space:nowrap;
font-size:0pt;
letter-spacing:-1em;
}
.cols {
display:inline-block;
position:relative;
width:32%;
height:100%;
margin:0 auto;
margin-right:2%;
border:0px;
background:lightgreen;
box-sizing:border-box;
padding:10px;
font-size:10pt;
letter-spacing:normal;
}
.cols:last-child {
margin-right:0;
}
I think seeing your usage for addEntity and removeEntity code would be helpful, but my first thought is are you actually setting the object.name? Try in your loader just before scene.add(object); something like this:
object.name = "test_name";
scene.add(object);
What might be happening is the default "name" for an Object3D is "", so when you then call your removeEntity function it fails due to the scene objects name being ""
Also, I notice you pass in object.name to your loader? Is this where your storing the URL to the resource? If so, I would recommend using the Object3D's built in .userData method to store that information and keep the name field for scene identification purposes.
Edit: Response to newly added Code
First thing to note is it's not a great idea to have "/" in your object name, it seems to work fine but you never know if some algorithm will decide to escape that string and break your project.
Second item is now that I've seen your code, its actually straight forward whats going on. Your delete function is trying to delete by name, you need an Object3D to delete. Try this:
function removeEntity(object) {
var selectedObject = scene.getObjectByName(object.name);
scene.remove( selectedObject );
animate();
}
Here you see I lookup your Object3D
in the Three.js Scene
by passing in your object tag's name
attribute. Hope that helps
Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.
var isFloat = function(n) {
n = n.length > 0 ? Number(n) : false;
return (n === parseFloat(n));
};
var isInteger = function(n) {
n = n.length > 0 ? Number(n) : false;
return (n === parseInt(n));
};
var isNumeric = function(n){
if(isInteger(n) || isFloat(n)){
return true;
}
return false;
};
This will resolve any nested properties.
public class Environment extends PropertyPlaceholderConfigurer {
/**
* Map that hold all the properties.
*/
private Map<String, String> propertiesMap;
/**
* Iterate through all the Property keys and build a Map, resolve all the nested values before building the map.
*/
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props);
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String valueStr = beanFactory.resolveEmbeddedValue(placeholderPrefix + keyStr.trim() + DEFAULT_PLACEHOLDER_SUFFIX);
propertiesMap.put(keyStr, valueStr);
}
}
/**
* This method gets the String value for a given String key for the property files.
*
* @param name - Key for which the value needs to be retrieved.
* @return Value
*/
public String getProperty(String name) {
return propertiesMap.get(name).toString();
}
Shorter answer: ignore it.
This module is the part of Postgres that processes the SQL language. The error will often pop up as part of copying a remote database, such as with a 'heroku pg:pull'. It does not overwrite your SQL processor and warns you about that.
Here's a stdlib solution that supports a variable utc offset in the input time string:
>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)
If you are not using jQuery and using something like fetch API for requests you can use the following to get the csrf-token
:
document.querySelector('meta[name="csrf-token"]').getAttribute('content')
fetch('/users', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')},
credentials: 'same-origin',
body: JSON.stringify( { id: 1, name: 'some user' } )
})
.then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('request failed', error)
})
IF you want to to manipulate the ::before or ::after sudo elements entirely through CSS, you could do it JS. See below;
jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');
Notice how the <style>
element has an ID, which you can use to remove it and append to it again if your style changes dynamically.
This way, your element is style exactly how you want it through CSS, with the help of JS.
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
Try to assign the image that way instead:
imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
A few miscellaneous thoughts on this topic:
values
returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.each
. This is not true for keys
as each
is an iterator while keys
returns a list.If any background task runs more than 10 minutes,then the task will be suspended and code block specified with beginBackgroundTaskWithExpirationHandler is called to clean up the task. background remaining time can be checked with [[UIApplication sharedApplication] backgroundTimeRemaining]. Initially when the App is in foreground backgroundTimeRemaining is set to bigger value. When the app goes to background, you can see backgroundTimeRemaining value decreases from 599.XXX ( 1o minutes). once the backgroundTimeRemaining becomes ZERO, the background task will be suspended.
//1)Creating iOS Background Task
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//This code block is execute when the application’s
//remaining background time reaches ZERO.
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
//#### background task ends
});
//2)Making background task Asynchronous
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
NSLog(@"Multitasking Supported");
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
**//Putting All together**
//To make the code block asynchronous
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
NSLog(@"Running in the background\n");
while(TRUE)
{
NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
[NSThread sleepForTimeInterval:1]; //wait for 1 sec
}
//#### background task ends
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});
}
else
{
NSLog(@"Multitasking Not Supported");
}
If you want to run the script directly, you can:
PYTHONPATH
).sys.path
in the your script.Then:
import module_you_wanted
@bninopaul 's answer is not completely for beginners
here is the code you can "copy and run"
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[13,1,1,0,2,0],
[3,9,6,0,1,0],
[0,0,16,2,0,0],
[0,0,0,13,0,0],
[0,0,0,0,15,0],
[0,0,1,0,0,15]]
df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size
plt.show()
modify the file:build.gradle(app directory). in fact:you should not change this file , only by this to get sync tips,then sync project.
Based on my Comment here is one way to get what you want done:
Start byt selecting any cell in your range and Press Ctrl + T
This will give you this pop up:
make sure the Where is your table text is correct and click ok you will now have:
Now If you add a column header in D it will automatically be added to the table all the way to the last row:
Now If you enter a formula into this column:
After you enter it, the formula will be auto filled all the way to last row:
Now if you add a new row at the next row under your table:
Once entered it will be resized to the width of your table and all columns with formulas will be added also:
Hope this solves your problem!
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
67
Reserved.objects.filter(client=client_id).order_by('-check_in')
'-' is indicates Descending order and for Ascending order just give class attribute
You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.
You have not placed the script tags for angular js
you can do so by using cdn or downloading the angularjs for your project and then referencing it
after this you have to add your own java script in your case main.js
that should do
To start the port correctly in your desired port use:
npm start -- --port 8000
Use ax.yaxis.tick_right()
for example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
How to POST mixed data: File, String[], String in one request.
You can use only what you need.
private String doPOST(File file, String[] array, String name) {
RestTemplate restTemplate = new RestTemplate(true);
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
//add array
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
for (String item : array) {
builder.queryParam("array", item);
}
//add some String
builder.queryParam("name", name);
//another staff
String result = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}
The POST request will have File in its Body and next structure:
POST https://my_url?array=your_value1&array=your_value2&name=bob
I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.
response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)
Note, format provided for --write-out should be quoted.
As suggested by @ibai, add --head
to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.
Same error occurs in localhost, i'm just changing the mysql port (8080 into localhost mysql port 5506). it works for me.
Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure
At work, we recently went through implementation of i18n on a couple of our properties, and one of the things we kept struggling with was the performance hit of dealing with on-the-fly translation, then I discovered this great blog post by Thomas Bley which inspired the way we're using i18n to handle large traffic loads with minimal performance issues.
Instead of calling functions for every translation operation, which as we know in PHP is expensive, we define our base files with placeholders, then use a pre-processor to cache those files (we store the file modification time to make sure we're serving the latest content at all times).
Thomas uses {tr}
and {/tr}
tags to define where translations start and end. Due to the fact that we're using TWIG, we don't want to use {
to avoid confusion so we use [%tr%]
and [%/tr%]
instead. Basically, this looks like this:
`return [%tr%]formatted_value[%/tr%];`
Note that Thomas suggests using the base English in the file. We don't do this because we don't want to have to modify all of the translation files if we change the value in English.
Then, we create an INI file for each language, in the format placeholder = translated
:
// lang/fr.ini
formatted_value = number_format($value * Model_Exchange::getEurRate(), 2, ',', ' ') . '€'
// lang/en_gb.ini
formatted_value = '£' . number_format($value * Model_Exchange::getStgRate())
// lang/en_us.ini
formatted_value = '$' . number_format($value)
It would be trivial to allow a user to modify these inside the CMS, just get the keypairs by a preg_split
on \n
or =
and making the CMS able to write to the INI files.
Essentially, Thomas suggests using a just-in-time 'compiler' (though, in truth, it's a preprocessor) function like this to take your translation files and create static PHP files on disk. This way, we essentially cache our translated files instead of calling a translation function for every string in the file:
// This function was written by Thomas Bley, not by me
function translate($file) {
$cache_file = 'cache/'.LANG.'_'.basename($file).'_'.filemtime($file).'.php';
// (re)build translation?
if (!file_exists($cache_file)) {
$lang_file = 'lang/'.LANG.'.ini';
$lang_file_php = 'cache/'.LANG.'_'.filemtime($lang_file).'.php';
// convert .ini file into .php file
if (!file_exists($lang_file_php)) {
file_put_contents($lang_file_php, '<?php $strings='.
var_export(parse_ini_file($lang_file), true).';', LOCK_EX);
}
// translate .php into localized .php file
$tr = function($match) use (&$lang_file_php) {
static $strings = null;
if ($strings===null) require($lang_file_php);
return isset($strings[ $match[1] ]) ? $strings[ $match[1] ] : $match[1];
};
// replace all {t}abc{/t} by tr()
file_put_contents($cache_file, preg_replace_callback(
'/\[%tr%\](.*?)\[%\/tr%\]/', $tr, file_get_contents($file)), LOCK_EX);
}
return $cache_file;
}
Note: I didn't verify that the regex works, I didn't copy it from our company server, but you can see how the operation works.
Again, this example is from Thomas Bley, not from me:
// instead of
require("core/example.php");
echo (new example())->now();
// we write
define('LANG', 'en_us');
require(translate('core/example.php'));
echo (new example())->now();
We store the language in a cookie (or session variable if we can't get a cookie) and then retrieve it on every request. You could combine this with an optional $_GET
parameter to override the language, but I don't suggest subdomain-per-language or page-per-language because it'll make it harder to see which pages are popular and will reduce the value of inbound links as you'll have them more scarcely spread.
We like this method of preprocessing for three reasons:
We just add a column for content in our database called language
, then we use an accessor method for the LANG
constant which we defined earlier on, so our SQL calls (using ZF1, sadly) look like this:
$query = select()->from($this->_name)
->where('language = ?', User::getLang())
->where('id = ?', $articleId)
->limit(1);
Our articles have a compound primary key over id
and language
so article 54
can exist in all languages. Our LANG
defaults to en_US
if not specified.
I'd combine two things here, one is a function in your bootstrap which accepts a $_GET
parameter for language and overrides the cookie variable, and another is routing which accepts multiple slugs. Then you can do something like this in your routing:
"/wilkommen" => "/welcome/lang/de"
... etc ...
These could be stored in a flat file which could be easily written to from your admin panel. JSON or XML may provide a good structure for supporting them.
PHP-based On-The-Fly Translation
I can't see that these offer any advantage over pre-processed translations.
Front-end Based Translations
I've long found these interesting, but there are a few caveats. For example, you have to make available to the user the entire list of phrases on your website that you plan to translate, this could be problematic if there are areas of the site you're keeping hidden or haven't allowed them access to.
You'd also have to assume that all of your users are willing and able to use Javascript on your site, but from my statistics, around 2.5% of our users are running without it (or using Noscript to block our sites from using it).
Database-Driven Translations
PHP's database connectivity speeds are nothing to write home about, and this adds to the already high overhead of calling a function on every phrase to translate. The performance & scalability issues seem overwhelming with this approach.
I just figured a simple way out . This works -
Just create a file with Tabs as delimiters ( similar to CSV but replace comma with Tab ). Save it with extension .XLS . The file can be opened in Excel .
Some code to help --
var fs = require('fs');
var writeStream = fs.createWriteStream("file.xls");
var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = "0"+"\t"+" 21"+"\t"+"Rob"+"\n";
var row2 = "1"+"\t"+" 22"+"\t"+"bob"+"\n";
writeStream.write(header);
writeStream.write(row1);
writeStream.write(row2);
writeStream.close();
This creates the file in XLS file format . It doesnt work if you try XLSX instead of XLS .
You have 4 columns A,B,C,D
Here is a better way to select the columns you need for the new dataframe:-
df2 = df1[['A','D']]
if you wish to use column numbers instead, use:-
df2 = df1[[0,3]]
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
From the document.getElementsByTagName
I guess you are running the javascript in a browser.
The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.
From Sort an array of associative arrays by value of given key in php:
by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output:
Array
(
[0] => Array
(
[price] => 200.0
[product] => test3
)
[1] => Array
(
[price] => 1000.50
[product] => test1
)
[2] => Array
(
[price] => 8800.50
[product] => test2
)
)
You could call std::terminate()
from any thread and the thread you're referring to will forcefully end.
You could arrange for ~thread()
to be executed on the object of the target thread, without a intervening join()
nor detach()
on that object. This will have the same effect as option 1.
You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.
Options 1 and 2 don't leak intra-process resources, but they terminate every thread.
Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.
There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.
A std::thread
may have this member function:
native_handle_type native_handle();
You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type
is a pthread_t
. If you are successful, you are likely to leak resources.
Another way you could do it is using the next() function.
matched_obj = next(x for x in list if x.n == 10)
From the Jinja2 template designer documentation:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as
ROWTERMINATOR = '0x0a'
Pay attention to header record as well and specify
FIRSTROW = 2
My final block for data file export from google bigquery looks like this.
BULK INSERT TABLENAME
FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
TABLOCK
)
(cross-posting from an answer I gave to a similar question - Does Android support near real time push notification? )
I recently started playing with MQTT http://mqtt.org for Android as a way of doing this sort of thing (i.e. push notification that is not SMS but data driven, almost immediate message delivery, not polling, etc.)
I have a blog post with background information on this in case it's helpful
http://dalelane.co.uk/blog/?p=938
(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)
Please try the following code snippet,
IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value),
Format(Avg(Fields!Vision_Score.Value)),
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))
hope it will help, Thank-you.
The zip()
function in Python 3 returns an iterator. That is the reason why when you print test1
you get - <zip object at 0x1007a06c8>
. From documentation -
Make an iterator that aggregates elements from each of the iterables.
But once you do - list(test1)
- you have exhausted the iterator. So after that anytime you do list(test1)
would only result in empty list.
In case of test2
, you have already created the list once, test2
is a list, and hence it will always be that list.
You can use format like here,
public static double getDoubleValue(String value,int digit){
if(value==null){
value="0";
}
double i=0;
try {
DecimalFormat digitformat = new DecimalFormat("#.##");
digitformat.setMaximumFractionDigits(digit);
return Double.valueOf(digitformat.format(Double.parseDouble(value)));
} catch (NumberFormatException numberFormatExp) {
return i;
}
}
I find the best (and least frustrating) path is to start with Allow from All
, then, when you know it will work that way, scale it back to the more secure Allow from 127.0.0.1
or Allow from ::1
(localhost).
As long as your firewall is configured properly, Allow from all
shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site.
Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.
Hopefully this is enough to get you started, there is lots of documentation available online.
Neither of these approaches (npm link
or package.json
file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.
For example:
/local/mymodule/package.json:
"name": "mymodule",
"peerDependencies":
{
"foo": "^2.5"
}
/dev/myproject/package.json:
"dependencies":
{
"mymodule": "file:/local/mymodule",
"foo": "^2.5"
}
In this scenario, npm sets up myproject
's node_modules/
like this:
/dev/myproject/node_modules/
foo/
mymodule -> /local/mymodule
When node loads mymodule
and it does require('foo')
, node resolves the mymodule
symlink, and then only looks in /local/mymodule/node_modules/
(and its ancestors) for foo
, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/
, since that's where were running our project from, and where foo
is installed.
So, we either need a way to tell node to not resolve this symlink when looking for foo
, or we need a way to tell npm to install a copy of mymodule
when the file dependency syntax is used in package.json
. I haven't found a way to do either, unfortunately :(
wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
I already added these params by xml but it didnot work correctly
and with this line all is ok
Mocking is generating pseudo-objects that simulate real objects behaviour for tests
use $unwind you will get the first object instead of array of objects
query:
db.getCollection('vehicles').aggregate([
{
$match: {
status: "AVAILABLE",
vehicleTypeId: {
$in: Array.from(newSet(d.vehicleTypeIds))
}
}
},
{
$lookup: {
from: "servicelocations",
localField: "locationId",
foreignField: "serviceLocationId",
as: "locations"
}
},
{
$unwind: "$locations"
}
]);
result:
{
"_id" : ObjectId("59c3983a647101ec58ddcf90"),
"vehicleId" : "45680",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Isuzu/2003-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
{
"_id" : ObjectId("59c3983a647101ec58ddcf91"),
"vehicleId" : "81765",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Hino/2004-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value
<select name="gender">
<option value="default">Select </option>
<option value="male"> Male </option>
<option value="female"> Female </option>
</select>
OR
<select name="gender">
<option value="male" selected="selected"> Male </option>
<option value="female"> Female </option>
</select>
When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.
Most important thing, AVOID SQL INJECTIONS:
//....
$fname = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$email = mysql_real_escape_string($_POST['email']);
}
else
{
//die ('invalid email address');
// or whatever, a default value? $email = '';
}
$paswod = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';
$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
echo 'userid is already there';
}
else
{
$sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';
I use this mnemonic :
a.compareTo(b) < 0 // a < b
a.compareTo(b) > 0 // a > b
a.compareTo(b) == 0 // a == b
You keep the signs and always compare the result of compareTo()
to 0
Use like
rake db:drop db:create db:migrate db:seed
All in one line. This is faster since the environment doesn't get reloaded again and again.
db:drop - will drop database.
db:create - will create database (host/db/password will be taken from config/database.yml)
db:migrate - will run existing migrations from directory (db/migration/.rb)*.
db:seed - will run seed data possible from directory (db/migration/seed.rb)..
I usually prefer:
rake db:reset
to do all at once.
Cheers!
Try this on Ruby. It will return a new date/time the specified number of days in the future
DateTime.now.days_since(10)
I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.
To workaround I use JPQL CONCAT function (this code emulate start with):
@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
private static final String QUERY = "select b from Branch b"
+ " left join b.filial f"
+ " where f.id = ?1 and b.id like CONCAT(?2, '%')";
@Query(QUERY)
List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}
I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html
First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
Case in method names is important, so no addclass
.
It might be possible to delete the Zone Record entirely, then recreate it exactly as you want it. Perhaps this will force a full propagation. If I'm wrong, somebody tell me and I'll delete this suggestion. Also, I don't know how to save a Zone Record and recreate it using WHM or any other tool.
I do know that when I deleted a hosting account today and recreated it, the original Zone Record seemed to be propagated instantly to a DNS resolver up the line from my computer. That is good evidence it works.
It's explained in great detail in the docs, but I'll try to summarize:
matching
means git push
will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.
simple
means git push
will push only the current branch to the one that git pull
would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.
This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.
UIButton will not support setTextAlignment. So You need to go with setContentHorizontalAlignment for button text alignment
For your reference
[buttonName setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3
to a int is nonsense.
A double
or a float
datatype can hold rational numbers.
The way Java casts a double
to an int
is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i
will be zero.
%TEMP%
vc_redist.x64
see Download Visual C++ Redistributable for Visual Studio 2015Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
Your svn merge
syntax is wrong.
You want to checkout a working copy of trunk
and then use the svn merge --reintegrate
option:
$ pwd
/home/user/project-trunk
$ svn update # (make sure the working copy is up to date)
At revision <N>.
$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U foo.c
U bar.c
U .
$ # build, test, verify, ...
$ svn commit -m "Merge branch_1 back into trunk!"
Sending .
Sending foo.c
Sending bar.c
Transmitting file data ..
Committed revision <N+1>.
See the SVN book chapter on merging for more details.
Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate
This post will explore various approaches of fetching MIME Type across various programming languages with their CONS in one-line description as header. So, use them accordingly and the one which works for you.
For eg. the code below is especially helpful when user may supply either of .xls, .xlsx or .xlsm and you don't want to write code testing extension and supplying MIME-type for each of them. Let the system do this job.
>>> pip install python-magic
>>> import magic
>>> magic.from_file("Employee.pdf", mime=True)
'application/pdf'
>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'
Source: Baeldung's blog on File MIME Types in Java
@Test
public void get_JAVA7_mimetype() {
Path path = new File("Employee.xlsx").toPath();
String mimeType = Files.probeContentType(path);
assertEquals(mimeType, "application/vnd.ms-excel");
}
It will use FileTypeDetector implementations to probe the MIME type and invokes the probeContentType of each implementation to resolve the type. Hence, if the file is known to the implementations then the content type is returned. However, if that doesn’t happen, a system-default file type detector is invoked.
@Test
public void getMIMEType_from_Extension(){
File file = new File("Employee.xlsx");
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
assertEquals(mimeType, "application/vnd.ms-excel");
}
@Test
public void getMIMEType_UsingGetFileNameMap(){
File file = new File("Employee.xlsx");
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(file.getName());
assertEquals(mimeType, "image/png");
}
It returns the matrix of MIME types used by all instances of URLConnection which then is used to resolve the input file type. However, this matrix of MIME types is very limited when it comes to URLConnection.
By default, the class uses content-types.properties file in JRE_HOME/lib. We can, however, extend it, by specifying a user-specific table using the content.types.user.table property:
System.setProperty("content.types.user.table","<path-to-file>");
Source: FileReader API & Medium's article on using Magic Numbers in JavaScript to get Mime Types
Final result looks something like this when one use javaScript to fetch the MimeType based on filestream. Open the embedded jsFiddle to see and understand this approach.
Bonus: It's accessible for most of the MIME Types and also you can add custom Mime Types in the getMimetype function. Also, it has FULL SUPPORT for MS Office Files Mime Types.
The steps to calculate mime type for a file in this example would be:
Browser Support (Above 95% overall and Close to 100% in all modern browsers):
const uploads = []_x000D_
_x000D_
const fileSelector = document.getElementById('file-selector')_x000D_
fileSelector.addEventListener('change', (event) => {_x000D_
console.time('FileOpen')_x000D_
const file = event.target.files[0]_x000D_
_x000D_
const filereader = new FileReader()_x000D_
_x000D_
filereader.onloadend = function(evt) {_x000D_
if (evt.target.readyState === FileReader.DONE) {_x000D_
const uint = new Uint8Array(evt.target.result)_x000D_
let bytes = []_x000D_
uint.forEach((byte) => {_x000D_
bytes.push(byte.toString(16))_x000D_
})_x000D_
const hex = bytes.join('').toUpperCase()_x000D_
_x000D_
uploads.push({_x000D_
filename: file.name,_x000D_
filetype: file.type ? file.type : 'Unknown/Extension missing',_x000D_
binaryFileType: getMimetype(hex),_x000D_
hex: hex_x000D_
})_x000D_
render()_x000D_
}_x000D_
_x000D_
console.timeEnd('FileOpen')_x000D_
}_x000D_
_x000D_
_x000D_
const blob = file.slice(0, 4);_x000D_
filereader.readAsArrayBuffer(blob);_x000D_
})_x000D_
_x000D_
const render = () => {_x000D_
const container = document.getElementById('files')_x000D_
_x000D_
const uploadedFiles = uploads.map((file) => {_x000D_
return `<div class=result><hr />_x000D_
<span class=filename>Filename: <strong>${file.filename}</strong></span><br>_x000D_
<span class=fileObject>File Object (Mime Type):<strong> ${file.filetype}</strong></span><br>_x000D_
<span class=binaryObject>Binary (Mime Type):<strong> ${file.binaryFileType}</strong></span><br>_x000D_
<span class=HexCode>Hex Code (Magic Number):<strong> <em>${file.hex}</strong></span></em>_x000D_
</div>`_x000D_
})_x000D_
_x000D_
container.innerHTML = uploadedFiles.join('')_x000D_
}_x000D_
_x000D_
const getMimetype = (signature) => {_x000D_
switch (signature) {_x000D_
case '89504E47':_x000D_
return 'image/png'_x000D_
case '47494638':_x000D_
return 'image/gif'_x000D_
case '25504446':_x000D_
return 'application/pdf'_x000D_
case 'FFD8FFDB':_x000D_
case 'FFD8FFE0':_x000D_
case 'FFD8FFE1':_x000D_
return 'image/jpeg'_x000D_
case '504B0304':_x000D_
return 'application/zip'_x000D_
case '504B34':_x000D_
return 'application/vnd.ms-excel.sheet.macroEnabled.12'_x000D_
default:_x000D_
return 'Unknown filetype'_x000D_
}_x000D_
}
_x000D_
.result {_x000D_
font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;_x000D_
line-height: 20px;_x000D_
font-size: 14px;_x000D_
margin: 10px 0;_x000D_
}_x000D_
_x000D_
.filename {_x000D_
color: #333;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.fileObject {_x000D_
color: #a53;_x000D_
}_x000D_
_x000D_
.binaryObject {_x000D_
color: #63f;_x000D_
}_x000D_
_x000D_
.HexCode {_x000D_
color: #262;_x000D_
}_x000D_
_x000D_
em {_x000D_
padding: 2px 4px;_x000D_
background-color: #efefef;_x000D_
font-style: normal;_x000D_
}_x000D_
_x000D_
input[type=file] {_x000D_
background-color: #4CAF50;_x000D_
border: none;_x000D_
color: white;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
margin: 4px 2px;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<body>_x000D_
_x000D_
<input type="file" id="file-selector">_x000D_
_x000D_
<div id="files"></div>
_x000D_
In case somebody will struggle with same issue, it is case sensitive statement, so wrong case means your application won't get the permission.
WRONG
<uses-permission android:name="ANDROID.PERMISSION.INTERNET" />
CORRECT
<uses-permission android:name="android.permission.INTERNET" />
This issue may happen ie. on autocomplete in IDE
Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2
it gives you something like 0.30000000000000004
. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.
I would inherit from ValueError
class IllegalArgumentError(ValueError):
pass
It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.
If you need to catch that specific error, it is helpful to have a name.
Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.
After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.
"Atomic operation" means an operation that appears to be instantaneous from the perspective of all other threads. You don't need to worry about a partly complete operation when the guarantee applies.
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
There is a more straightforward way to disable scrolling (technically it is more rather interception of a scrolling event and ending it when a condition is met), using just standard functionality. RecyclerView
has the method called addOnScrollListener(OnScrollListener listener)
, and using just this you can stop it from scrolling, just so:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (viewModel.isItemSelected) {
recyclerView.stopScroll();
}
}
});
Use case:
Let's say that you want to disable scrolling when you click on one of the items within RecyclerView
so you could perform some actions with it, without being distracted by accidentally scrolling to another item, and when you are done with it, just click on the item again to enable scrolling. For that, you would want to attach OnClickListener
to every item within RecyclerView
, so when you click on an item, it would toggle isItemSelected
from false
to true
. This way when you try to scroll, RecyclerView
will automatically call method onScrollStateChanged
and since isItemSelected
set to true
, it will stop immediately, before RecyclerView
got the chance, well... to scroll.
Note: for better usability, try to use GestureListener
instead of OnClickListener
to prevent accidental
clicks.
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
lapply
can be used instead of a for
loop.
d1[] <- lapply(d1, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
This doesn't really have any advantages over the for loop, though maybe it's easier if you have non-numeric columns as well, in which case
d1[sapply(d1, is.numeric)] <- lapply(d1[sapply(d1, is.numeric)], function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
is almost as easy.
After compiling a few answers, I've come up with the following code. What surprised me was that the timer does not get frozen on a PC (Chrome, FF) or Android Chrome - the trigger worked in the background, and the visibility check was the only reliable info.
var timestamp = new Date().getTime();
var timerDelay = 5000;
var processingBuffer = 2000;
var redirect = function(url) {
//window.location = url;
log('ts: ' + timestamp + '; redirecting to: ' + url);
}
var isPageHidden = function() {
var browserSpecificProps = {hidden:1, mozHidden:1, msHidden:1, webkitHidden:1};
for (var p in browserSpecificProps) {
if(typeof document[p] !== "undefined"){
return document[p];
}
}
return false; // actually inconclusive, assuming not
}
var elapsedMoreTimeThanTimerSet = function(){
var elapsed = new Date().getTime() - timestamp;
log('elapsed: ' + elapsed);
return timerDelay + processingBuffer < elapsed;
}
var redirectToFallbackIfBrowserStillActive = function() {
var elapsedMore = elapsedMoreTimeThanTimerSet();
log('hidden:' + isPageHidden() +'; time: '+ elapsedMore);
if (isPageHidden() || elapsedMore) {
log('not redirecting');
}else{
redirect('appStoreUrl');
}
}
var log = function(msg){
document.getElementById('log').innerHTML += msg + "<br>";
}
setTimeout(redirectToFallbackIfBrowserStillActive, timerDelay);
redirect('nativeApp://');
I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....
import java.util.HashMap;
import java.util.Map;
import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;
public class Testing
{
public static void main(String[] args)
{
try
{
Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP
map.put("name", "chris");
map.put("island", "faranga");
Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP
mapInner.put("a", "A");
mapInner.put("b", "B");
mapInner.put("c", "C");
map.put("innerMap", mapInner);
Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP
mapRoot.put("ROOT", map);
System.out.println("Map: " + mapRoot);
System.out.println();
ToXML toXML = new ToXML();
String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML
System.out.println("Converted XML: " + convertedXML);
System.out.println();
ToMap toMap = new ToMap();
Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP
System.out.println("Converted Map: " + convertedMap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
-------- Map Detected --------
-------- XML created Successfully --------
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>
-------- XML Detected --------
-------- Map created Successfully --------
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
If you've implemented a change
method like this:
class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end
You can create an instance of the migration and run migrate(:up)
or migrate(:down)
on an instance, like this:
$ rails console
>> require "db/migrate/20090408054532_add_part_number_to_products.rb"
>> AddPartNumberToProducts.new.migrate(:down)
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3)
. If you get an error, you don't have the right version.
For example, DATETIME(3)
will give you millisecond resolution in your timestamps, and TIMESTAMP(6)
will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3)
will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001
, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT
or DOUBLE
columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001)
will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
You're thinking too complicated. It's actually just $('#'+openaddress)
.
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
the first parameters of function JSON.parse
should be a String, and your data is a JavaScript object, so it will convert to a String [object object]
, you should use JSON.stringify
before pass the data
JSON.parse(JSON.stringify(userData))
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
If you want to keep the row with the lowest id
value:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)
If you want the id
value that is the highest:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)
The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
Check out the percent
function from the formattable
package:
library(formattable)
x <- c(0.23, 0.95, 0.3)
percent(x)
[1] 23.00% 95.00% 30.00%
Take a look at the Java standard API doc. Right next to LinkedHashMap
, there is a LinkedHashSet
. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).
There is also an interface SortedSet
implemented by TreeSet
and ConcurrentSkipListSet
. Both allow iteration in the natural order of their elements or a Comparator
, but not random access or insertion order.
For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.
<div id="inner" tabindex="0">
this div can now have focus and receive keyboard events
</div>
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
Easiest way to see if the file is being cached is to append a query string to the <link />
element so that the browser will re-load it.
To do this you can change your stylesheet reference to something like
<link rel="stylesheet" type="text/css" href="/css/stylesheet.css?v=1" />
Note the v=1
part. You can update this each time you make a new version to see if it is indeed being cached.
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
1) Initialize array arr
and add elements
2) set variable to search for SEARCH_STRING
3) check if your array contains element
arr=()
arr+=('a')
arr+=('b')
arr+=('c')
SEARCH_STRING='b'
if [[ " ${arr[*]} " == *"$SEARCH_STRING"* ]];
then
echo "YES, your arr contains $SEARCH_STRING"
else
echo "NO, your arr does not contain $SEARCH_STRING"
fi
The warning is still there. In order to get rid of it I put it into a selector like this:
if ([self respondsToSelector:@selector(dismissModalViewControllerAnimated:)]) {
[self performSelector:@selector(dismissModalViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
It benefits people with OCD like myself ;)
I have applied the solution provided by @Levit and created function that will not call the extra Http Request.
It will solve the error Unable to Resolve Host
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) return false;
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
case ConnectivityManager.TYPE_MOBILE:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
default:
return false;
}
return false;
}
private static boolean isInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
Debug.i(exitValue + "");
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Now call it like,
if (!isInternetAvailable(getActivity())) {
//Show message
} else {
//Perfoem the api request
}
#import "MyViewController.h"
@interface MyViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation MyViewController
double timerInterval = 1.0f;
- (NSTimer *) timer {
if (!_timer) {
_timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)onTick:(NSTimer*)timer
{
NSLog(@"Tick...");
}
@end
Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.
The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.
import pandas as pd
tmp_data=pd.read_csv('file.csv',sep=';')
#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
Product(
name = tmp_data.ix[row]['Name']
description = tmp_data.ix[row]['Description'],
price = tmp_data.ix[row]['price'],
)
for row in tmp_data['ID']
]
Product.objects.bulk_create(products)
I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.
Pandas has so many useful caveats, it is worth getting to know
Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.
df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")
If you need to filter out rows that contain any null (OR connected) please use
df.na.drop()
Use WebElement.send_keys
method to simulate key typing.
name
in the code (Username
, Password
) does not match actual name
of the elements (username
, password
).
username = browser.find_element_by_name('username')
username.send_keys('user1')
password = browser.find_element_by_name('password')
password.send_keys('secret')
form = browser.find_element_by_id('loginForm')
form.submit()
# OR browser.find_element_by_id('submit').click()
You may use formatters after picking value inside your datepicker directive. For example
angular.module('foo').directive('bar', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.push(function(value) {
if (value) {
// format and return date here
}
return undefined;
});
}
};
});
LINK.
Check this code:
Javascript:
app.config( ["$routeProvider"], function($routeProvider){
$routeProvider.when("/part1", {"templateUrl" : "part1"});
$routeProvider.when("/part2", {"templateUrl" : "part2"});
$routeProvider.otherwise({"redirectTo":"/part1"});
}]
);
function HomeFragmentController($scope) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.transitionState = "active"
});
}
CSS:
.fragmentWrapper {
overflow: hidden;
}
.fragment {
position: relative;
-moz-transition-property: left;
-o-transition-property: left;
-webkit-transition-property: left;
transition-property: left;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;
-webkit-transition-duration: 0.1s;
transition-duration: 0.1s
}
.fragment:not(.active) {
left: 540px;
}
.fragment.active {
left: 0px;
}
Main page HTML:
<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>
Partials HTML example:
<div id="part1" class="fragment {{transitionState}}">
</div>
tldr; it's a converted code form the source code, which the python VM interprets for execution.
Bottom-up understanding: the final stage of any program is to run/execute the program's instructions on the hardware/machine. So here are the stages preceding execution:
Executing/running on CPU
Converting bytcode to machine code.
Machine code is the final stage of conversion.
Instructions to be executed on CPU are given in machine code. Machine code can be executed directly by CPU.
Converting Bytecode to machine code.
Converting Source code to bytcode.
Now the actual plot. There are two approaches when carrying any of these stages: convert [or execute] a code all at once (aka compile) and convert [or execute] the code line by line (aka interpret).
For example, we could compile a source code to bytcoe, compile bytecode to machine code, interpret machine code for execution.
Some implementations of languages skip stage 3 for efficiency, i.e. compile source code into machine code and then interpret machine code for execution.
Some implementations skip all middle steps and interpret the source code directly for execution.
Modern languages often involve both compiling an interpreting.
JAVA for example, compile source code to bytcode [that is how JAVA source is stored, as a bytcode], compile bytcode to machine code [using JVM], and interpret machine code for execution. [Thus JVM is implemented differently for different OSs, but the same JAVA source code could be executed on different OS that have JVM installed.]
Python for example, compile source code to bytcode [usually found as .pyc files accompanying the .py source codes], compile bytocde to machine code [done by a virtual machine such as PVM and the result is an executable file], interpret the machine code/executable for execution.
When we can say that a language is interpreted or compiled?
Therefore, JAVA and Python are interpreted languages.
A confusion might occur because of the third stage, that's converting bytcode to machine code. Often this is done using a software called a virtual machine. The confusion occurs because a virtual machine acts like a machine, but it's actually not! Virtual machines are introduced for portability, having a VM on any REAL machine will allow us to execute the same source code. The approach used in most VMs [that's the third stage] is compiling, thus some people would say it's a compiled language. For the importance of VMs, we often say that such languages are both compiled and interpreted.
You can cast the the json as follows:
Given your class:
export class Employee{
firstname: string= '';
}
and the json:
let jsonObj = {
"firstname": "Hesham"
};
You can cast it as follows:
let e: Employee = jsonObj as Employee;
And the output of console.log(e);
is:
{ firstname: 'Hesham' }
For completeness, here's kisp's solution ported to VB (can't add code to a comment)
Namespace Utils
''' <summary>
''' Subclass of WebClient to provide access to the timeout property
''' </summary>
Public Class WebClient
Inherits System.Net.WebClient
Private _TimeoutMS As Integer = 0
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal TimeoutMS As Integer)
MyBase.New()
_TimeoutMS = TimeoutMS
End Sub
''' <summary>
''' Set the web call timeout in Milliseconds
''' </summary>
''' <value></value>
Public WriteOnly Property setTimeout() As Integer
Set(ByVal value As Integer)
_TimeoutMS = value
End Set
End Property
Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
If _TimeoutMS <> 0 Then
w.Timeout = _TimeoutMS
End If
Return w
End Function
End Class
End Namespace
Switch fallthrough is historically one of the major source of bugs in modern softwares. The language designer decided to make it mandatory to jump at the end of the case, unless you are defaulting to the next case directly without processing.
switch(value)
{
case 1:// this is still legal
case 2:
}
You can also simply use
WORKDIR /var/www/app
It will automatically create the folders if they don't exist.
Then switch back to the directory you need to be in.
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
A simple definition: A web service is a function that can be accessed by other programs over the web (HTTP).
For example, when you create a website in PHP that outputs HTML, its target is the browser and by extension the human reading the page in the browser. A web service is not targeted at humans but rather at other programs.
So your PHP site that generates a random integer could be a web service if it outputs the integer in a format that may be consumed by another program. It might be in an XML format or another format, as long as other programs can understand the output.
The full definition is obviously more complex but you asked for plain English.
Suppose we have three anchor tags like ,
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
now in script
$(".testClick").click(function () {
var anchorValue= $(this).attr("href");
alert(anchorValue);
});
use this keyword instead of className (testClick)
You can always use $('#GridName').data('kendoGrid').dataSource.read();
. You don't really need to .refresh();
after that, .dataSource.read();
will do the trick.
Now if you want to refresh your grid in a more angular way, you can do:
<div kendo-grid="vm.grid" id="grid" options="vm.gridOptions"></div>
vm.grid.dataSource.read();`
OR
vm.gridOptions.dataSource.read();
And don't forget to declare your datasource as kendo.data.DataSource
type
Here is a guide to JSZIP to create ZIP files by JavaScript. To download files you need to have filesaver.js, You can include those libraries by:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>
Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.
<script type="text/javascript">
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "file.zip");
});
</script>
Now let's get in to deeper. Create an instance of JSZip.
var zip = new JSZip();
Add a file with a Hello World text:
zip.file("hello.txt", "Hello World\n");
Download the filie with name archive.zip
zip.generateAsync({type:"blob"}).then(function(zip) {
saveAs(zip, "archive.zip");
});
Read More from here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library
String is immutable.
Why? Check here.
StringBuffer is not. It is thread safe.
Further questions like when to use which and other concepts can be figured out following this.
Hope this helps.
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE
.
Reference: https://www.postgresql.org/docs/current/functions-matching.html
You can use composer method like
composer create-project laravel/laravel blog "5.1"
Or here is the composer file
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~4.0",
"phpspec/phpspec": "~2.1"
},
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"pre-update-cmd": [
"php artisan clear-compiled"
],
"post-update-cmd": [
"php artisan optimize"
],
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
}
}
So, which one should be used to create a resource? Or one needs to support both?
You should use PATCH
. You PATCH the list of questions like
PATCH /questions HTTP/1.1
with a list containing your to be created object like
[
{
"title": "I said semantics!",
"content": "Is this serious?",
"answer": "Not really"
}
]
It's a PATCH request as
id
).A great advantage of this method is that you can create multiple entities using a single request, simply by providing them all in the list.
This is something PUT
obviously can't. You could use POST
for creating multiple entities as it's the kitchen sink of HTTP and can do basically everything.
A disadvantage is that probably nobody uses PATCH
this way. I'm afraid, I just invented it, but I hope, I provided a good argumentation.
You could use CREATE
instead, as custom HTTP verbs are allowed, it's just that they mayn't work with some tools.
Concerning semantics, CREATE
is IMHO the only right choice, everything else is a square peg in a round hole. Unfortunately, all we have are round holes.
Just set usesCleartextTraffic
flag in the application tag of AndroidManifest.xml
file.
No need to create config file for Android.
<application
android:usesCleartextTraffic="true"
.
.
.>
I fixed this error by inserting these lines of code:
<dependency>
<groupId>junit</groupId> <!-- NOT org.junit here -->
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
into <dependencies> node.
more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
>>> L = [1,2,3]
>>> " ".join(str(x) for x in L)
'1 2 3'
I fixed this by doing the following:
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module
for Python 2 and and Python 3.
You can use exec
if you want to as well.
Or using __import__
you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
Without using inline CSS you could set the text size of all your buttons using:
input[type="submit"], input[type="button"] {
font-size: 14px;
}
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
In python 3.x, use input()
instead of raw_input()