If "validation failure" means that there is some client error in the request, then use HTTP 400 (Bad Request). For instance if the URI is supposed to have an ISO-8601 date and you find that it's in the wrong format or refers to February 31st, then you would return an HTTP 400. Ditto if you expect well-formed XML in an entity body and it fails to parse.
(1/2016): Over the last five years WebDAV's more specific HTTP 422 (Unprocessable Entity) has become a very reasonable alternative to HTTP 400. See for instance its use in JSON API. But do note that HTTP 422 has not made it into HTTP 1.1, RFC-7231.
Richardson and Ruby's RESTful Web Services contains a very helpful appendix on when to use the various HTTP response codes. They say:
400 (“Bad Request”)
Importance: High.
This is the generic client-side error status, used when no other 4xx error code is appropriate. It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense. (p. 381)
and:
401 (“Unauthorized”)
Importance: High.
The client tried to operate on a protected resource without providing the proper authentication credentials. It may have provided the wrong credentials, or none at all. The credentials may be a username and password, an API key, or an authentication token—whatever the service in question is expecting. It’s common for a client to make a request for a URI and accept a 401 just so it knows what kind of credentials to send and in what format. [...]
If your software uses a ProxySelector
(for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector
for your HttpClient
like this:
ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();
And then do your requests as usual:
HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);
Try this: sed -i '/^[ \t]*$/d' file-name
It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.
Note: there is a 'space' followed by '\t' inside the square bracket.
The modifier -i
will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.
Try This:
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.
My project is now behaving as I would expect.
this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:
menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) {
console.log("success!");
$scope.appetizers = data.appetizers;
console.log(data.appetizers);
});
});
This description is very vague. What did you try, and how did it fail.
To include a library with your project, you have to include it in the modules passed to the linker. The exact steps to do this depend on the tools you are using. That part has nothing to do with the OS.
Now, if you are successfully compiling the library into your app and it doesn't run, that COULD be related to the OS.
If you are already in a REPL window and don't see the welcome message with the version number, you can use help() to see the major and minor version:
>>>help()
Welcome to Python 3.6's help utility!
...
JavaScript - jQuery way:
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input, textarea")) {
e.preventDefault();
}
});
Javascript - the native way, that works for me:
<script type="text/javascript">
//on backspace down + optional callback
function onBackspace(e, callback){
var key;
if(typeof e.keyIdentifier !== "undefined"){
key = e.keyIdentifier;
}else if(typeof e.keyCode !== "undefined"){
key = e.keyCode;
}
if (key === 'U+0008' ||
key === 'Backspace' ||
key === 8) {
if(typeof callback === "function"){
callback();
}
return true;
}
return false;
}
//event listener
window.addEventListener('keydown', function (e) {
switch(e.target.tagName.toLowerCase()){
case "input":
case "textarea":
break;
case "body":
onBackspace(e,function(){
e.preventDefault();
});
break;
}
}, true);
</script>
You can use cURL and CRON to run .php files at set times.
Here's an example of what cURL needs to run the .php file:
curl http://localhost/myscript.php
Then setup the CRON job to run the above cURL:
nano -w /var/spool/cron/root
or
crontab -e
Followed by:
01 * * * * /usr/bin/curl http://www.yoursite.com/script.php
For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/
For more info about cURL: What is cURL in PHP?
For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800
Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )
NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.
Best of luck with the automatic PHP running :-)
You can also refine Hash::each
so it will support recursive enumeration. Here is my version of Hash::each
(Hash::each_pair
) with block and enumerator support:
module HashRecursive
refine Hash do
def each(recursive=false, &block)
if recursive
Enumerator.new do |yielder|
self.map do |key, value|
value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
yielder << [[key], value]
end
end.entries.each(&block)
else
super(&block)
end
end
alias_method(:each_pair, :each)
end
end
using HashRecursive
Here are usage examples of Hash::each
with and without recursive
flag:
hash = {
:a => {
:b => {
:c => 1,
:d => [2, 3, 4]
},
:e => 5
},
:f => 6
}
p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2
p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6
hash.each do |key, value|
puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6
hash.each(true) do |key, value|
puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6
hash.each_pair(recursive=true) do |key, value|
puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6
Here is example from the question itself:
hash = {
1 => ["a", "b"],
2 => ["c"],
3 => ["a", "d", "f", "g"],
4 => ["q"]
}
hash.each(recursive=false) do |key, value|
puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]
Also take a look at my recursive version of Hash::merge
(Hash::merge!
) here.
it looks like this is the way to do! as simple as that
with this line you are joining together the all text parts within the current element
''.join(htmlelement.find(text=True))
sorted
return a new sorted list from the items in iterable.
CODE
import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print sorted(a)
OUTPUT
[1, 2, 3, 6, 8]
I had a somewhat similar problem where a bounded area consisted of an image in a float:left block and a non-float text block. The area has a fluid width. The text would, by design, wrap up along the right side of the image. The trouble was, the text began with an <h4> tag, the first word of which is the tiny word "From." As I resized the window to a smaller width, the non-floated text would, for a certain range of widths, leave only the word "From" at the top of the wrap area, the rest of the text having been squeezed below the float block. My solution was to make the first word of the tag bigger, by replacing the space that followed it with this code, <span style="opacity:0;">x</span> . The effect was to make the first word, instead of "From", "FromxNextWord", where the "x", being invisible, looked like a space. Now my first word was big enough not to be abandoned by the rest of the text block.
Everything. They're unrelated languages.
You want the background color of your main view to be semi-transparent? There's nothing behind it... so nothing will really happen however:
If you want to modify the alpha of any view, use the alpha property:
UIView *someView = [[UIView alloc] init];
...
someView.alpha = 0.8f; //Sets the opacity to 80%
...
Views themselves have the alpha transparency, not just UIColor.
But since your problem is that you can't read text on top of the images... either:
UIView *overlay = [[[UIView alloc] init] autorelease]; overlay.frame = self.view.bounds; overlay.alpha = 0.2f; [self.view addSubview:overlay]; ... Add the rest of the views
Try adding/editing lower_case_table_names = 2 in my.ini
or my.cnf
This can be achieved by three different approaches (see my blog article here for more details):
Elements
panel like below$x()
and $$()
in Console
panel, as shown in Lawrence's answerHere is how you search XPath in Elements
panel:
Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.
In the command line at the bottom use the following:
$()
: Returns the first element that matches. Equivalent to document.querySelector()
or calls the $
function in the page, if it exists.
$$()
: Returns an array of DOM nodes that match. This is like for document.querySelectorAll()
, but returns an array instead of a NodeList
.
$x()
: Evaluates an XPath expression and returns an array of matching nodes.
To do this cross browser including IE7+, you will need to expand the plugin with a transformation matrix. Since vendor prefix is done in jQuery from jquery-1.8+ I will leave that out for the transform
property.
$.fn.animateRotate = function(endAngle, options, startAngle)
{
return this.each(function()
{
var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
anims = {}, animsEnd = {};
if(typeof options !== 'object')
{
options = {};
}
else if(typeof options.extra === 'object')
{
anims = options.extra;
animsEnd = options.extra;
}
anims.deg = startAngle;
animsEnd.deg = endAngle;
options.step = function(now, fx)
{
if(fx.prop === 'deg')
{
if(noTransform)
{
rad = now * (Math.PI * 2 / 360);
costheta = Math.cos(rad);
sintheta = Math.sin(rad);
matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
$('body').append('Test ' + matrixValues + '<br />');
elem.css({
'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
});
}
else
{
elem.css({
//webkitTransform: 'rotate('+now+'deg)',
//mozTransform: 'rotate('+now+'deg)',
//msTransform: 'rotate('+now+'deg)',
//oTransform: 'rotate('+now+'deg)',
transform: 'rotate('+now+'deg)'
});
}
}
};
if(startAngle)
{
$(anims).animate(animsEnd, options);
}
else
{
elem.animate(animsEnd, options);
}
});
};
Note: The parameters options
and startAngle
are optional, if you only need to set startAngle
use {}
or null
for options
.
Example usage:
var obj = $(document.createElement('div'));
obj.on("click", function(){
obj.stop().animateRotate(180, {
duration: 250,
complete: function()
{
obj.animateRotate(0, {
duration: 250
});
}
});
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);
See also this jsfiddle for a demo.
Update: You can now also pass extra: {}
in the options. This will make you able to execute other animations simultaneously. For example:
obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});
This will rotate the element 90 degrees, and move it to the right with 100px and make it semi-transparent all at the same time during the animation.
preg_replace('/[\s]+/mu', ' ', $var);
\s
already contains tabs and new lines, so this above regex appears to be sufficient.
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
I did it in a easier way , setEditable and setFocusable false. but you should check this.
I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.
A simple:
int* a;
class foo{
foo(){
for(i=0;i<n;i++)
a=new int[i];
}
Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
int total = monValues.Sum(x => Convert.ToInt32(x));
I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.
$("#Friends").animate( {top:
"-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );
Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.
https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive
Thank you.
This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#
I use AlertifyJS to style my dialogues.
alertify.alert('Ready!');_x000D_
alertify.YoutubeDialog || alertify.dialog('YoutubeDialog',function(){_x000D_
var iframe;_x000D_
return {_x000D_
// dialog constructor function, this will be called when the user calls alertify.YoutubeDialog(videoId)_x000D_
main:function(videoId){_x000D_
//set the videoId setting and return current instance for chaining._x000D_
return this.set({ _x000D_
'videoId': videoId_x000D_
});_x000D_
},_x000D_
// we only want to override two options (padding and overflow)._x000D_
setup:function(){_x000D_
return {_x000D_
options:{_x000D_
//disable both padding and overflow control._x000D_
padding : !1,_x000D_
overflow: !1,_x000D_
}_x000D_
};_x000D_
},_x000D_
// This will be called once the DOM is ready and will never be invoked again._x000D_
// Here we create the iframe to embed the video._x000D_
build:function(){ _x000D_
// create the iframe element_x000D_
iframe = document.createElement('iframe');_x000D_
iframe.frameBorder = "no";_x000D_
iframe.width = "100%";_x000D_
iframe.height = "100%";_x000D_
// add it to the dialog_x000D_
this.elements.content.appendChild(iframe);_x000D_
_x000D_
//give the dialog initial height (half the screen height)._x000D_
this.elements.body.style.minHeight = screen.height * .5 + 'px';_x000D_
},_x000D_
// dialog custom settings_x000D_
settings:{_x000D_
videoId:undefined_x000D_
},_x000D_
// listen and respond to changes in dialog settings._x000D_
settingUpdated:function(key, oldValue, newValue){_x000D_
switch(key){_x000D_
case 'videoId':_x000D_
iframe.src = "https://www.youtube.com/embed/" + newValue + "?enablejsapi=1";_x000D_
break; _x000D_
}_x000D_
},_x000D_
// listen to internal dialog events._x000D_
hooks:{_x000D_
// triggered when the dialog is closed, this is seperate from user defined onclose_x000D_
onclose: function(){_x000D_
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');_x000D_
},_x000D_
// triggered when a dialog option gets update._x000D_
// warning! this will not be triggered for settings updates._x000D_
onupdate: function(option,oldValue, newValue){_x000D_
switch(option){_x000D_
case 'resizable':_x000D_
if(newValue){_x000D_
this.elements.content.removeAttribute('style');_x000D_
iframe && iframe.removeAttribute('style');_x000D_
}else{_x000D_
this.elements.content.style.minHeight = 'inherit';_x000D_
iframe && (iframe.style.minHeight = 'inherit');_x000D_
}_x000D_
break; _x000D_
} _x000D_
}_x000D_
}_x000D_
};_x000D_
});_x000D_
//show the dialog_x000D_
alertify.YoutubeDialog('GODhPuM5cEE').set({frameless:true});
_x000D_
<!-- JavaScript -->_x000D_
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>_x000D_
<!-- CSS -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.rtl.min.css"/>
_x000D_
Yes - just explicitly provide the path to java.exe. For instance:
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
The easiest way to do this for a running command shell is something like:
set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
For example, here's a complete session showing my default JVM, then the change to the path, then the new one:
c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
This won't change programs which explicitly use JAVA_HOME though.
Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.
For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.targetFunction();
...
}
...
Constructor looks like a method but name should be as class name and no return value.
Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding. Super class name and Sub class names are different.
If you trying to write Super class Constructor in Sub class, then Sub class will treat that as a method not constructor because name should not match with Sub class name. And it will give an compilation error that methods does not have return value. So we should declare as void, then only it will compile.
In ksh
,bash
,sh
:
$ count7=0
$ count1=5
$
$ (( count7 += count1 ))
$ echo $count7
$ 5
Create 2 methods which handle the cases. You can instruct the @RequestMapping
annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.
@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET,
produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id,
@RequestParam("logout") String logout) { ... }
@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET,
produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name")
String username, @RequestParam("password") String password,
@ModelAttribute("submitModel") SubmitModel model, BindingResult errors)
throws LoginException {...}
This launches the Scheduled Tasks MMC Control Panel:
%SystemRoot%\system32\taskschd.msc /s
Older versions of windows had a splash screen for the MMC control panel and the /s switch would supress it. It's not needed but doesn't hurt either.
It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app
Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/
Yet another answer (in January 2018) to the old question (in January 2009).
The specification of Java properties file is described in the JavaDoc of java.util.Properties.load(java.io.Reader)
. One problem is that the specification is a bit complicated than the first impression we may have. Another problem is that some answers here arbitrarily added extra specifications - for example, ;
and '
are regarded as starters of comment lines but they should not be. Double/single quotations around property values are removed but they should not be.
The following are points to be considered.
\n
, \r
, \r\n
or the end of the stream.\
.
, \u0020
), tab (\t
, \u0009
) and form feed (\f
, \u000C
).=
is used as the separator between a key and a value.:
is used as the separator between a key and a value, too.#
or !
as its first non-white space characters, meaning leading white spaces before #
or !
are allowed.\
.=
, :
and white spaces can be embedded in a key if they are escaped by backslashes.\r
and \n
escape sequences.\uxxxx
is used to represent a Unicode character.So, for example, if test.properties
has the following content:
# A comment line that starts with '#'.
# This is a comment line having leading white spaces.
! A comment line that starts with '!'.
key1=value1
key2 : value2
key3 value3
key\
4=value\
4
\u006B\u0065\u00795=\u0076\u0061\u006c\u0075\u00655
\k\e\y\6=\v\a\lu\e\6
\:\ \= = \\colon\\space\\equal
it should be interpreted as the following key-value pairs.
+------+--------------------+
| KEY | VALUE |
+------+--------------------+
| key1 | value1 |
| key2 | value2 |
| key3 | value3 |
| key4 | value4 |
| key5 | value5 |
| key6 | value6 |
| : = | \colon\space\equal |
+------+--------------------+
PropertiesLoader
class in Authlete.Authlete NuGet package can interpret the format of the specification. The example code below:
using System;
using System.IO;
using System.Collections.Generic;
using Authlete.Util;
namespace MyApp
{
class Program
{
public static void Main(string[] args)
{
string file = "test.properties";
IDictionary<string, string> properties;
using (TextReader reader = new StreamReader(file))
{
properties = PropertiesLoader.Load(reader);
}
foreach (var entry in properties)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
}
}
}
will generate this output:
key1 = value1
key2 = value2
key3 = value3
key4 = value4
key5 = value5
key6 = value6
: = = \colon\space\equal
An equivalent example in Java is as follows:
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String file = "test.properties";
Properties properties = new Properties();
try (Reader reader = new FileReader(file))
{
properties.load(reader);
}
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
System.out.format("%s = %s\n", entry.getKey(), entry.getValue());
}
}
}
The source code, PropertiesLoader.cs
, can be found in authlete-csharp. xUnit tests for PropertiesLoader
are written in PropertiesLoaderTest.cs
.
Your project should almost always use the past tense. In any case, the project should always use the same tense for consistency and clarity.
I understand some of the other arguments arguing to use the present tense, but they usually don't apply. The following bullet points are common arguments for writing in the present tense, and my response.
This is the most correct reason one would want to use the present tense, but only with the right style of project. This manner of thinking considers all commits as optional improvements or features, and you are free to decide which commits to keep and which to reject in your particular repository.
This argument works if you are dealing with a truly distributed project. If you are dealing with a distributed project, you are probably working on an open source project. And it is probably a very large project if it is really distributed. In fact, it's probably either the Linux kernel or Git. Since Linux is likely what caused Git to spread and gain in popularity, it's easy to understand why people would consider its style the authority. Yes, the style makes sense with those two projects. Or, in general, it works with large, open source, distributed projects.
That being said, most projects in source control do not work like this. It is usually incorrect for most repositories. It's a modern way of thinking about a commits: Subversion (SVN) and CVS repositories could barely support this style of repository check-ins. Usually an integration branch handled filtering bad check-ins, but those generally weren't considered "optional" or "nice-to-have features".
In most scenarios, when you are making commits to a source repository, you are writing a journal entry which describes what changed with this update, to make it easier for others in the future to understand why a change was made. It generally isn't an optional change - other people in the project are required to either merge or rebase on it. You don't write a diary entry such as "Dear diary, today I meet a boy and he says hello to me.", but instead you write "I met a boy and he said hello to me."
Finally, for such non-distributed projects, 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository.
No, I guarantee you that the majority of projects ever logged in a version control system have had their history in the past tense (I don't have references, but it's probably right, considering the present tense argument is new since Git). "Revision" messages or commit messages in the present tense only started making sense in truly distributed projects - see the first point above.
See the first point. 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository. 99.99% beats 0.01%.
I've never seen a good argument that says use improper tense/grammar because it's shorter. You'll probably only save 3 characters on average for a standard 50 character message. That being said, the present tense on average will probably be a few characters shorter.
Tickets are written as either something that is currently happening (e.g. the app is showing the wrong behavior when I click this button), or something that needs to be done in the future (e.g. the text will need a review by the editor).
History (i.e. commit messages) is written as something that was done in the past (e.g. the problem was fixed).
All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time
<input type="submit" name="Submit_this" id="This" />
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
I changed the memory limit from .htaccess and this problem got resolved.
I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:
php_value memory_limit 512M
After scan was over, I removed this line to make the size as it was before.
1 - remove the margin from your BODY CSS.
2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>
3 - Define the CSS for the wrapper:
This will hold everything together, centered on the page.
#wrapper {
margin-left:auto;
margin-right:auto;
width:960px;
}
There is restriction on using --jars
: if you want to specify a directory for location of jar/xml
file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.
If you specify --driver-class-path
and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.
Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf
option. It's better to pass driver and executor class paths as --conf
, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.
spark-submit \
--master yarn \
--queue spark_queue \
--deploy-mode cluster \
--num-executors 12 \
--executor-memory 4g \
--driver-memory 8g \
--executor-cores 4 \
--conf spark.ui.enabled=False \
--conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapred.output.dir=/tmp \
--conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Yes, you can do almost that:
SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...
$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p));
for dynamic merging of cells
jQuery has the inArray
function:
on RHEL 7:
sudo yum install yum-utils mariadb-devel python-pip python-devel gcc
sudo /bin/pip2 install MySQL-python
Yes. You can have a span
within a span
. Your problem stems from something else.
There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.
I make use of both in this fashion:
iOS Safari has a feature that allows you to add a "smart" banner to your webpage that will link either to your app, if it is installed, or to the App Store.
You do this by adding a meta
tag to the page. You can even specify a detailed app URL if you want the app to do something special when it loads.
Details are at Apple's Promoting Apps with Smart App Banners page.
The mechanism has the advantages of being easy and presenting a standardized banner. The downside is that you don't have much control over the look or location. Also, all bets are off if the page is viewed in a browser other than Safari.
I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status
command Git Shell suggested to push changes as
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
I did the same as Git Shell suggested (git push
) and everything is ok now.
Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.
fatal: Not a git repository (or any of the parent directories):
For example if your Project is in D
drive in some folder you have to do something like below as you do in cmd
to change directory.
cd D:\someFolder // if your project is not deep in `D`
And if its within nested folder in D
cd D:\somefolder\someNestedFolder\nestedInNested // if your project is not deep in `D`
If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.
string s2 = s1.Replace(",", "," + Environment.NewLine);
Also, just from a performance perspective, here's how the three current solutions I've seen stack up over 100k iterations:
ReplaceWithConstant - Ms: 328, Ticks: 810908
ReplaceWithEnvironmentNewLine - Ms: 310, Ticks: 766955
SplitJoin - Ms: 483, Ticks: 1192545
ReplaceWithConstant:
string s2 = s1.Replace(",", ",\n");
ReplaceWithEnvironmentNewLine:
string s2 = s1.Replace(",", "," + Environment.NewLine);
SplitJoin:
string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
ReplaceWithEnvironmentNewLine and ReplaceWithConstant are within the margin of error of each other, so there's functionally no difference.
Using Environment.NewLine
should be preferred over "\n"
for the sake readability and consistency similar to using String.Empty
instead of ""
.
For enum type, I think this is a suitable way, and the difference between class is how to calculate hash value.
template <typename T>
struct EnumTypeHash {
std::size_t operator()(const T& type) const {
return static_cast<std::size_t>(type);
}
};
enum MyEnum {};
class MyValue {};
std::unordered_map<MyEnum, MyValue, EnumTypeHash<MyEnum>> map_;
use for loop. like this:
for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
new_list.append(my_list[i + x])
Use this script instead:
@taskkill/f /im test.exe >nul 2>&1
@pause
What the 2>&1
part actually does, is that it redirects the stderr
output to stdout
. I will explain it better below:
Kill the task "test.exe". Redirect stderr
to stdout
. Then, redirect stdout
to nul
.
Show the pause message Press any key to continue . . .
until someone presses a key.
NOTE: The @
symbol is hiding the prompt for each command. You can save up to 8 bytes this way.
The shortest version of your script could be:
@taskkill/f /im test.exe >nul 2>&1&pause
The &
character is used for redirection the first time, and for separating the commands the second time.
An @
character is not needed twice in a line. This code is just 40 bytes, despite the one you've posted being 49 bytes! I actually saved 9 bytes. For a cleaner code look above.
@sfjedi
I've created a class and assigned the css values to it.
.radioA{
vertical-align: middle;
}
It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.
You can either use regex, or keep on using str_replace
.
Eg.
$url = parse_url($_SERVER['REQUEST_URI']);
if ($url != '/') {
parse_str($url['query']);
echo $id;
echo $othervar;
}
Output will be: http://www.testing.com/123/123
Daniel answer is right on the spot. If you want to query more than one field do this:
Employee.objects.values_list('eng_name','rank')
This will return list of tuples. You cannot use named=Ture when querying more than one field.
Moreover if you know that only one field exists with that info and you know the pk id then do this:
Employee.objects.values_list('eng_name','rank').get(pk=1)
/(["\']).*?(?<!\\)(\\\\)*\1/is
should work with any quoted string
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
Just use the following method, pass it lat and long and get distance in meter:
private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
double R = 6371000f; // Radius of the earth in m
double dLat = (lat1 - lat2) * Math.PI / 180f;
double dLon = (lon1 - lon2) * Math.PI / 180f;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
return d;
}
Look at the "Sprite Text" sample in the GLSurfaceView samples.
Anyway, we have a "goes to" operator now. "-->"
is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.
Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)"
on some platforms.
MERGE INTO OPT
USING
(SELECT 1 "one" FROM dual)
ON
(OPT.email= '[email protected]' and OPT.campaign_id= 100)
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100)
;
Edit: 3 years has passed since I answered this question and I guess a more modern solution is needed, although the current one does the thing :)
1.Flexbox
It's by far the shortest and most flexible. Apply display: flex;
to the parent container and adjust the placement of its children by justify-content: space-between;
like this:
.header {
display: flex;
justify-content: space-between;
}
Can be seen online here - http://jsfiddle.net/skip405/NfeVh/1073/
Note however that flexbox support is IE10 and newer. If you need to support IE 9 or older, use the following solution:
2.You can use the text-align: justify
technique here.
.header {
background: #ccc;
text-align: justify;
/* ie 7*/
*width: 100%;
*-ms-text-justify: distribute-all-lines;
*text-justify: distribute-all-lines;
}
.header:after{
content: '';
display: inline-block;
width: 100%;
height: 0;
font-size:0;
line-height:0;
}
h1 {
display: inline-block;
margin-top: 0.321em;
/* ie 7*/
*display: inline;
*zoom: 1;
*text-align: left;
}
.nav {
display: inline-block;
vertical-align: baseline;
/* ie 7*/
*display: inline;
*zoom:1;
*text-align: right;
}
The working example can be seen here: http://jsfiddle.net/skip405/NfeVh/4/. This code works from IE7 and above
If inline-block elements in HTML are not separated with space, this solution won't work - see example http://jsfiddle.net/NfeVh/1408/ . This might be a case when you insert content with Javascript.
If we don't care about IE7 simply omit the star-hack properties. The working example using your markup is here - http://jsfiddle.net/skip405/NfeVh/5/. I just added the header:after
part and justified the content.
In order to solve the issue of the extra space that is inserted with the after
pseudo-element one can do a trick of setting the font-size
to 0 for the parent element and resetting it back to say 14px for the child elements. The working example of this trick can be seen here: http://jsfiddle.net/skip405/NfeVh/326/
The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.
This answer adds to the solutions above to address your last sentence that reads:
how do I ensure that sub-left and sub-right stay within sub-title
The problem is that as the content of sub-left or sub-right expands they will extend below sub-title. This behaviour is designed into CSS but does cause problems for most of us. The easiest solution is to have a div that is styled with the CSS Clear declaration.
To do this include a CSS statement to define a closing div (can be Clear Left or RIght rather than both, depending on what Float declarations have been used:
#sub_close {clear:both;}
And the HTML becomes:
<div id="sub-title">
<div id="sub-left">Right</div>
<div id="sub-right">Left</div>
<div id="sub-close"></div>
</div>
Sorry, just realized this was posted previously, shouldn't have made that cup of coffee while typing my reply!
@Darko Z: you are right, the best description for the overflow:auto (or overflow:hidden) solution that I have found was in a a post on SitePoint a while ago Simple Clearing of FLoats and there is also a good description in a 456bereastreet article CSS Tips and Tricks Part-2. Have to admit to being too lazy to implement these solutions myself, as the closing div cludge works OK although it is of course very inelegant. So will make an effort from now on to clean up my act.
Hello Googlers from the future.
On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.
Using ssh-add -K
no longer survives restarts as well.
Here are 3 possible solutions.
I've used the first method successfully. I've created a file called config
in ~/.ssh
:
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
You're doing things in the wrong order.
You need to first add all JComponents to the JFrame, and only then call pack()
and then setVisible(true)
on the JFrame
If you later added JComponents that could change the GUI's size you will need to call pack()
again, and then repaint()
on the JFrame after doing so.
With __future__
module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do from __future__ import with_statement
in 2.5, as the with
keyword was new and shouldn't be used as variable names any longer. In order to use with
as a Python keyword in Python 2.5 or older, you will need to use the import from above.
Another example is
from __future__ import division
print 8/7 # prints 1.1428571428571428
print 8//7 # prints 1
Without the __future__
stuff, both print
statements would print 1
.
The internal difference is that without that import, /
is mapped to the __div__()
method, while with it, __truediv__()
is used. (In any case, //
calls __floordiv__()
.)
Apropos print
: print
becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.
>>> print
>>> from __future__ import print_function
>>> print
<built-in function print>
>>>
To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:
$('#id-of-the-button').click(function() {document.forms[0].submit()});
Which assumes you just have the one form on the page.
From the api on GridLayout:
The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).
JPanel displayPanel = new JPanel();
// JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
// JPanel displayPanel = new JPanel( new BorderLayout() );
// JPanel displayPanel = new JPanel( new GridBagLayout() );
JTextField titleText = new JTextField( "title" );
titleText.setPreferredSize( new Dimension( 200, 24 ) );
// For FlowLayout and GridLayout, uncomment:
displayPanel.add( titleText );
// For BorderLayout, uncomment:
// displayPanel.add( titleText, BorderLayout.NORTH );
// For GridBagLayout, uncomment:
// displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
// 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
// new Insets( 0, 0, 0, 0 ), 0, 0 ) );
Use the insert method of the combobox to insert the "Please select item" in to 0 index,
comboBox1.Items.Insert(0, "Please select any value");
and add all the items to the combobox after the first index. In the form load set
comboBox1.SelectedIndex = 0;
EDIT:
In form load write the text in to the comboBox1.Text
by hardcoding
comboBox1.Text = "Please, select any value";
and in the TextChanged event of the comboBox1 write the following code
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex < 0)
{
comboBox1.Text = "Please, select any value";
}
else
{
comboBox1.Text = comboBox1.SelectedText;
}
}
var y = $(window).scrollTop(); //your current y position on the page
$(window).scrollTop(y+150);
"await is only valid in async function"
But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.
In the viewDidLoad
method of the presenting controller add:
// hide navigation bar title in the next controller
let backButton = UIBarButtonItem(title: "", style:.Plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
Use jFeed - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});
This should work:
$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`
So the length is between 10 16-bit chars, and 40 hex digits.
In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.
In my case, my dataframe has the following characteristics
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
The first option data.index = pd.to_datetime(data.index)
returned
ParserError: String does not contain a date: ParserError: String does not contain a date:
The second option: data.index.to_datetime()
returned
AttributeError: 'Index' object has no attribute 'to_datetime'
It returned
Another option I have tested is. data.index = pd.to_datetime(data.index)
It returned: ParserError: String does not contain a date:
What could be my problem? Thanks
use ng-bind-html-unsafe
it will apply html with text inside like below:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'
It also allows the placeholder to depend on the instance for ModelForms with instance specified.
another option, that uses delegates and the Thread Pool...
assuming 'GetEnergyUsage' is a method that takes a DateTime and another DateTime as input arguments, and returns an Int...
// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime,
DateTime procDateTime);
// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);
Set the colspan
attribute to 2.
There is a browser-based implementation of VSC that allows you to run it on a browser on your Android (or any other) device. Check it out here:
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.
However if you want to be sure of what just happened, just type
git status
and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.
Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book
I had the same problem. For some reason --initialize
did not work.
After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.
I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:
https://bugs.mysql.com/bug.php?id=28913
In short words: Add the following line to your my.ini:
innodb_flush_method=normal
I had this problem with mysql 5.7 on Windows.
Make sure you choose the right project intepreter in the compiler. I used the Pycharm, and I encountered the same problem. And it was solved by choose the right intepreter. Thisvideo may help you.
Given a list of dates dates
:
Max date is max(dates)
Min date is min(dates)
If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.
However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.
You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.
A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.
You can find more details in the Testing help section of the on-line documentation.
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
If you want to add your menu custom
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_custom, menu);
}
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
You are trying to concatenate a string and an integer.
You need to cast @ID
as a string.
try:
SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))
For me, this is the clearest and most intuitive:
values = []
for action in ['Sell','Buy']:
amounts = orders_df['Amounts'][orders_df['Action'==action]].values
if action == 'Sell':
prices = orders_df['Prices'][orders_df['Action'==action]].values
else:
prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
values += list(amounts*prices)
orders_df['Values'] = values
The .values
method returns a numpy array
allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.
The only solution which works for me on Visual Studio 2013 in a WEB project:
Lets say I want to rename "project1" to be "project2". Lets say the physical path to my .sln file is: c:\my\path\project1\project1.sln
so the path to my .csproj file as well as the bin and the obj folders should be: c:\my\path\project1\project1\
Open the solution in VS by double clicking the project1.sln file.
In Solution Explorer, right-click the project (NOT the solution!!!), select Rename, and enter a new name.
In Solution Explorer, right-click the project and select Properties. On the Application tab, change the "Assembly name" and "Default namespace".
In the main CS file (or any other code files like Global.asax for example), rename the namespace declaration to use the new name. For this right-click the namespace and select Refactor > Rename enter a new name. For example:
namespace project1
4.1 In Solution Explorer, right-click the project (NOT the solution!!!), select Rename, and enter a new name.
1 [assembly: AssemblyTitle("New Name Here")] 2 [assembly: AssemblyDescription("")] 3 [assembly: AssemblyConfiguration("")] 4 [assembly: AssemblyCompany("")] 5 [assembly: AssemblyProduct("New Name Here")] 6 [assembly: AssemblyCopyright("Copyright © 2013")] 7 [assembly: AssemblyTrademark("")] 8 [assembly: AssemblyCulture("")]
Close the Visual Studio.
Delete bin and obj directories physically.
Rename the parent folder and the source folder to the new name (project2):
In the example: c:\my\path\project1\project1
will be: c:\my\path\project2\project2
Rename the SLN file name by right click on that SLN file forward by Rename.
Then finally open the SLN file (within notepad or any editor) and copy and replace (Ctrl+h) any old name to the new name.
Open VS and click BUILD -> Clean Solution
click Build -> Build solution and then F5 to run...
Note1: If you get something like this: Compilation Error CS0246: The type or namespace name 'project2' could not be found (are you missing a using directive or an assembly reference?)
Source File: c:\Users\Username\AppData\Local\Temp\Temporary ASP.NET Files\root\78dd917f\d0836ce4\App_Web_index.cshtml.a8d08dba.b0mwjmih.0.cs
Then go to the "Temporary ASP.NET Files" folder and delete everything.
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
Here you can do it by using HttpRequest
or HttpSession
. And think your problem is within the JSP.
If you are going to use the inside servlet do following,
Object obj = new Object();
session.setAttribute("object", obj);
or
HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);
and after setting your attribute by using request or session, use following to access it in the JSP,
<%= request.getAttribute("object")%>
or
<%= session.getAttribute("object")%>
So seems your problem is in the JSP.
If you want use scriptlets it should be as follows,
<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>
Or can use expressions as follows,
<%= session.getAttribute("object")%>
or can use EL as follows,
${object}
or ${sessionScope.object}
You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny
Taking the answer above as guidance;
I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.
Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.
The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.
Thanks to the guy above for the idea!
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:
ALTER USER user SET search_path to 'name_of_schema';
after these changes "INSERT" will work correctly.
First, I'd make sure that this really is a performance bottleneck, otherwise I'd go with the solution that is cleanest and most expressive.
If it IS a performance bottleneck, just try the different strategies and see what's the quickest. My bet is on creating a new ArrayList and puting the desired objects in that one, discarding the old ArrayList.
This usually happened if you haven't stopped docker probably.
To resolve
service docker stop
cd /var/run/docker/libcontainerd
rm -rf containerd/*
rm -f docker-containerd.pid
service docker start
then "docker run...." to download your image and start the container as usual
It looks like you just want:
eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
? (DateTime?) null
: DateTime.Parse(dateTimeEnd);
Note that this will throw an exception if dateTimeEnd
isn't a valid date.
An alternative would be:
DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
? validValue
: (DateTime?) null;
That will now set the result to null
if dateTimeEnd
isn't valid. Note that TryParse
handles null
as an input with no problems.
just put your script in a file and run that file with 2>/dev/null at the end of command line!
This way, if there is a problem with the command whatsoever, it will not halt your xcode build
in my case I was running just a command to uninstall my previous copy of the app from a connected iphone, so it could give an error if the iphone is not there. To solve it:
$mobiledevice uninstall_app com.my.app 2>/dev/null
@property (nonatomic, copy) void (^simpleBlock)(void);
@property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);
If you are going to be repeating the same block in several places use a type def
typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
@property (nonatomic) MyCompletionBlock completion;
You can't. It's not a trusted event.
Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.
Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.
You have to add a class and add/remove that on the mouseover/mouseout events manually.
Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.
In ECMAScript 6 it's more or less possible by wrapping the code inside a with
statement with a proxy object. Note it requires non-strict mode and it's bad practice.
function storeVars(target) {_x000D_
return new Proxy(target, {_x000D_
has(target, prop) { return true; },_x000D_
get(target, prop) { return (prop in target ? target : window)[prop]; }_x000D_
});_x000D_
}_x000D_
var vars = {}; // Outer variable, not stored._x000D_
with(storeVars(vars)) {_x000D_
var a = 1; // Stored in vars_x000D_
var b = 2; // Stored in vars_x000D_
(function() {_x000D_
var c = 3; // Inner variable, not stored._x000D_
})();_x000D_
}_x000D_
console.log(vars);
_x000D_
The proxy claims to own all identifiers referenced inside with
, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let
and const
variables are not included.
Inspired by this answer by Bergi.
I recently discovered the rather useful sweep
function and add it here for the sake of completeness:
sweep
The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):
Let's say you have a matrix and want to standardize it column-wise:
dataPoints <- matrix(4:15, nrow = 4)
# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)
# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)
# Center the points
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")
# Return the result
dataPoints_Trans1
## [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,] 0.5 0.5 0.5
## [4,] 1.5 1.5 1.5
# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")
# Return the result
dataPoints_Trans2
## [,1] [,2] [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,] 0.3872983 0.3872983 0.3872983
## [4,] 1.1618950 1.1618950 1.1618950
NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)
simply run following on terminal if you don't have pip installed on your mac.
sudo easy_install pip
download python 3 here: python3
once you're done with these 2 steps, make sure to run the following to verify whether you've installed them successfully.
python3 --version
pip3 --version
My solution was uninstalling and installing the PHP instance (7.0 in my case) again:
sudo apt-get purge php7.0
sudo apt-get install php7.0
After that you will need to restart the Apache service:
sudo service apache2 restart
Finally, verify again in your browser with your localhost or IP address.
You can make method which return the datatable of given sql query:
public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
and now can be used like this:
table = GetDataTable();
Can't you put the variables in a higher scope?
(function () {
var privateVariable = true;
var MyClass = function () {
if (privateVariable) console.log('readable from private scope!');
};
MyClass.prototype.publicMethod = function () {
if (privateVariable) console.log('readable from public scope!');
};
}))();
The error is caused by the "smart-quotes" (or whatever they're called). The lesson here is, "don't write your code in an 'editor' that converts quotes to smart-quotes".
names(newprice)[1]<-paste(“premium”) # error
names(newprice)[1]<-paste("premium") # works
Also, you don't need paste("premium")
(the call to paste
is redundant) and it's a good idea to put spaces around <-
to avoid confusion (e.g. x <- -10; if(x<-3) "hi" else "bye"; x
).
You can use either [[
or ((
keyword. When you use [[
keyword, you have to use string operators such as -eq
, -lt
. I think, ((
is most preferred for arithmetic, because you can directly use operators such as ==
, <
and >
.
Using [[
operator
a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
echo "Error"
else
echo "No Error"
fi
Using ((
operator
a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
echo "Error"
else
echo "No Error"
fi
Do not use -a
or -o
operators Since it is not Portable.
SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{your_db}';
Note from the docs though: For InnoDB tables, the row count is only a rough estimate used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).
You are absolutely correct in that respect. In small trivial programs where a variable must exist until the death of the program, there is no real benefit to deallocating the memory.
In fact, I had once been involved in a project where each execution of the program was very complex but relatively short-lived, and the decision was to just keep memory allocated and not destabilize the project by making mistakes deallocating it.
That being said, in most programs this is not really an option, or it can lead you to run out of memory.
Try
$waffles = foo($waffles);
Or pass the array by reference, like suggested in the other answers.
In addition, you can add new elements to an array without writing the index, e.g.
$waffles = array(1,2,3); // filling on initialization
or
$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;
On a sidenote, if you want to sum all values in an array, use array_sum()
Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include
statement so the preprocessor finds it where it already is.
Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.
Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...
<some folder>\xyz.h
<some folder>\code\xyz.cxx
In that case the #include statement in xyz.cxx should look something like this..
#include "..\xyz.h"
On the other hand let's say your file structure looks like this...
<some folder>\include\xyz.h
<some folder>\code\xyz.cxx
In that case the #include statement in xyz.cxx should look something like this..
#include "..\include\xyz.h"
Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h>
you should probably change it to #include "xyz.h"
Just to extend the accepted answer:
From version 2.7
and 3.1
python has got set
literal {}
in form of usage {1,2,3}
, but {}
itself still used for empty dict.
Python 2.7 (first line is invalid in Python <2.7)
>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>
Python 3.x
>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>
More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes
One reason for using pointers is to interface with C functions. Another reason is to save memory; for example: instead of passing an object which contains a lot of data and has a processor-intensive copy-constructor to a function, just pass a pointer to the object, saving memory and speed especially if you're in a loop, however a reference would be better in that case, unless you're using an C-style array.
Make the list a character vector (not a vector of names)
rm(list = c('temp1','temp2'))
or
rm(temp1, temp2)
I am implementing old http (0.9, 1.0, 1.1) request and response reader/writer. Request URI is the most problematic place.
You can't just use RFC 1738, 2396 or 3986 as it is. There are many old HTTP clients and servers that allows more characters. So I've made research based on accidentally published webserver access logs: "GET URI HTTP/1.0" 200
.
I've found that the following non-standard characters are often used in URI:
\ { } < > | ` ^ "
These characters were described in RFC 1738 as unsafe.
If you want to be compatible with all old HTTP clients and servers - you have to allow these characters in request URI.
Please read more information about this research in oghttp-request-collector.
Check your project's properties. On the "Application" tab, select your Program
class as the Startup object:
If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:
# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log
# Send both stdout and stderr to out.log
myprogram &> out.log # New bash syntax
myprogram > out.log 2>&1 # Older sh syntax
# Log output, hide errors.
myprogram > out.log 2> /dev/null
Check out the pack URI syntax. You want something like this:
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
Yes, see the following from String Resources: Formatting and Styling
If you need to format your strings using
String.format(String, Object...)
, then you can do so by putting your format arguments in the string resource. For example, with the following resource:<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal number. You can format the string with arguments from your application like this:Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Note that getString
has an overload that uses the string as a format string:
String text = res.getString(R.string.welcome_messages, username, mailCount);
If you need to handle plurals, use this:
<plurals name="welcome_messages">
<item quantity="one">Hello, %1$s! You have a new message.</item>
<item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>
The first mailCount
param is used to decide which format to use (single or plural), the other params are your substitutions:
Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);
See String Resources: Plurals for more details.
One minor update, you should change the checks for "if errorlevel 1" to the following...
IF %ERRORLEVEL% NEQ 0
This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.
And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.
Worked example for a specific case:
Let's say you have my-module that you're sharing via npm.
You install it with npm install my-module
You use it thus:
import * as lol from 'my-module';
const a = lol('abc', 'def');
The module's logic is all in index.js
:
module.exports = function(firstString, secondString) {
// your code
return result
}
To add typings, create a file index.d.ts
:
declare module 'my-module' {
export default function anyName(arg1: string, arg2: string): MyResponse;
}
interface MyResponse {
something: number;
anything: number;
}
To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9
Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/
It is very straight forward
HTML
<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>
jQuery
$(document).ready(function(){
$('.button').css( 'cursor', 'pointer' );
// for old IE browsers
$('.button').css( 'cursor', 'hand' );
});
I just had to dig through this issue myself and succeeded. Contrary to what others have offered as solutions, the path to my happy ending was directly correlated to JavaDoc. No "src.zip" files necessary. My trials and tribulations in the process involved finding the CORRECT JavaDoc to point at. Pointing a Java 1.7 project at Java 8 Javadoc does NOT work. (Even if "jre8" appears to be the only installed JRE available.) Thus, I beat my head against the brick wall unnecessarily.
Window > Preferences > Java > Installed JREs
If the JRE of your project is not listed (as happened to me when I migrated a jre7 project to a new jre8 workspace), you will need to add it here. Click "Add..." and point your Workspace at the desired jre folder. (Mine was C://Program Files/Java/jre7). Then "Edit..." the now-available JRE, select the rt.jar, and click "Javadoc Location..." and aim it at the correct javadoc location. For my use:
For jre7 -- http://docs.oracle.com/javase/7/docs/api/ For jre8 -- http://docs.oracle.com/javase/8/docs/api/
Voila, hover tooltip javadoc is re-enabled. I hope this helps anyone else trying to figure this problem out.
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+
<img src="'../images/foo.gif'"
alt="line 1
line 2" title="line 1
line 2">
Try a JavaScript tooltip library for a better result, something like OverLib.
A few ways:
-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)
-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END
Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.
If you ever want to know exactly what a reserved function does in python, type in help(enter_keyword)
Make sure if you are entering a reserved keyword that you enter it as a string.
Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:
$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;
The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
The way i usually do it is by embedding a Row inside the Raised button:
class Sendbutton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {},
color: Colors.black,
textColor: Colors.white,
child: Row(
children: <Widget>[
Text('Send'),
Icon(Icons.send)
],
),
);
}
}
did you try something like
for o : AnyObject in self.subviews {
if let v = o as? NSView {
v.removeFromSuperview()
}
}
You can do this by creating a constraint and connecting it via interface builder
See explanation: Auto_Layout_Constraints_in_Interface_Builder
raywenderlich beginning-auto-layout
AutolayoutPG Articles constraint Fundamentals
@interface ViewController : UIViewController {
IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this
self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign
I hope this clarifies it.
Just for completeness: You can pass slice
a vector of indices:
df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))
which gives
id stopId stopSequence
1 1 a 1
2 1 c 3
3 2 b 1
4 2 c 4
5 3 b 1
6 3 a 3
In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.
git rebase -i origin/master
Then, your commits will appear:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments
Select the commit you want to reword and save.
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments
Now, you have the opportunity to add header and body, where the first line will be the header.
Create perpetuum mobile
Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.
At times it is quite handy to get the auto increment primary key (id
) of the row if it exists and 0
if it doesn't.
Here's how this can be done in a single query:
SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...
You can use git log to display the diffs while searching:
git log -p -- path/to/file
It seems when even using a "valid" custom window name (not _blank, etc.) using window.open to launch a new window, there is still issues. It works fine the first time you click the link, but if you click it again (with the first launched window still up) you receive an "Error: No such interface supported" script debug.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
Drag the variable from Variables pane to Watch pane and voila!
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;
set the wrapper to height 100%
.vwrapper {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 100%;
}
and set the 3rd row to flex-grow
#row3 {
background-color: green;
flex: 1 1 auto;
display: flex;
}
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
My script:
echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings
Output:
WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:
On my bash script I was getting mad as you until I've just tried:
echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"
Just hit enter where you want to insert that jump. Output now is:
WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
Now that we have Java 8/streams, we can add one more possible answer to the list:
Assuming that each of the values actually are String
objects, the cast to String
should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.
Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
The best way to resolve this task is (similar with PHP trim
function):
function trim( str, charlist ) {_x000D_
if ( typeof charlist == 'undefined' ) {_x000D_
charlist = '\\s';_x000D_
}_x000D_
_x000D_
var pattern = '^[' + charlist + ']*(.*?)[' + charlist + ']*$';_x000D_
_x000D_
return str.replace( new RegExp( pattern ) , '$1' )_x000D_
}_x000D_
_x000D_
document.getElementById( 'run' ).onclick = function() {_x000D_
document.getElementById( 'result' ).value = _x000D_
trim( document.getElementById( 'input' ).value,_x000D_
document.getElementById( 'charlist' ).value);_x000D_
}
_x000D_
<div>_x000D_
<label for="input">Text to trim:</label><br>_x000D_
<input id="input" type="text" placeholder="Text to trim" value="dfstextfsd"><br>_x000D_
<label for="charlist">Charlist:</label><br>_x000D_
<input id="charlist" type="text" placeholder="Charlist" value="dfs"><br>_x000D_
<label for="result">Result:</label><br>_x000D_
<input id="result" type="text" placeholder="Result" disabled><br>_x000D_
<button type="button" id="run">Trim it!</button>_x000D_
</div>
_x000D_
P.S.: why i posted my answer, when most people already done it before? Because i found "the best" mistake in all of there answers: all used the '+' meta instead of '*', 'cause trim
must remove chars IF THEY ARE IN START AND/OR END, but it return original string in else case.
The short version
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://almondmendoza.com/android-applications/")));
should work as well...
This produces the same results as using __year, __month, and __day and seems to work for me:
YourModel.objects.filter(your_datetime_field__startswith=datetime.date(2009,8,22))
This works fine for me...
.delimitador{
width:100%;
margin:auto;
}
.contenedor{
height:0px;
width:100%;
/*max-width:560px; /* Así establecemos el ancho máximo (si lo queremos) */
padding-top:56.25%; /* Relación: 16/9 = 56.25% */
position:relative;
}
iframe{
position:absolute;
height:100%;
width:100%;
top:0px;
left:0px;
}
and then
<div class="delimitador">
<div class="contenedor">
// youtube code
</div>
</div>
This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.
import pandas as pd
import io
texts = ['''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.11 False Graduated
113 Zoe 4.12 True ''',
'''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.21 False Graduated
113 Zoe 4.12 False On vacation''']
df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,21,20])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,21,20])
df = pd.concat([df1,df2])
print(df)
# id Name score isEnrolled Comment
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.11 False Graduated
# 2 113 Zoe 4.12 True NaN
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.21 False Graduated
# 2 113 Zoe 4.12 False On vacation
df.set_index(['id', 'Name'], inplace=True)
print(df)
# score isEnrolled Comment
# id Name
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.11 False Graduated
# 113 Zoe 4.12 True NaN
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.21 False Graduated
# 113 Zoe 4.12 False On vacation
def report_diff(x):
return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
changes = df.groupby(level=['id', 'Name']).agg(report_diff)
print(changes)
prints
score isEnrolled Comment
id Name
111 Jack 2.17 True He was late to class
112 Nick 1.11 | 1.21 False Graduated
113 Zoe 4.12 True | False nan | On vacation
THIS COMMAND REMOVES ALL IMAGES (USE WITH CAUTION)
Have you tried to use --force
sudo docker rmi $(sudo docker images -aq) --force
This above code run like a charm even doe i had the same issue
this worked for me in windows 7
import subprocess
subprocess.call("taskkill /IM geckodriver.exe")
The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).
Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.
OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.
Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.
Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...
If your sed usage tends to be entirely substitution expressions (as mine tends to be), you can also use perl -pe
instead
$ echo 'foo,bar,baz' | perl -pe 's/,/,\n/g'
foo,
bar,
baz
Append a semicolon to the following line to fix the issue.
font-family: Arial, Helvetica, sans-serif;
Here is a python script, built off of Shalmanese's answer and some help from Alex martelli over at Translating Perl to Python
I'm making it community wiki, so please feel free to edit, and refactor as long as it doesn't break the functionality (thankfully we can just roll back) - It's pretty ugly but works
use like so (assuming the script is called dump_for_mysql.py
:
sqlite3 sample.db .dump | python dump_for_mysql.py > dump.sql
Which you can then import into mysql
note - you need to add foreign key constrains manually since sqlite doesn't actually support them
here is the script:
#!/usr/bin/env python
import re
import fileinput
def this_line_is_useless(line):
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
'PRAGMA foreign_keys=OFF',
]
for useless in useless_es:
if re.search(useless, line):
return True
def has_primary_key(line):
return bool(re.search(r'PRIMARY KEY', line))
searching_for_end = False
for line in fileinput.input():
if this_line_is_useless(line):
continue
# this line was necessary because '');
# would be converted to \'); which isn't appropriate
if re.match(r".*, ''\);", line):
line = re.sub(r"''\);", r'``);', line)
if re.match(r'^CREATE TABLE.*', line):
searching_for_end = True
m = re.search('CREATE TABLE "?(\w*)"?(.*)', line)
if m:
name, sub = m.groups()
line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
line = line % dict(name=name, sub=sub)
else:
m = re.search('INSERT INTO "(\w*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
# Add auto_increment if it is not there since sqlite auto_increments ALL
# primary keys
if searching_for_end:
if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
# replace " and ' with ` because mysql doesn't like quotes in CREATE commands
if line.find('DEFAULT') == -1:
line = line.replace(r'"', r'`').replace(r"'", r'`')
else:
parts = line.split('DEFAULT')
parts[0] = parts[0].replace(r'"', r'`').replace(r"'", r'`')
line = 'DEFAULT'.join(parts)
# And now we convert it back (see above)
if re.match(r".*, ``\);", line):
line = re.sub(r'``\);', r"'');", line)
if searching_for_end and re.match(r'.*\);', line):
searching_for_end = False
if re.match(r"CREATE INDEX", line):
line = re.sub('"', '`', line)
if re.match(r"AUTOINCREMENT", line):
line = re.sub("AUTOINCREMENT", "AUTO_INCREMENT", line)
print line,
this solution is deprecated since 2.3 and will be removed in 3.0, see documentation
$form->getData();
gives you an array for the form parameters
from symfony2 book page 162 (Chapter 12: Forms)
[...] sometimes, you may just want to use a form without a class, and get back an array of the submitted data. This is actually really easy:
public function contactAction(Request $request) {
$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'email')
->add('message', 'textarea')
->getForm();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
// data is an array with "name", "email", and "message" keys
$data = $form->getData();
}
// ... render the form
}
You can also access POST values (in this case "name") directly through the request object, like so:
$this->get('request')->request->get('name');
Be advised, however, that in most cases using the getData() method is a better choice, since it returns the data (usually an object) after it's been transformed by the form framework.
When you want to access the form token, you have to use the answer of Problematic
$postData = $request->request->get('contact');
because the getData()
removes the element from the array
since 2.3 you should use handleRequest
instead of bindRequest
:
$form->handleRequest($request);
Try request.setAttribute("param",value);
. It worked fine for me.
Please find this code sample:
private void sanitizePrice(ServletRequest request){
if(request.getParameterValues ("price") != null){
String price[] = request.getParameterValues ("price");
for(int i=0;i<price.length;i++){
price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
System.out.println(price[i]);
}
request.setAttribute("price", price);
//request.getParameter("numOfBooks").re
}
}
A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull
command:
git pull --rebase
Example:
contents of the ae.csv file:
"Date, xpto 14"
"code","number","year","C"
"blab","15885","2016","Y"
"aeea","15883","1982","E"
"xpto","15884","1986","B"
"jrgg","15885","1400","A"
CREATE TABLE Tabletmp (
rec VARCHAR(9)
);
For put only column 3:
LOAD DATA INFILE '/local/ae.csv'
INTO TABLE Tabletmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 2 LINES
(@col1, @col2, @col3, @col4, @col5)
set rec = @col3;
select * from Tabletmp;
2016
1982
1986
1400
Google has this to say on transferring data between accounts.
http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304
It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.
It's conveniently titled: "Moving Product Data"
http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582
Use foreach($fields as &$field){
- so you will work with the original array.
Here is more about passing by reference.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
I tried the old-fashioned version, of just adjusting aria-* and CSS attributes like many of these older answers, but eventually gave up and just did a conditional fake-click. Works a beaut':
HTML:
<a href="#" onclick="expandAll();"
title="Expand All" alt="Expand All"><img
src="/images/expand-all-icon.png"/></a>
<a href="#" onclick="collapseAll();"
title="Collapse All" alt="Collapse All"><img
src="/images/collapse-all-icon.png"/></a>
Javascript:
async function expandAll() {
let heads = $(".ui-accordion-header");
heads.each((index, el) => {
if ($(el).hasClass("ui-accordion-header-collapsed") === true)
$(el).trigger("click");
});
}
async function collapseAll() {
let heads = $(".ui-accordion-header");
heads.each((index, el) => {
if ($(el).hasClass("ui-accordion-header-collapsed") === false)
$(el).trigger("click");
});
}
(The HTML newlines are placed in those weird places to prevent whitespace in the presentation.)
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) {
...
}
int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}
Or make the string static in getStr
:
char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}
Or allocate the string on the heap:
char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}
This code should work in all browsers.
function replaceContentInContainer(matchClass, content) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].innerHTML = content;
}
}
}
The way it works is by looping through all of the elements in the document, and searching their class list for matchClass
. If a match is found, the contents is replaced.
var sizef = document.getElementById('input-file-id').files[0].size;
if(sizef > 210000){
alert('sorry error');
}else {
//action
}
The best way I have tried before is to use urlencode()
. Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.
However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING
, by passing it to curl_setopt()
:
curl_setopt($ch, CURLOPT_ENCODING, "");
TLDR: Aggregation pipeline is faster as compared to conventional .find().sort()
.
Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:
.find()
and .sort()
.As suggested by many .find().sort() is the simplest way to perform the sorting.
.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])
However, this is a slow process compared to the aggregation pipeline.
Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:
NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort()
method.
Here's an example of the aggregation pipeline.
db.collection_name.aggregate([{
"$match": {
# your query - optional step
}
},
{
"$sort": {
"field_1": pymongo.ASCENDING,
"field_2": pymongo.DESCENDING,
....
}
}])
Try this method yourself, compare the speed and let me know about this in the comments.
Edit: Do not forget to use allowDiskUse=True
while sorting on multiple fields otherwise it will throw an error.
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
We already have tons of options to get mean by group, adding one more from mosaic
package.
mosaic::mean(speed~dive, data = df)
#dive1 dive2
#0.579 0.440
This returns a named numeric vector, if needed a dataframe we can wrap it in stack
stack(mosaic::mean(speed~dive, data = df))
# values ind
#1 0.579 dive1
#2 0.440 dive2
data
set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
speed=runif(10))
In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:
void foo(char c)
{
puts("char");
}
void foo(int i)
{
puts("int");
}
int main()
{
foo('i');
return 0;
}
Output:
char
The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.
The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.
subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.
Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)
.. .. 01 .. ..
.. 06 02 ..
.. 11 07 03 ..
16 12 08 04
21 17 13 09 05
22 18 14 10
.. 23 19 15 ..
.. 24 20 ..
.. .. 25 .. ..
And by diamond you mean:
.. .. .. .. ..
01 02 03 04
.. 05 06 07 ..
08 09 10 11
.. 12 13 14 ..
15 16 17 18
.. 19 20 21 ..
22 23 24 25
.. .. .. .. ..
The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.
@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).
In my case I needed to force content-type: text/plain to be parsed as json.
If you cannot change the content-type of the request, try using the following code:
app.use(express.json({type: '*/*'}));
Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:
app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
// echo json
res.json(req.body);
});
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
void 0
returns undefined and can not be overwritten while undefined
can be overwritten.
var undefined = "HAHA";
var names = [{_x000D_
name: "Joe",_x000D_
age: 20,_x000D_
email: "[email protected]"_x000D_
},_x000D_
{_x000D_
name: "Mike",_x000D_
age: 50,_x000D_
email: "[email protected]"_x000D_
},_x000D_
{_x000D_
name: "Joe",_x000D_
age: 45,_x000D_
email: "[email protected]"_x000D_
}_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
I do not know C#, but with a little guesswork I think I understand what
foo : int {
get { return getFoo(); }
set { setFoo(newValue); }
}
does. It looks very similar to what you have in Swift, but it's not the same: in Swift you do not have the getFoo
and setFoo
. That is not a little difference: it means you do not have any underlying storage for your value.
Swift has stored and computed properties.
A computed property has get
and may have set
(if it's writable). But the code in the getter and setter, if they need to actually store some data, must do it in other properties. There is no backing storage.
A stored property, on the other hand, does have backing storage. But it does not have get
and set
. Instead it has willSet
and didSet
which you can use to observe variable changes and, eventually, trigger side effects and/or modify the stored value. You do not have willSet
and didSet
for computed properties, and you do not need them because for computed properties you can use the code in set
to control changes.
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
Use a collection that is a static property of your Car
class.
Every time you create a new instance of a Car
, store the reference in this collection.
To destroy all Car
s, just set all items to null
.
I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.
If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).
Right click any database or table and select "Find text on server".
All the matches are shown in a separate tab for each table - very nice.
Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!
First of all, the term generator originally was somewhat ill-defined in Python, leading to lots of confusion. You probably mean iterators and iterables (see here). Then in Python there are also generator functions (which return a generator object), generator objects (which are iterators) and generator expressions (which are evaluated to a generator object).
According to the glossary entry for generator it seems that the official terminology is now that generator is short for "generator function". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.
It might still be a good idea to be precise and avoid the term "generator" without further specification.
I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:
borrowed from: https://gist.github.com/gsakkis/4572159
The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:
# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime
from sqlalchemy.orm import Query
try:
basestring
except NameError:
basestring = str
def render_query(statement, dialect=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if dialect is None:
dialect = statement.session.bind.dialect
statement = statement.statement
elif dialect is None:
dialect = statement.bind.dialect
class LiteralCompiler(dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_array_value(self, val, item_type):
if isinstance(val, list):
return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
return self.render_literal_value(val, item_type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (basestring, date, datetime, timedelta)):
return "'%s'" % str(value).replace("'", "''")
elif isinstance(value, list):
return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(dialect, statement).process(statement)
Tested to two levels of nested arrays.
You can do like this:
$q="SELECT * FROM projects WHERE Year(Date) = '$year' and Month(Date) = '$month'";