when you see this problem always put your autocomplete function in keyup function and ensure you have added the libraries
$( "#searcharea" ).keyup(function(){
$( "#searcharea" ).autocomplete({
source: "suggestions.php"
});
});
FileReader API with jQuery, simple example.
( function ( $ ) {_x000D_
// Add click event handler to button_x000D_
$( '#load-file' ).click( function () {_x000D_
if ( ! window.FileReader ) {_x000D_
return alert( 'FileReader API is not supported by your browser.' );_x000D_
}_x000D_
var $i = $( '#file' ), // Put file input ID here_x000D_
input = $i[0]; // Getting the element from jQuery_x000D_
if ( input.files && input.files[0] ) {_x000D_
file = input.files[0]; // The file_x000D_
fr = new FileReader(); // FileReader instance_x000D_
fr.onload = function () {_x000D_
// Do stuff on onload, use fr.result for contents of file_x000D_
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )_x000D_
};_x000D_
//fr.readAsText( file );_x000D_
fr.readAsDataURL( file );_x000D_
} else {_x000D_
// Handle errors here_x000D_
alert( "File not selected or browser incompatible." )_x000D_
}_x000D_
} );_x000D_
} )( jQuery );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="file" />_x000D_
<input type='button' id='load-file' value='Load'>_x000D_
<div id="file-content"></div>
_x000D_
To read as text... uncomment //fr.readAsText(file);
line and comment fr.readAsDataURL(file);
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
This works (pandas v'0.19.2'):
df.rename(columns=df.iloc[0])
The answers above all over complicate the story.
That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.
Based on the answer of @macetw I print the exception directly to stderr in a decorator.
Python 3
from functools import wraps
from sys import stderr
from traceback import format_exc
from typing import Callable, Collection, Any, Mapping
def force_error_output(func: Callable):
@wraps(func)
def forced_error_output(*args: Collection[Any], **kwargs: Mapping[str, Any]):
nonlocal func
try:
func(*args, **kwargs)
except Exception as exception:
stderr.write(format_exc())
stderr.write("\n")
stderr.flush()
raise exception
return forced_error_output
Python 2
from functools import wraps
from sys import stderr
from traceback import format_exc
def force_error_output(func):
@wraps(func)
def forced_error_output(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as exception:
stderr.write(format_exc())
stderr.write("\n")
stderr.flush()
raise exception
return forced_error_output
Then in your worker just use the decorator
@force_error_output
def da_worker(arg1: int, arg2: str):
pass
replace
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3
with
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3
e.g. installing into /usr/local/bin
instead of /usr/bin
.
and ensure the /usr/local/bin
is before /usr/bin
in PATH.
i.e.
[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin
Ensure this always is the case by adding
export PATH=/usr/local/bin:$PATH
to the end of your ~/.bashrc
file. Prefixing the PATH
environment variable with custom bin folder such as /usr/local/bin
or /opt/<some install>/bin
is generally recommended to ensure that customizations are found before the default system ones.
You can check the CSS display
property:
if ($('#car').css('display') == 'none') {
alert('Car 2 is hidden');
}
Here is a demo: http://jsfiddle.net/YjP4K/
Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.
From the latest working spec for window.close()
:
The
close()
method on Window objects should, if all the following conditions are met, close the browsing context A:
- The corresponding browsing context A is script-closable.
- The browsing context of the incumbent script is familiar with the browsing context A.
- The browsing context of the incumbent script is allowed to navigate the browsing context A.
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.
This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.
Chrome allows that exception -- which it doesn't apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:
This method is only allowed to be called for windows that were opened by a script using the
window.open
method.
If you try to use window.close
from a Greasemonkey / Tampermonkey / userscript you will get:
Firefox: The error message, "Scripts may not close windows that were not opened by script.
"
Chrome: just silently fails.
The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.
However, since the security risks, posed by window.close
, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
Consider making a feature request.
Chrome is currently was vulnerable to the "self redirection" exploit. So code like this used to work in general:
open(location, '_self').close();
This is buggy behavior, IMO, and is now (as of roughly April 2015) mostly blocked. It will still work from injected code only if the tab is freshly opened and has no pages in the browsing history. So it's only useful in a very small set of circumstances.
However, a variation still works on Chrome (v43 & v44) plus Tampermonkey (v3.11 or later). Use an explicit @grant
and plain window.close()
. EG:
// ==UserScript==
// @name window.close demo
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
setTimeout (window.close, 5000);
Thanks to zanetu for the update. Note that this will not work if there is only one tab open. It only closes additional tabs.
Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.
You can open up about:config
and set
allow_scripts_to_close_windows
to true
.
If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.
There currently is no equivalent setting for Chrome.
That depends on your definition of which disk drive Windows used to boot. I can think of 3 different answers on a standard BIOS system (who knows what an EFI system does):
2 and 3 should be easy to find - I'm not so sure about 1. Though you can raw disk read to find an MBR, that doesn't mean it's the BIOS boot device this time or even next time (you could have multiple disks with MBRs).
You really can't even be sure that the PC was started from a hard drive - it's perfectly possible to boot Windows from a floppy. In that case, both 1 and 2 would technically be a floppy disk, though 3 would remain C:\Windows.
You might need to be a bit more specific in your requirements or goals.
Strings are immutable types. You cannot modify them, only return new string instances.
Because of that, formatting with an instance method makes little sense, as it would have to be called like:
String formatted = "%s: %s".format(key, value);
The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.
Here is an example of why format()
would be dumb as an instance method. In .NET (and probably in Java), Replace()
is an instance method.
You can do this:
"I Like Wine".Replace("Wine","Beer");
However, nothing happens, because strings are immutable. Replace()
tries to return a new string, but it is assigned to nothing.
This causes lots of common rookie mistakes like:
inputText.Replace(" ", "%20");
Again, nothing happens, instead you have to do:
inputText = inputText.Replace(" ","%20");
Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace()
would be where format()
is, as a static method of String
:
inputText = String.Replace(inputText, " ", "%20");
Now there is no question as to what's going on.
The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.
Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).
Of course there are some methods that are perfect as instance methods, take String.Length()
int length = "123".Length();
In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.
My simple rules for Instance Methods on Immutable Objects:
update your CSS to the following: this should fix
.page {
width: 280px;
border:solid 1px blue;
overflow-x: auto;
}
This will happen before ReactDOM.render()
takes control of the root <div>
. I.e. your App will not have been mounted up to that point.
So you can add your loader in your index.html
file inside the root <div>
. And that will be visible on the screen until React takes over.
You can use whatever loader element works best for you (svg
with animation for example).
You don't need to remove it on any lifecycle method. React will replace any children of its root <div>
with your rendered <App/>
, as we can see in the GIF below.
index.html
<head>
<style>
.svgLoader {
animation: spin 0.5s linear infinite;
margin: auto;
}
.divLoader {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="root">
<div class="divLoader">
<svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
<path fill="lightblue"
d="PATH FOR THE LOADER ICON"
/>
</svg>
</div>
</div>
</body>
index.js
Using debugger
to inspect the page before ReactDOM.render()
runs.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
debugger; // TO INSPECT THE PAGE BEFORE 1ST RENDER
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In Bash you can also explicitly specify your redirects to different files:
cmd >log.out 2>log_error.out
Appending would be:
cmd >>log.out 2>>log_error.out
Try using the COLUMN command with the FORMAT option for that:
COLUMN COLUMN_NAME FORMAT 99.99
SELECT COLUMN_NAME FROM ....
Visual Studio Commmunity 2017 - dumpbin.exe
became available once I installed the C++ profiling tools
in Modify
menu from the Visual Studio Installer
.
TakeScreenShot screenshot=new TakeScreenShot();
screenshot.screenShot("screenshots//TestScreenshot//password.png");
it will work , please try.
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
If we see logically programming language and scripting language so this is 99.09% same . because we use same concept like loop , control condition ,variable and all so we can say yes both are same but there is only one thing is different between them that is in C/C++ and other programming language we compile the code before execution . but in the PHP , JavaScript and other scripting language we don't need to compile we directly execute in the browser.
Thanks Nitish K. Jha
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
Use @title
in your controllers when you want your variable to be available in your views.
The explanation is that @title
is an instance variable while title
is a local variable. Rails makes instance variables from controllers available to views because the template code (erb, haml, etc) is executed within the scope of the current controller instance.
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
I met same issue installing node-sass when I am on Node 12.9.0
Once switching to Node 10.19.0, the issue is gone.
$alphabets = range('A', 'Z');
$doubleAlphabets = array();
$count = 0;
foreach($alphabets as $key => $alphabet)
{
$count++;
$letter = $alphabet;
while ($letter <= 'Z')
{
$doubleAlphabets[] = $letter;
++$letter;
}
}
return $doubleAlphabets;
One approach would be to iterate over the array, calling the description
message on each item:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
[result appendString:[obj description]];
}
NSLog(@"The concatenated string is %@", result);
Another approach would be to do something based on each item's class:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
if ([obj isKindOfClass:[NSNumber class]])
{
// append something
}
else
{
[result appendString:[obj description]];
}
}
NSLog(@"The concatenated string is %@", result);
If you want commas and other extraneous information, you can just do:
NSString * result = [array description];
A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field
L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.
You can undo a rails generate
in the following ways:
rails destroy MODEL
rails destroy controller_name
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
Curly braces are always needed for accessing array elements and carrying out brace expansion.
It's good to be not over-cautious and use {}
for shell variable expansion even when there is no scope for ambiguity.
For example:
dir=log
prog=foo
path=/var/${dir}/${prog} # excessive use of {}, not needed since / can't be a part of a shell variable name
logfile=${path}/${prog}.log # same as above, . can't be a part of a shell variable name
path_copy=${path} # {} is totally unnecessary
archive=${logfile}_arch # {} is needed since _ can be a part of shell variable name
So, it is better to write the three lines as:
path=/var/$dir/$prog
logfile=$path/$prog.log
path_copy=$path
which is definitely more readable.
Since a variable name can't start with a digit, shell doesn't need {}
around numbered variables (like $1
, $2
etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {}
in such contexts:
set app # set $1 to app
fruit=$1le # sets fruit to apple, but confusing
fruit=${1}le # sets fruit to apple, makes the intention clear
See:
Google Closure Compiler, YUI compressor, Minify, /Packer/... etc, are options for compressing/obfuscating your JS codes. But none of them can help you from hiding your code from the users.
Anyone with decent knowledge can easily decode/de-obfuscate your code using tools like JS Beautifier. You name it.
So the answer is, you can always make your code harder to read/decode, but for sure there is no way to hide.
If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:
function once = function(object,event,callback){
var handle={};
var eventNames=event.split(" ");
var cbWrapper=function(){
eventNames.forEach(function(e){
object.removeEventListener(e,cbWrapper, false );
});
callback.apply(this,arguments);
};
eventNames.forEach(function(e){
object.addEventListener(e,cbWrapper,false);
});
handle.cancel=function(){
eventNames.forEach(function(e){
object.removeEventListener(e,cbWrapper, false );
});
};
return handle;
};
Usage:
var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
//do something
});
then if you wish to cancel at some point you can still do it with
handler.cancel();
It's good for other event usages as well :)
There is no "canonical" way to do the matrix in C++, STL does not provide classes like "matrix". However there are some 3rd party libraries that do. You are encouraged to use them or write your own implementation. You can try my implementation derived from some public implementation found on the internet.
While a = 'foo' if True else 'bar'
is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:
a = (b == True and "123" or "456" )
... which in python should be shortened to:
a = b is True and "123" or "456"
... or if you simply want to test the truthfulness of b's value in general...
a = b and "123" or "456"
? :
can literally be swapped out for and or
Well, this question was asked years ago. I think technology has changed quite a bit and browser compatibility is much better. You could use vertical-align but I would consider that some what less scaleable and less reusable. I would recommend a flexbox approach.
Here is the same example the original poster used but with flexbox. It styles a single element. If a button size changes for whatever reason, it will continue to be vertically and horizontally centered.
.button {
border: 1px solid #ccc;
height: 40px;
margin: 60px;
padding: 4px;
display: flex;
justify-content: space-around;
align-items: center;
}
Example: JsFiddle
function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
Try this
<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat; background-position: center;"> </div>
Try this one :
var time = new Date().toJSON();
SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)
or
SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))
The easiest way is to pickle it using to_pickle
:
df.to_pickle(file_name) # where to save it, usually as a .pkl
Then you can load it back using:
df = pd.read_pickle(file_name)
Note: before 0.11.1 save
and load
were the only way to do this (they are now deprecated in favor of to_pickle
and read_pickle
respectively).
Another popular choice is to use HDF5 (pytables) which offers very fast access times for large datasets:
import pandas as pd
store = pd.HDFStore('store.h5')
store['df'] = df # save it
store['df'] # load it
More advanced strategies are discussed in the cookbook.
Since 0.13 there's also msgpack which may be be better for interoperability, as a faster alternative to JSON, or if you have python object/text-heavy data (see this question).
I figured it out myself. I need
select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual
public static void main(String[] args) {
int m = 100;
int a[] =new int[m];
for (int i=2; i<m; i++)
for (int j=0; j<m; j+=i)
a[j]++;
for (int i=0; i<m; i++)
if (a[i]==1) System.out.println(i);
}
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
As a key-hardened salted hash, using a secure algorithm such as sha-512.
In Yii2 we need to return()
the result from the action.I think you need to add a return
in front of your redirect.
return $this->redirect(['user/index']);
Also, you might want to take a look at NetworkX
You can center a button
without using text-align
on the parent div
by simple using margin:auto; display:block;
For example:
HTML
<div>
<button>Submit</button>
</div>
CSS
button {
margin:auto;
display:block;
}
SEE IT IN ACTION: CodePen
Yes, You can use gcc to compile your asm code. Use -c for compilation like this:
gcc -c file.S -o file.o
This will give object code file named file.o. To invoke linker perform following after above command:
gcc file.o -o file
I found this clickOut
directive:
https://github.com/chliebel/angular2-click-outside. I check it and it works well (i only copy clickOutside.directive.ts
to my project). U can use it in this way:
<div (clickOutside)="close($event)"></div>
Where close
is your function which will be call when user click outside div. It is very elegant way to handle problem described in question.
If you use above directive to close popUp window, remember first to add event.stopPropagation()
to button click event handler which open popUp.
Below i copy oryginal directive code from file clickOutside.directive.ts
(in case if link will stop working in future) - the author is Christian Liebel :
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';_x000D_
_x000D_
@Directive({_x000D_
selector: '[clickOutside]'_x000D_
})_x000D_
export class ClickOutsideDirective {_x000D_
constructor(private _elementRef: ElementRef) {_x000D_
}_x000D_
_x000D_
@Output()_x000D_
public clickOutside = new EventEmitter<MouseEvent>();_x000D_
_x000D_
@HostListener('document:click', ['$event', '$event.target'])_x000D_
public onClick(event: MouseEvent, targetElement: HTMLElement): void {_x000D_
if (!targetElement) {_x000D_
return;_x000D_
}_x000D_
_x000D_
const clickedInside = this._elementRef.nativeElement.contains(targetElement);_x000D_
if (!clickedInside) {_x000D_
this.clickOutside.emit(event);_x000D_
}_x000D_
}_x000D_
}
_x000D_
use MAX
in your SELECT
to return on value.. EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will more than one value
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
As others have mentioned, use triple quotes ”””abc”””
for multiline strings. Also, you can do this without having to call close()
using the with
keyword. For example:
# HTML String
html = """
<table border=1>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
<indent>
<% for i in range(10): %>
<tr>
<td><%= i %></td>
<td><%= i**2 %></td>
</tr>
</indent>
</table>
"""
# Write HTML String to file.html
with open("file.html", "w") as file:
file.write(html)
See https://stackoverflow.com/a/11783672/2206251 for more details on the with
keyword in Python.
You are trying to install a package on the system-wide path without having the permission to do so.
In general, you can use sudo
to temporarily obtain superuser
permissions at your responsibility in order to install the package on the system-wide path:
sudo pip install -r requirements.txt
Find more about sudo
here.
Actually, this is a bad idea and there's no good use case for it, see @wim's comment.
If you don't want to make system-wide changes, you can install the package on your per-user path using the --user
flag.
All it takes is:
pip install --user runloop requirements.txt
Finally, for even finer grained control, you can also use a virtualenv, which might be the superior solution for a development environment, especially if you are working on multiple projects and want to keep track of each one's dependencies.
After activating your virtualenv with
$ my-virtualenv/bin/activate
the following command will install the package inside the virtualenv (and not on the system-wide path):
pip install -r requirements.txt
You can use CSS Flexbox instead another display value, The Flexbox Layout (Flexible Box) module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.
Example
/* CONTAINER */
#wrapper
{
width:300px;
height:300px;
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
-ms-flex-direction: column;
-moz-flex-direction: column;
-webkit-flex-direction: column;
flex-direction: column;
}
/* SOME ITEM CHILD ELEMENTS */
#first
{
width:300px;
height: 200px;
background-color:#F5DEB3;
}
#second
{
width:300px;
background-color: #9ACD32;
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, */
}
If you want to have full support for old browsers like IE9 or below, you will have to use a polyfills like flexy, this polyfill enable support for Flexbox model but only for 2012 spec of flexbox model.
Recently I found another polyfill to help you with Internet Explorer 8 & 9 or any older browser that not have support for flexbox model, I still have not tried it but I leave the link here
You can find a usefull and complete Guide to Flexbox model by Chris Coyer here
In Sourcetree: Just ignore a file in specified folder. Sourcetree will ask if you like to ignore all files in that folder. It's perfect!
The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
This is Perfect. try this one :)
<form name="test" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
/* Html Input Fields */
</form>
I included these suggestions in a Gist I created on Github: http://gist.github.com/137348
Feel free to fork it, and make it better.
Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...
To make it work you should probably add this header to your response.You can also try to add the header crossorigin:true
to your request.
1. for error: unescaped apostrophe in string
what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file
In Android Studio, in problem file use :
Edit->find->replace
Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')
2. for other problematic symbols
I use to comment each next half part +rebuild
until i won't find the wrong sign.
E.g. an escaped word "\update" unexpectedly drops such error :)
Why would you need any other way? Comparing an Object
reference with null
is the least-verbose way to check if it's null.
It is not recommended to use DataReader
and Command.ExecuteReader
to get just one value from the database. Instead, you should use Command.ExecuteScalar
as following:
String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();
Here is more information about Connecting to database and managing data.
\
is used for escape sequences in programming languages.
\n
prints a newline
\\
prints a backslash
\"
prints "
\t
prints a tabulator
\b
moves the cursor one back
Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:
.container {_x000D_
border: 1px solid #DDDDDD;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.tag {_x000D_
float: left;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1000;_x000D_
background-color: #92AD40;_x000D_
padding: 5px;_x000D_
color: #FFFFFF;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="tag">Featured</div>_x000D_
<img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
The key is the container has to be positioned relative and the tag positioned absolute.
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
Escape the variable in order to access variables outside of the ssh session: ssh [email protected] "~/tools/myScript.pl \$BUILD_NUMBER"
Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.
This is what { mode: 'no-cors' }
was made for.
Use: cast(date_parse(inv.date_created,'%Y-%m-%d %h24:%i:%s') as date)
Input: String timestamp
Output: date format 'yyyy-mm-dd'
Just wanted to update the answer. As per Swashata Ghosh, the following is a simpler way that worked for moi:
HTML:
<button type="button" class="btn btn-primary example">Example</button>
JS:
$('.example').popover({
title: function() {
return 'Popup title' +
'<button class="close">×</button>';
},
content: 'Popup content',
trigger: 'hover',
html: true
});
$('.popover button.close').click(function() {
$(this).popover('toggle');
});
Edit: This is out of date, see @Merlin's answer.
[False]
, being a nonempty list, is not the same as False
. You should write:
test = df.sort('one', ascending=False)
Just ran into this syntax problem on a CentOS 7 machine.
On a very old Ubuntu machine running mail
, the syntax for a nicely composed email is
echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"
However on a CentOS 7 box which came with mailx
installed, it's quite different:
echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"
Consulting man mail
indicates that -r
is deprecated and the 'From' sender address should now be set directly using -S "variable=value"
.
In these and subsequent examples, I'm defining
$sender
as"Sender Name <[email protected]>"
and$recipients
as"[email protected]"
as I do in my bash script.
You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).
This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)
To get around this, I used a method which pipes the generated output through tr
before passing to mail
, and also specifies the charset of the email:
echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"
In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):
LANG="en_GB.UTF8" ; export LANG ;
(An alternate method of setting locales for cronjobs is discussed here)
More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.
You could also do the following:
// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
Add this attribute to you activity in manifest file. android:noHistory="true"
I used:
Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log
-Encoding ASCII -Append
This appended fine. I added the ASCII encoding to remove the nul characters Notepad++ was showing without the explicit encoding.
As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;
I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
UPDATE: Suggest using Dataframes
, plus something like ... .write.mode(SaveMode.Overwrite) ...
.
Handy pimp:
implicit class PimpedStringRDD(rdd: RDD[String]) {
def write(p: String)(implicit ss: SparkSession): Unit = {
import ss.implicits._
rdd.toDF().as[String].write.mode(SaveMode.Overwrite).text(p)
}
}
For older versions try
yourSparkConf.set("spark.hadoop.validateOutputSpecs", "false")
val sc = SparkContext(yourSparkConf)
In 1.1.0 you can set conf settings using the spark-submit script with the --conf flag.
WARNING (older versions): According to @piggybox there is a bug in Spark where it will only overwrite files it needs to to write it's part-
files, any other files will be left unremoved.
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
This is a "PHP Notice", so you could in theory ignore it. Change php.ini
:
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
To
error_reporting = E_ALL & ~E_NOTICE
This show all errors, except for notices.
You need to edit the Tomcat/conf/server.xml
and change the connector port. The connector setting should look something like this:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
Just change the connector port from default 8080 to another valid port number.
You could simply have: var result = (str == "true")
.
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
I had this issue (again) and it turned out I installed from the conda-forge channel; removing it and reinstalling from anaconda channel instead fixed it for me.
Update: I again had the same problem with a new env, this time I did install nb_conda_kernels
from anaconda channel, but my jupyter_client
was from the conda-forge channel. Uninstalling nb_conda_kernels
and reinstalling updated that to a higher-priority channel.
So make sure you've installed from the correct channels :)
For the record, tested with httpclient 4.3.6 and compatible with Executor of fluent api:
CloseableHttpClient httpClient = HttpClients.custom().
setHostnameVerifier(new AllowAllHostnameVerifier()).
setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
{
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
return true;
}
}).build()).build();
If you are Struggling with addToBackStack() & popBackStack() then simply use
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "Home");
ft.commit();`
In your Activity In OnBackPressed() find out fargment by tag and then do your stuff
Fragment home = getSupportFragmentManager().findFragmentByTag("Home");
if (home instanceof HomeFragment && home.isVisible()) {
// do you stuff
}
For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.
pip install -U setuptools
and easy_install
was putting egg-info in the wrong directory.
Then I just reinstalled apt-get install python-dev
.
Let me install the drivers I want after that
I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.
package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Layout
RelativeLayout atulsLayout = new RelativeLayout(this);
atulsLayout.setBackgroundColor(Color.GREEN);
//Button
Button redButton = new Button(this);
redButton.setText("Log In");
redButton.setBackgroundColor(Color.RED);
//Username input
EditText username = new EditText(this);
redButton.setId(1);
username.setId(2);
RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
//give rules to position widgets
usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
usernameDetails.setMargins(0,0,0,50);
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
username.setWidth(px);
//Add widget to layout(button is now a child of layout)
atulsLayout.addView(redButton,buttonDetails);
atulsLayout.addView(username,usernameDetails);
//Set these activities content/display to this view
setContentView(atulsLayout);
}
}
Here's one approach using a regular expression:
$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace
Perl 6 will include a trim function:
$string .= trim;
Source: Wikipedia
If you want the overflow to wrap: flex-flow: row wrap
Usually when you have a '\r' at the end of the string, only carriage return is printed without any newline. If you have the following:
printf("fooooo\r");
printf("bar");
the output will be:
barooo
One thing I can suggest (maybe a workaround) is to have a NULL terminated fixed size string that is initialized to all space characters, ending in a '\r' (every time before printing), and then use strcpy to copy your string into it (without the newline), so every subsequent print will overwrite the previous string. Something like this:
char str[MAX_LENGTH];
// init str to all spaces, NULL terminated with character as '\r'
strcpy(str, my_string); // copy my_string into str
str[strlen(my_string)] = ' '; // erase null termination char
str[MAX_LENGTH - 1] = '\r';
printf(str);
You can do error checking so that my_string
is always atleast one less in length than str
, but you get the basic idea.
Please check this answer
// In angularJS script
$scope.foo = function() {
console.log('test');
};
$window.angFoo = function() {
$scope.foo();
$scope.$apply();
};
// In jQuery
if (window.angFoo) {
window.angFoo();
}
A color value has more than one dimension, so there is no intrinsic way to compare two colors. You have to determine for your use case the meaning of the colors and thereby how to best compare them.
Most likely you want to compare the hue, saturation and/or lightness properties of the colors as oppposed to the red/green/blue components. If you are having trouble figuring out how you want to compare them, take some pairs of sample colors and compare them mentally, then try to justify/explain to yourself why they are similar/different.
Once you know which properties/components of the colors you want to compare, then you need to figure out how to extract that information from a color.
Most likely you will just need to convert the color from the common RedGreenBlue representation to HueSaturationLightness, and then calculate something like
avghue = (color1.hue + color2.hue)/2
distance = abs(color1.hue-avghue)
This example would give you a simple scalar value indicating how far the gradient/hue of the colors are from each other.
Try setting a height on your td elements.
vertical-align: middle;
means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.
Another solution I ran across tonight, which worked for my needs, was to add box-sizing
attributes:
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
These attributes force the border to be part of the box model's width and height and correct the issue as well.
According to caniuse.com » box-sizing, box-sizing
is supported in IE8+.
If you're using LESS or Sass there is a Bootstrap mixin for this.
LESS:
.box-sizing(border-box);
Sass:
@include box-sizing(border-box);
Just adding and formalizing @David 's solution from above:
Note that jQuery functions are chainable and return 'this' so that multiple invocations can be called one after the other (e.g $container.css("overflow", "hidden").css("outline", 0);
).
So the improved code should be:
(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
var ret = orig.apply(this, arguments);
$(this).trigger(ev);
return ret; // must include this
}
})();
Add this extension to convert your html code to a regular string:
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
And then you show your String inside an UITextView Or UILabel
textView.text = yourString.html2String
or
label.text = yourString.html2String
add following code in function.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'var1'; // var1 is the name of variable you want to add
return $vars;
}
then you will b able to use $_GET['var1']
This is generally referred to as an Indeterminate Progress Bar or Indeterminate Progress Dialog.
Combine this with a Thread and a Handler to get exactly what you want. There are a number of examples on how to do this via Google or right here on SO. I would highly recommend spending the time to learn how to use this combination of classes to perform a task like this. It is incredibly useful across many types of applications and will give you a great insight into how Threads and Handlers can work together.
I'll get you started on how this works:
The loading event starts the dialog:
//maybe in onCreate
showDialog(MY_LOADING_DIALOG);
fooThread = new FooThread(handler);
fooThread.start();
Now the thread does the work:
private class FooThread extends Thread {
Handler mHandler;
FooThread(Handler h) {
mHandler = h;
}
public void run() {
//Do all my work here....you might need a loop for this
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("state", 1);
msg.setData(b);
mHandler.sendMessage(msg);
}
}
Finally get the state back from the thread when it is complete:
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int state = msg.getData().getInt("state");
if (state == 1){
dismissDialog(MY_LOADING_DIALOG);
removeDialog(MY_LOADING_DIALOG);
}
}
};
Solution
Using only two lines of CSS, utilizing the magical power of Flexbox
.parent { display: flex; }
.child { margin: auto }
When compiling memcached under Centos 5.x i got the same problem.
The solution is to upgrade gcc and g++ to version 4.4 at least.
Make sure your CC/CXX is set (exported) to right binaries before compiling.
In a more general sense, this is known as the "birthday problem" or "birthday paradox". Wikipedia has a pretty good overview at: Wikipedia - Birthday Problem
In very rough terms, the square root of the size of the pool is a rough approximation of when you can expect a 50% chance of a duplicate. The article includes a probability table of pool size and various probabilities, including a row for 2^128. So for a 1% probability of collision you would expect to randomly pick 2.6*10^18 128-bit numbers. A 50% chance requires 2.2*10^19 picks, while SQRT(2^128) is 1.8*10^19.
Of course, that is just the ideal case of a truly random process. As others mentioned, a lot is riding on the that random aspect - just how good is the generator and seed? It would be nice if there was some hardware support to assist with this process which would be more bullet-proof except that anything can be spoofed or virtualized. I suspect that might be the reason why MAC addresses/time-stamps are no longer incorporated.
To stop animation you may set such objectAnimator that do nothing, e.g.
first when manual flipping there is animation left to right:
flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);
then when switching to auto flipping there's no animation
flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);
doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
This should do what you want:
<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">
or shorter
<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">
Each {}
creates a new instance and ====
comparison of different objects instances always results in false
. When they are convert to strings ===
results to true
A better solution is to use &
"dev": "npm run start-watch & npm run wp-server"
For the Germans:
you have to change your decimal commas into a Full stop in your csv-file (in Excel:File -> Options -> Advanced -> "Decimal seperator") , then the error is solved.
Very easy with the dateTime() object, too.
$tomorrow = new DateTime('tomorrow');
echo $tomorrow->format("Y-m-d"); // Tomorrow's date
$yesterday = new DateTime('yesterday');
echo $yesterday->format("Y-m-d"); // Yesterday's date
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Maybe it will help someone, but sometimes Name tag might be missing for a reference and it leads that assembly cannot be found when building with MSBuild.
Make sure that Name
tag is available for particular reference csproj file, for example,
<ProjectReference Include="..\MyDependency1.csproj">
<Project>{9A2D95B3-63B0-4D53-91F1-5EFB99B22FE8}</Project>
<Name>MyDependency1</Name>
</ProjectReference>
If you want to avoid a DirectoryNotFoundException
you will need to ensure that the directory of the file does indeed exist. File.Exists
accomplishes this. Another way would be to utilize the Path
and Directory
utility classes like so:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}
Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}
You can also add linker flags to a specific target using the LINK_FLAGS
property:
set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")
If you want to propagate this change to other targets, you can create a dummy target to link to.
Not sure this is the best way, but you can certainly replace the tick labels like this:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
plt.plot(x,y)
plt.xticks(x," ")
plt.show()
In Python 3.4 this generates a simple line plot with no tick labels on the x-axis. A simple example is here: http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
This related question also has some better suggestions: Hiding axis text in matplotlib plots
I'm new to python. Your mileage may vary in earlier versions. Maybe others can help?
Similar to colMeans
, colSums
, etc, you could write a column maximum function, colMax
, and a column sort function, colSort
.
colMax <- function(data) sapply(data, max, na.rm = TRUE)
colSort <- function(data, ...) sapply(data, sort, ...)
I use ...
in the second function in hopes of sparking your intrigue.
Get your data:
dat <- read.table(h=T, text = "Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
7 23 299 8.6 65 5 7
8 19 99 13.8 59 5 8
9 8 19 20.1 61 5 9")
Use colMax
function on sample data:
colMax(dat)
# Ozone Solar.R Wind Temp Month Day
# 41.0 313.0 20.1 74.0 5.0 9.0
To do the sorting on a single column,
sort(dat$Solar.R, decreasing = TRUE)
# [1] 313 299 190 149 118 99 19
and over all columns use our colSort
function,
colSort(dat, decreasing = TRUE) ## compare with '...' above
The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible
. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
}
.day-item-wrapper {
position: relative;
}
.day-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
background: rgba(0,0,0,0.1);
}
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
the simplest for me
android:numeric="integer"
although this also more customize
android:digits="0123456789"
You can use the -l
option in the she-bang header:
#!/usr/bin/perl -l
$text = "hello";
print $text;
print $text;
Output:
hello
hello
320
And the segments look like this
{64}@{255}
64 + 1 + 255 = 320
You should also read this if you are validating emails
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
I am using following code to decode base64 string in node API nodejs version 10.7.0
let data = 'c3RhY2thYnVzZS5jb20='; // Base64 string
let buff = new Buffer(data, 'base64'); //Buffer
let text = buff.toString('ascii'); //this is the data type that you want your Base64 data to convert to
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');
Please don't try to run above code in console of the browser, won't work. Put the code in server side files of nodejs. I am using above line code in API development.
Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.
So updating entity value would be more secure, more optimist.
If the value changes frequent, then you might consider not to use version field. For an example "an entity that has counter field, that will increased everytime a web page accessed"
There are no hard and fast rules, but the rule of thumb from a purely conceptual standpoint that I like to use can briefly be summed up like this: a URI path (by definition) represents a resource and query parameters are essentially modifiers on that resource. So far that likely doesn't help... With a REST API you have the major methods of acting upon a single resource using GET
, PUT
, and DELETE
. Therefore whether something should be represented in the path or as a parameter can be reduced to whether those methods make sense for the representation in question. Would you reasonably PUT
something at that path and would it be semantically sound to do so? You could of course PUT
something just about anywhere and bend the back-end to handle it, but you should be PUT
ing what amounts to a representation of the actual resource and not some needlessly contextualized version of it. For collections the same can be done with POST
. If you wanted to add to a particular collection what would be a URL that makes sense to POST
to.
This still leaves some gray areas as some paths could point to what amount to children of parent resources which is somewhat discretionary and dependent on their use. The one hard line that this draws is that any type of transitive representation should be done using a query parameter, since it would not have an underlying resource.
In response to the real world example given in the original question (Twitter's API), the parameters represent a transitive query that filters on the state of the resources (rather than a hierarchy). In that particular example it would be entirely unreasonable to add to the collection represented by those constraints, and further that query would not be able to be represented as a path that would make any sense in the terms of an object graph.
The adoption of this type of resource oriented perspective can easily map directly to the object graph of your domain model and drive the logic of your API to the point where everything works very cleanly and in a fairly self-documenting way once it snaps into clarity. The concept can also be made clearer by stepping away from systems that use traditional URL routing mapped on to a normally ill-fitting data model (i.e. an RDBMS). Apache Sling would certainly be a good place to start. The concept of object traversal dispatch in a system like Zope also provides a clearer analog.
Update your version of youtube-dl to the lastest as older version might not support.
pip install --upgrade youtube_dl
Install 'ffmpeg' and 'ffprobe' module
pip install ffmpeg
pip install ffprobe
If you face the same issue, then download ffmpeg builds and put all the .exe files to Script folder($path: "Python\Python38-32\Scripts") (Windows OS only)
The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).
1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.
you can install the script ;
pip3 install --user advance-touch
After installed, you can use ad command
ad airport/plane/captain.txt
airport/
+-- plane/
¦ +-- captain.txt
A quick solution that might help someone :
Add this line as value for start ng serve --host 0.0.0.0 --disable-host-check
in your package.json
ex:
{
"ng": "ng",
"start": "ng serve --host 0.0.0.0 --disable-host-check",
"build": "ng build",
}
And then simply do start
or npm run start
you will be able to access your project from other local IPs.
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
I haven't really seen many practical real world uses of the %n
specifier, but I remember that it was used in oldschool printf vulnerabilities with a format string attack quite a while back.
Something that went like this
void authorizeUser( char * username, char * password){
...code here setting authorized to false...
printf(username);
if ( authorized ) {
giveControl(username);
}
}
where a malicious user could take advantage of the username parameter getting passed into printf as the format string and use a combination of %d
, %c
or w/e to go through the call stack and then modify the variable authorized to a true value.
Yeah it's an esoteric use, but always useful to know when writing a daemon to avoid security holes? :D
Here's a one-liner slim way for layering text on top of an input in jQuery using ES6 syntax.
$('.input-group > input').focus(e => $(e.currentTarget).parent().find('.placeholder').hide()).blur(e => { if (!$(e.currentTarget).val()) $(e.currentTarget).parent().find('.placeholder').show(); });
_x000D_
* {
font-family: sans-serif;
}
.input-group {
position: relative;
}
.input-group > input {
width: 150px;
padding: 10px 0px 10px 25px;
}
.input-group > .placeholder {
position: absolute;
top: 50%;
left: 25px;
transform: translateY(-50%);
color: #929292;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<span class="placeholder">Username</span>
<input>
</div>
_x000D_
I was having the same problem. It seems that passing Me.ComboBox1.Value
as an argument for the Vlookup
function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.
Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False)
Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>)
.
So it would end up being
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False)
Strange as it may sound, it works for me.
Hope this helps.
Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!
Usage: input is your nameId input has file image
<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function converImageToBase64(inputId) {
let image = $('#'+inputId)[0]['files']
if (image && image[0]) {
const reader = new FileReader();
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(image[0])
})
}
}
async function proccessData() {
const image = await converImageToBase64('asd')
console.log(image)
}
</script>
Example: converImageToBase64('yourFileInputId')
Sprockets together with Sass has some nifty helpers you can use to get the job done. Sprockets will only process these helpers if your stylesheet file extensions are either .css.scss
or .css.sass
.
Image specific helper:
background-image: image-url("logo.png")
Agnostic helper:
background-image: asset-url("logo.png", image)
background-image: asset-url($asset, $asset-type)
Or if you want to embed the image data in the css file:
background-image: asset-data-url("logo.png")
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
Here is a way to do it while passing in an extra argument:
https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
With the backend:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
.
And yet another way with an in-template filter only:
https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)
<div ng:app>
<div ng-controller="HelloCntl">
<ul>
<li ng-repeat="friend in friends | filter:{name:'!Adam'}">
<span>{{friend.name}}</span>
<span>{{friend.phone}}</span>
</li>
</ul>
</div>
To add to the answers here, ensure there's no space between the select
and [name...
Wrong:
'select [name=' + name + ']'
^
Right:
'select[name=' + name + ']'
I had this exact problem and this worked:
plt.savefig(output_dir + '/xyz.png', bbox_inches='tight')
Here is the documentation:
[https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html][1]
Here are a few popular examples:
<div>{{myDate | date:'M/d/yyyy'}}</div>
7/4/2014
<div>{{myDate | date:'yyyy-MM-dd'}}</div>
2014-07-04
<div>{{myDate | date:'M/d/yyyy HH:mm:ss'}}</div>
7/4/2014 12:01:59
To get a div
to 100% height on a page, you will need to set each object on the hierarchy above the div to 100% as well. for instance:
html { height:100%; }
body { height:100%; }
#full { height: 100%; }
#someid { height: 100%; }
Although I cannot fully understand your question, I'm assuming this is what you mean.
This is the example I am working from:
<html style="height:100%">
<body style="height:100%">
<div style="height:100%; width: 300px;">
<div style="height:100%; background:blue;">
</div>
</div>
</body>
</html>
Style
is just a replacement for the CSS which I haven't externalised.
Input: 0 0.1 1000
=FIXED(E5,2)
Output: 0.00 0.10 1,000.00
=TEXT(E5,"0.00")
Output: 0.00 0.10 1000.00
Note: As you can see FIXED add a coma after a thousand, where TEXT does not.
You could use "typeof".
if(typeof maybeObject != "undefined")
alert("GOT HERE");
View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();
Yes you can. I assume you have a xampp already installed. So,
That's how I am working with multiple xampp installed
As a general rule, the token should not be stored on the localStorage
neither the sessionStorage
. Both places are accessible from JS and the JS should not care about the authentication token.
IMHO The token should be stored on a cookie with the HttpOnly
and Secure
flag as suggested here: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage
exec
returns an object with a index
property:
var match = /bar/.exec("foobar");_x000D_
if (match) {_x000D_
console.log("match found at " + match.index);_x000D_
}
_x000D_
And for multiple matches:
var re = /bar/g,_x000D_
str = "foobarfoobar";_x000D_
while ((match = re.exec(str)) != null) {_x000D_
console.log("match found at " + match.index);_x000D_
}
_x000D_
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
Changing the framework to
.NET Framework 4 Client Profile
did the job for me.
Here is an example where pointer to data members could be useful:
#include <iostream>
#include <list>
#include <string>
template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
for (const typename Container::value_type& x : container) {
if (x->*ptr == t)
return x;
}
return typename Container::value_type{};
}
struct Object {
int ID, value;
std::string name;
Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};
std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
new Object(2,11,"Tom"), new Object(15,16,"John") };
int main() {
const Object* object = searchByDataMember (objects, 11, &Object::value);
std::cout << object->name << '\n'; // Tom
}
We use the following:
Canada
([A-Z]{1}[0-9]{1}){3} //We raise to upper first
America
[0-9]{5} //-or-
[0-9]{5}-[0-9]{4} //10 digit zip
Other
Accept as is
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.
So I made a code example with early binding of a variable (= copying):
<?php
$a = 1;
$b = 2;
$closureExampleEarlyBinding = function() use ($a, $b){
$a++;
$b++;
echo "Inside \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."<br />";
};
echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";
$closureExampleEarlyBinding();
echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";
/* this will output:
Before executing $closureExampleEarlyBinding() $a = 1
Before executing $closureExampleEarlyBinding() $b = 2
Inside $closureExampleEarlyBinding() $a = 2
Inside $closureExampleEarlyBinding() $b = 3
After executing $closureExampleEarlyBinding() $a = 1
After executing $closureExampleEarlyBinding() $b = 2
*/
?>
Example with referencing a variable (notice the '&' character before variable);
<?php
$a = 1;
$b = 2;
$closureExampleReferencing = function() use (&$a, &$b){
$a++;
$b++;
echo "Inside \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Inside \$closureExampleReferencing() \$b = ".$b."<br />";
};
echo "Before executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Before executing \$closureExampleReferencing() \$b = ".$b."<br />";
$closureExampleReferencing();
echo "After executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "After executing \$closureExampleReferencing() \$b = ".$b."<br />";
/* this will output:
Before executing $closureExampleReferencing() $a = 1
Before executing $closureExampleReferencing() $b = 2
Inside $closureExampleReferencing() $a = 2
Inside $closureExampleReferencing() $b = 3
After executing $closureExampleReferencing() $a = 2
After executing $closureExampleReferencing() $b = 3
*/
?>
It is too late but helps someone, I'm using node version v7.9.0
and express version 4.15.0
if your directory structure is something like this:
your-project
uploads
package.json
server.js
server.js code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/uploads'));// you can access image
//using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.
//Or you can change the directory for hiding real directory name:
`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg
app.listen(7000);
Your request mapping is /save
, but your POST is to /save.html
. Changing the POST to /save
should fix it.
After editing .gitignore
to match the ignored files, you can do git ls-files -ci --exclude-standard
to see the files that are included in the exclude lists; you can then do
git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"
to remove them from the repository (without deleting them from disk).
Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):
apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
(The -r
flag in xargs
prevents git rm
from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs
may or may not have a similar option.)
Now you can just type git apply-gitignore
in your repo, and it'll do the work for you!
No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.
Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.
But as of now use this:
List<User> users=new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUserId(rs.getString("UserId"));
user.setFName(rs.getString("FirstName"));
...
...
...
users.add(user);
}
From menu, Code -> Comment with Line Commment. So simple.
You could create a Hashmap<String, Object>
using one of the values as a key, and then seeing if yourHashMap.keySet().contains(yourValue)
returns true.
It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.
Since the stack is already unwound when entering the catch block, the solution in my case was to not catch certain exceptions which then lead to a SIGABRT. In the signal handler for SIGABRT I then fork() and execl() either gdb (in debug builds) or Google breakpads stackwalk (in release builds). Also I try to only use signal handler safe functions.
GDB:
static const char BACKTRACE_START[] = "<2>--- backtrace of entire stack ---\n";
static const char BACKTRACE_STOP[] = "<2>--- backtrace finished ---\n";
static char *ltrim(char *s)
{
while (' ' == *s) {
s++;
}
return s;
}
void Backtracer::print()
{
int child_pid = ::fork();
if (child_pid == 0) {
// redirect stdout to stderr
::dup2(2, 1);
// create buffer for parent pid (2+16+1 spaces to allow up to a 64 bit hex parent pid)
char pid_buf[32];
const char* stem = " ";
const char* s = stem;
char* d = &pid_buf[0];
while (static_cast<bool>(*s))
{
*d++ = *s++;
}
*d-- = '\0';
char* hexppid = d;
// write parent pid to buffer and prefix with 0x
int ppid = getppid();
while (ppid != 0) {
*hexppid = ((ppid & 0xF) + '0');
if(*hexppid > '9') {
*hexppid += 'a' - '0' - 10;
}
--hexppid;
ppid >>= 4;
}
*hexppid-- = 'x';
*hexppid = '0';
// invoke GDB
char name_buf[512];
name_buf[::readlink("/proc/self/exe", &name_buf[0], 511)] = 0;
ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_START[0], sizeof(BACKTRACE_START));
(void)r;
::execl("/usr/bin/gdb",
"/usr/bin/gdb", "--batch", "-n", "-ex", "thread apply all bt full", "-ex", "quit",
&name_buf[0], ltrim(&pid_buf[0]), nullptr);
::exit(1); // if GDB failed to start
} else if (child_pid == -1) {
::exit(1); // if forking failed
} else {
// make it work for non root users
if (0 != getuid()) {
::prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
}
::waitpid(child_pid, nullptr, 0);
ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_STOP[0], sizeof(BACKTRACE_STOP));
(void)r;
}
}
minidump_stackwalk:
static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded)
{
int child_pid = ::fork();
if (child_pid == 0) {
::dup2(open("/dev/null", O_WRONLY), 2); // ignore verbose output on stderr
ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_START[0], sizeof(MINIDUMP_STACKWALK_START));
(void)r;
::execl("/usr/bin/minidump_stackwalk", "/usr/bin/minidump_stackwalk", descriptor.path(), "/usr/share/breakpad-syms", nullptr);
::exit(1); // if minidump_stackwalk failed to start
} else if (child_pid == -1) {
::exit(1); // if forking failed
} else {
::waitpid(child_pid, nullptr, 0);
ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_STOP[0], sizeof(MINIDUMP_STACKWALK_STOP));
(void)r;
}
::remove(descriptor.path()); // this is not signal safe anymore but should still work
return succeeded;
}
Edit: To make it work for breakpad I also had to add this:
std::set_terminate([]()
{
ssize_t r = ::write(STDERR_FILENO, EXCEPTION, sizeof(EXCEPTION));
(void)r;
google_breakpad::ExceptionHandler::WriteMinidump(std::string("/tmp"), dumpCallback, NULL);
exit(1); // avoid creating a second dump by not calling std::abort
});
Source: How to get a stack trace for C++ using gcc with line number information? and Is it possible to attach gdb to a crashed process (a.k.a "just-in-time" debugging)
To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css
containing:
/* Make the notebook cells take almost all available width */
.container {
width: 99% !important;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px !important;
}
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key == 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
};
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem('getSessionStorage', 'foobar');
localStorage.removeItem('getSessionStorage', 'foobar');
};
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
The method below is exactly reproducible, so there's no need to run clone again if both sides were consistent, just run the script on the other side too.
git log -n1 --format=%H >.git/info/grafts
git filter-branch -f
rm .git/info/grafts
If you then want to clean it up, try this script:
http://sam.nipl.net/b/git-gc-all-ferocious
I wrote a script which "kills history" for each branch in the repository:
http://sam.nipl.net/b/git-kill-history
see also: http://sam.nipl.net/b/confirm
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
RETURN 0
END
GO
CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
RETURN 1
END
-- etc...
Where performance matters, still use the hard values.
when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.
Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html
From their sample code:
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
/* Optional if authentication is required.
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
*/
PostMethod post = new PostMethod("https://someurl");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
// ...
InputStream in = post.getResponseBodyAsStream();
// handle response.
/* Example for a GET reqeust
GetMethod httpget = new GetMethod("https://someurl");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
*/
The build context menu has a Cancel build in Visual Studio 2013.
Turning off HyperV on windows 8.1 did the trick for me
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
I think you have to store the number on heap. The int ret
variable was on stack and was destructed at the end of execution of function myThread
.
void *myThread()
{
int *ret = malloc(sizeof(int));
if (ret == NULL) {
// ...
}
*ret = 42;
pthread_exit(ret);
}
Don't forget to free
it when you don't need it :)
Another solution is to return the number as value of the pointer, like Neil Butterworth suggests.
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
For Java 11 you can use new HTTP client:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.
As others mentioned using epel
gives a really outdated version, here is a little script I just wrote instead to add to the CI pipeline or pass it to ec2 user-data
to install the latest version of node, simply replace the version
with what you want, and the appropriate distro
of Linux you are using.
The following example is for amazon-Linux-2-AMI
#!/bin/bash
version='v14.13.1'
distro='linux-x64'
package_name="node-$version-$distro"
package_location="/usr/local/lib/"
curl -O https://nodejs.org/download/release/latest/$package_name.tar.gz
tar -xvf $package_name.tar.gz -C $package_location
rm -rfv $package_name.tar.gz
echo "export PATH=$package_location/$package_name/bin:\$PATH" >> ~/.profile
if you want to test it in the same shell simply run
. ~/.profile
Converted from comment for the sake of visitor's convenience
It's not clear from this message what the correct syntax is. It is:
ALTER SEQUENCE product_id_seq RESTART WITH 1453;
That should work even if one, and only one of the conditions is true :
var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];
function contains(target, pattern){
var value = 0;
pattern.forEach(function(word){
value = value + target.includes(word);
});
return (value === 1)
}
console.log(contains(str, arr));
If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
The quick select algorithm can find the k-th smallest element of an array in linear (O(n)
) running time. Here is an implementation in python:
import random
def partition(L, v):
smaller = []
bigger = []
for val in L:
if val < v: smaller += [val]
if val > v: bigger += [val]
return (smaller, [v], bigger)
def top_k(L, k):
v = L[random.randrange(len(L))]
(left, middle, right) = partition(L, v)
# middle used below (in place of [v]) for clarity
if len(left) == k: return left
if len(left)+1 == k: return left + middle
if len(left) > k: return top_k(left, k)
return left + middle + top_k(right, k - len(left) - len(middle))
def median(L):
n = len(L)
l = top_k(L, n / 2 + 1)
return max(l)
Use the built-in ERRORLEVEL Variable:
echo %ERRORLEVEL%
But beware if an application has defined an environment variable named ERRORLEVEL!
NestedScrollView
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.
https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html
ScrollView
Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects
https://developer.android.com/reference/android/widget/ScrollView.html
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
My solution is based on @Martijn Pieters' comment:
register_namespace
only influences serialisation, not search.
So the trick here is to use different dictionaries for serialization and for searching.
namespaces = {
'': 'http://www.example.com/default-schema',
'spec': 'http://www.example.com/specialized-schema',
}
Now, register all namespaces for parsing and writing:
for name, value in namespaces.iteritems():
ET.register_namespace(name, value)
For searching (find()
, findall()
, iterfind()
) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).
self.namespaces['default'] = self.namespaces['']
Now, the functions from the find()
family can be used with the default
prefix:
print root.find('default:myelem', namespaces)
but
tree.write(destination)
does not use any prefixes for elements in the default namespace.
Inside Fragments (onCreateView)
Toast.makeText(getActivity(), "your message" , Toast.LENGTH_LONG).show();
Inside Classes (onCreate)
Toast.makeText(myClassName.this, "your message" , Toast.LENGTH_LONG).show();
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
I would say that it is not in the spirit of Java to run a shell script from Java. Java is meant to be cross platform, and running a shell script would limit its use to just UNIX.
With that said, it's definitely possible to run a shell script from within Java. You'd use exactly the same syntax you listed (I haven't tried it myself, but try executing the shell script directly, and if that doesn't work, execute the shell itself, passing the script in as a command line parameter).
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
Differences might not be meaningful in a typical use case, but using the standard DOM functionality
$("#el")[0].outerHTML
is about twice as fast as
$("<div />").append($("#el").clone()).html();
so I would go with:
/*
* Return outerHTML for the first element in a jQuery object,
* or an empty string if the jQuery object is empty;
*/
jQuery.fn.outerHTML = function() {
return (this[0]) ? this[0].outerHTML : '';
};
if you do ctrl-z
and then type exit
it will close background applications.
Ctrl+Q
is another good way to kill the application.
Architecture identifies fundamental components of the system, describes their organisation and how they are related to create a framework for the system.
Design describes various components and how they should be developed to provide required functionality with in the framework provided by the system architecture.
goto services and stop the "World Wide Web Publishing Service" after restart the wamp server. after that start the "World Wide Web Publishing Service"
-webkit-appearance: none;
Note : use bootstrap to style a button.Its common for responsive.
Use the pdfpages
package.
\usepackage{pdfpages}
To include all the pages in the PDF file:
\includepdf[pages=-]{myfile.pdf}
To include just the first page of a PDF:
\includepdf[pages={1}]{myfile.pdf}
Run texdoc pdfpages
in a shell to see the complete manual for pdfpages
.
I was having the same problem. None of the above solutions worked for me. The key challenge was that I didn't have the root access. So, I first download the source of libffi. Then I compiled it with usual commands:
./configure --prefix=desired_installation_path_to_libffi
make
Then I recompiled python using
./configure --prefix=/home/user123/Softwares/Python/installation3/ LDFLAGS='-L/home/user123/Softwares/library/libffi/installation/lib64'
make
make install
In my case, 'home/user123/Softwares/library/libffi/installation/lib64' is path to LIBFFI installation directory where libffi.so is located. And, /home/user123/Softwares/Python/installation3/ is path to Python installation directory. Modify them as per your case.
LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];
In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);
This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.