In Python you can iterate over the list
itself:
for item in my_list:
#do something with item
or to use indices you can use xrange()
:
for i in xrange(1,len(my_list)): #as indexes start at zero so you
#may have to use xrange(len(my_list))
#do something here my_list[i]
There's another built-in function called enumerate()
, which returns both item and index:
for index,item in enumerate(my_list):
# do something here
examples:
In [117]: my_lis=list('foobar')
In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']
In [119]: for item in my_lis:
print item
.....:
f
o
o
b
a
r
In [120]: for i in xrange(len(my_lis)):
print my_lis[i]
.....:
f
o
o
b
a
r
In [122]: for index,item in enumerate(my_lis):
print index,'-->',item
.....:
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
Here are a few methods, in no particular order:
char c = 'c';
String s = Character.toString(c); // Most efficient way
s = new Character(c).toString(); // Same as above except new Character objects needs to be garbage-collected
s = c + ""; // Least efficient and most memory-inefficient, but common amongst beginners because of its simplicity
s = String.valueOf(c); // Also quite common
s = String.format("%c", c); // Not common
Formatter formatter = new Formatter();
s = formatter.format("%c", c).toString(); // Same as above
formatter.close();
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
In general, if you don't know how something works, look for an example which you can learn from.
For this problem, consider this DEMO
You can see loading content with AJAX is very easily accomplished with jQuery:
$(function(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";
// load() functions
var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
Try to understand how this works and then try replicating it. Good luck.
You can find the corresponding tutorial HERE
Right now the following event starts the ajax load
function:
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
You can also do this periodically: How to fire AJAX request Periodically?
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);
) the content is updated.
You can also just load the data immediately:
$("#result").html(ajax_load).load(loadUrl);
Which has THIS corresponding demo.
Private outer class would be useless as nothing can access it.
See more details:
You can use XDocument.Parse(string)
instead of Load(string)
.
As @osknows said in a comment above (rather than an answer which is why I am adding this), the Analysis Pack includes Random Number Generation functions (e.g. NORM.DIST
, NORM.INV
) to generate a set of numbers. A good summary link is at http://www.bettersolutions.com/excel/EUN147/YI231420881.htm.
In my case, I was running Python in the minimal alpine docker image. It was missing root CA certificates. Fix:
apk update && apk add ca-certificates
Neither optional parameters nor function overloading are supported in Go. Go does support a variable number of parameters: Passing arguments to ... parameters
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
Tchoupi's answer can be made a tad less verbose by concatenating the argument for strtotime() as follows:
$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );
(This relies on magic implementation details, but you can always go have a look at them if you're rightly mistrustful.)
varchar(max)
for SQLServer2005
varchar(65535)
for MySQL 5.0.3 and later
This will allocate storage as need and shouldn't affect performance.
I found this page which tells you how to import a PFX to JKS (Java Key Store):
keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME
you can try it too:
$(document).ajaxError(
function (event, jqXHR, ajaxSettings, thrownError) {
alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
});
Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example:
On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.
OR
If you're using a Spring boot application, go to application.properties and add this:
server.port = 8081
Lots of answers but no substance, like robots doing cut and paste on what's on their system. There is no need to set GOROOT
as an environment variable. However, there is a beneficial need to set the GOPATH
environment variable, and if not set it defaults to ${HOME}/go/
folder.
It is the PATH
environment variable that you must pay attention because this variable is the variable that can change your go version
. Not GOROOT
! Forget GOROOT
.
Now, if you switch or change to a new go version
, your downloaded packages will use the default $HOME/go
folder and it will mixed-up with whatever your previous go version
was. This is not good.
Therefore, this is where GOPATH
you need to define in order to isolate downloaded packages of the new go version
.
In summary, forget GOROOT
. Think more on GOPATH
.
I would not use URLEncoder
. Besides being incorrectly named (URLEncoder
has nothing to do with URLs), inefficient (it uses a StringBuffer
instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.
Instead I would use URIBuilder
or Spring's org.springframework.web.util.UriUtils.encodeQuery
or Commons Apache HttpClient
.
The reason being you have to escape the query parameters name (ie BalusC's answer q
) differently than the parameter value.
The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.
Sample code:
import org.apache.http.client.utils.URIBuilder;
URIBuilder ub = new URIBuilder("http://example.com/query");
ub.addParameter("q", "random word £500 bank \$");
String url = ub.toString();
// Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24
Since I'm just linking to other answers I marked this as a community wiki. Feel free to edit.
Try something like this:
div {
background-image: url(../img/picture1.jpg);
height: 30em;
background-repeat: no-repeat;
width: 100%;
background-position: center;
}
do url_raw.cast_to_raw()
support in oracle 6
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
For Windows 10,
Modify my.ini
file in C:\ProgramData\MySQL\MySQL Server 8.0\
[mysqld]
default_authentication_plugin=mysql_native_password
Restart the MySQL Service.
Login to MySQL on the command line, and execute the following commands in MySQL:
Create a new user.
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
Grant all privileges.
GRANT ALL PRIVILEGES ON * .* TO 'user'@'localhost';
Open MySQL workbench, and open a new connection using the new user credentials.
I was facing the same issue and this worked.
I have this function in the document ready event so that the reCaptcha is dynamically sized. Anyone should be able to drop this in place and go.
function ScaleReCaptcha()
{
if (document.getElementsByClassName('g-recaptcha').length > 0)
{parentWidth = document.getElementsByClassName('g-recaptcha') [0].parentNode.clientWidth;
childWidth = document.getElementsByClassName('g-recaptcha')[0].firstChild.clientWidth;
scale = (parentWidth) / (childWidth);
new_width = childWidth * scale;
document.getElementsByClassName('g-recaptcha')[0].style.transform = 'scale(' + scale + ')';
document.getElementsByClassName('g-recaptcha')[0].style.transformOrigin = '0 0';
}
}
I know this is an ancient thread, but it was my first hit on Google, and I wanted to share the following resub
that I put together, which adds support for multiple $1, $2, etc. backreferences...
#!/usr/bin/env bash
############################################
### resub - regex substitution in bash ###
############################################
resub() {
local match="$1" subst="$2" tmp
if [[ -z $match ]]; then
echo "Usage: echo \"some text\" | resub '(.*) (.*)' '\$2 me \${1}time'" >&2
return 1
fi
### First, convert "$1" to "$BASH_REMATCH[1]" and 'single-quote' for later eval-ing...
### Utility function to 'single-quote' a list of strings
squot() { local a=(); for i in "$@"; do a+=( $(echo \'${i//\'/\'\"\'\"\'}\' )); done; echo "${a[@]}"; }
tmp=""
while [[ $subst =~ (.*)\${([0-9]+)}(.*) ]] || [[ $subst =~ (.*)\$([0-9]+)(.*) ]]; do
tmp="\${BASH_REMATCH[${BASH_REMATCH[2]}]}$(squot "${BASH_REMATCH[3]}")${tmp}"
subst="${BASH_REMATCH[1]}"
done
subst="$(squot "${subst}")${tmp}"
### Now start (globally) substituting
tmp=""
while read line; do
counter=0
while [[ $line =~ $match(.*) ]]; do
eval tmp='"${tmp}${line%${BASH_REMATCH[0]}}"'"${subst}"
line="${BASH_REMATCH[$(( ${#BASH_REMATCH[@]} - 1 ))]}"
done
echo "${tmp}${line}"
done
}
resub "$@"
##################
### EXAMPLES ###
##################
### % echo "The quick brown fox jumps quickly over the lazy dog" | resub quick slow
### The slow brown fox jumps slowly over the lazy dog
### % echo "The quick brown fox jumps quickly over the lazy dog" | resub 'quick ([^ ]+) fox' 'slow $1 sheep'
### The slow brown sheep jumps quickly over the lazy dog
### % animal="sheep"
### % echo "The quick brown fox 'jumps' quickly over the \"lazy\" \$dog" | resub 'quick ([^ ]+) fox' "\"\$low\" \${1} '$animal'"
### The "$low" brown 'sheep' 'jumps' quickly over the "lazy" $dog
### % echo "one two three four five" | resub "one ([^ ]+) three ([^ ]+) five" 'one $2 three $1 five'
### one four three two five
### % echo "one two one four five" | resub "one ([^ ]+) " 'XXX $1 '
### XXX two XXX four five
### % echo "one two three four five one six three seven eight" | resub "one ([^ ]+) three ([^ ]+) " 'XXX $1 YYY $2 '
### XXX two YYY four five XXX six YYY seven eight
H/T to @Charles Duffy re: (.*)$match(.*)
If you want to use names, try a namedtuple:
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
for pair in pairs:
print("First = {}, second = {}".format(pair.first, pair.second))
Suggest replacing this:
char str[1024];
char tmp = '.';
strcat(str, tmp);
with this:
char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()
strcat(str, tmp); //
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
You may or may not need JavaHL depending on your OS. In addition to other suggestions just posting this here.
For other OS see this source: http://subclipse.tigris.org/wiki/JavaHL
I converted into millisecond and deducted days else month and year won't change and logical
var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10), // Year
parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();
Hope helps
Here is a simple function for converting a byte buffer to string:
public String byteBufferToString(ByteBuffer bufferData) {
byte[] buffer = new byte[bufferData.readableByteCount()];
// read bufferData and insert into buffer
data.read(buffer);
// CharsetUtil supports UTF_16, ASCII, and many more
String text = new String(buffer, CharsetUtil.UTF_8);
System.out.println("Text: "+text);
return text;
}
The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__
)
>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
I came up with 4 methods to achieve the results. Here is demo
Method 1:
#a {
margin-right: auto;
}
Method 2:
#a {
flex-grow: 1;
}
Method 3:
#b {
margin-left: auto;
}
Method 4:
#container {
justify-content: space-between;
}
Yes, a T...
is only a syntactic sugar for a T[]
.
The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.
If the last formal parameter is a variable arity parameter of type
T
, it is considered to define a formal parameter of typeT[]
. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.
Here's an example to illustrate:
public static String ezFormat(Object... args) {
String format = new String(new char[args.length])
.replace("\0", "[ %s ]");
return String.format(format, args);
}
public static void main(String... args) {
System.out.println(ezFormat("A", "B", "C"));
// prints "[ A ][ B ][ C ]"
}
And yes, the above main
method is valid, because again, String...
is just String[]
. Also, because arrays are covariant, a String[]
is an Object[]
, so you can also call ezFormat(args)
either way.
null
How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.
Consider this example:
static void count(Object... objs) {
System.out.println(objs.length);
}
count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!
Due to how varargs are resolved, the last statement invokes with objs = null
, which of course would cause NullPointerException
with objs.length
. If you want to give one null
argument to a varargs parameter, you can do either of the following:
count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"
The following is a sample of some of the questions people have asked when dealing with varargs:
As you've found out, the following doesn't "work":
String[] myArgs = { "A", "B", "C" };
System.out.println(ezFormat(myArgs, "Z"));
// prints "[ [Ljava.lang.String;@13c5982 ][ Z ]"
Because of the way varargs work, ezFormat
actually gets 2 arguments, the first being a String[]
, the second being a String
. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.
Here are some useful helper methods:
static <T> T[] append(T[] arr, T lastElement) {
final int N = arr.length;
arr = java.util.Arrays.copyOf(arr, N+1);
arr[N] = lastElement;
return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
final int N = arr.length;
arr = java.util.Arrays.copyOf(arr, N+1);
System.arraycopy(arr, 0, arr, 1, N);
arr[0] = firstElement;
return arr;
}
Now you can do the following:
String[] myArgs = { "A", "B", "C" };
System.out.println(ezFormat(append(myArgs, "Z")));
// prints "[ A ][ B ][ C ][ Z ]"
System.out.println(ezFormat(prepend(myArgs, "Z")));
// prints "[ Z ][ A ][ B ][ C ]"
It doesn't "work":
int[] myNumbers = { 1, 2, 3 };
System.out.println(ezFormat(myNumbers));
// prints "[ [I@13c5982 ]"
Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:
Integer[] myNumbers = { 1, 2, 3 };
System.out.println(ezFormat(myNumbers));
// prints "[ 1 ][ 2 ][ 3 ]"
Use translate:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
Caveat: Only works on ascii strings.
I had window 7 (64 bit) and Python 2.7.12,
I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.
exec
will also return a ChildProcess object that is an EventEmitter.
var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');
coffeeProcess.stdout.on('data', function(data) {
console.log(data);
});
OR pipe
the child process's stdout to the main stdout.
coffeeProcess.stdout.pipe(process.stdout);
OR inherit stdio using spawn
spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });
The nil pointer dereference is in line 65 which is the defer in
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
If err!= nil then res==nil and res.Body panics. Handle err before defering the res.Body.Close().
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
First create a real, permanent table as a template that has the required layout for the returned temporary table, using a naming convention that identifies it as a template and links it symbolically to the SP, eg tmp_SPName_Output. This table will never contain any data.
In the SP, use INSERT to load data into a temp table following the same naming convention, e.g. #SPName_Output which is assumed to exist. You can test for its existence and return an error if it does not.
Before calling the sp use this simple select to create the temp table:
SELECT TOP(0) * INTO #SPName_Output FROM tmp_SPName_Output;
EXEC SPName;
-- Now process records in #SPName_Output;
This has these distinct advantages:
I believe that must-revalidate
means :
Once the cache expires, refuse to return stale responses to the user even if they say that stale responses are acceptable.
Whereas no-cache
implies :
must-revalidate
plus the fact the response becomes stale right away.
If a response is cacheable for 10 seconds, then must-revalidate
kicks in after 10 seconds, whereas no-cache
implies must-revalidate
after 0 seconds.
At least, that's my interpretation.
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
console.log()
in java is System.out.println();
to put text on the next line
And System.out.print();
puts text on the same line.
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
No, but you could cast the whole expression rather than the sub-components of that expression. Actually, that probably makes it less readable in this case.
put the logic in
afterTextChanged(Editable s) {
string str = s.toString()
// use the string str
}
You can't have multiple lines in a text box, you need a textarea. Then it works with \n
between the values.
When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.
function() {
var a = 1;
console.log(a); // works
}
console.log(a); // fails
If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
var a = 1;
function() {
console.log(a); // works
}
console.log(a); // works
When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.
This is how we normally expect things to work.
A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.
The scope object and all its local variables are tied to the function and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.
Here's a really simple example in JavaScript that illustrates the point:
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a
. The variable a
is in scope for the inner function.
Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc
so that it persists after outer
has exited, all of the variables that were in scope when inner
was defined also persist. The variable a
has been closed over -- it is within a closure.
Note that the variable a
is totally private to fnc
. This is a way of creating private variables in a functional programming language such as JavaScript.
As you might be able to guess, when I call fnc()
it prints the value of a
, which is "1".
In a language without closure, the variable a
would have been garbage collected and thrown away when the function outer
exited. Calling fnc would have thrown an error because a
no longer exists.
In JavaScript, the variable a
persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.
a
belongs to the scope of outer
. The scope of inner
has a parent pointer to the scope of outer
. fnc
is a variable which points to inner
. a
persists as long as fnc
persists. a
is within the closure.
You can use push and pull to change column ordering. You pull one column and push the other on large devices:
<div class="row">
<div class="col-lg-6 col-md-6 col-lg-pull-6">elements 1</div>
<div class="col-lg-6 col-md-6 col-lg-push-6">
<div>
elements 2
</div>
</div>
</div>
I recently set up a script that does this.
As David Brabant pointed out, you can use the System.Net.WebRequest
class to do an HTTP request.
To check whether it is operational, you should use the following example code:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:
Here's a heavy-weight solution that gets you indenting, plus all the HTML pretty-printing you don't necessarily want to care about while you're editing.
First, download Tidy. Make sure you add the binary to your path, so you can call it from any location.
Next, create a config file describing your favorite HTML flavor. Documentation is not great for Tidy, but here's an overview, and a list of all the options. Here's my config file:
bare: yes
break-before-br: no
clean: yes
drop-proprietary-attributes: yes
fix-uri: yes
indent-spaces: 4
indent: yes
logical-emphasis: yes
markup: yes
output-xhtml: yes
quiet: yes
quote-marks: yes
replace-color: yes
tab-size: 4
uppercase-tags: no
vertical-space: yes
word-2000: yes
wrap: 0
Save this as tidyrc_html.txt
in your ftplugin
folder (under vimfiles).
One more file: add the following line to (or create) html.vim
, also in ftplugin
:
map <leader>tidy :%! tidy -config ~/vimfiles/ftplugin/tidyrc_html.txt <CR>
To use it, just open an HTML file, and type /tidy
. (That /
is the <leader>
key.)
There you go! Not a quick solution, by any means, but now you're a bit better equipped for editing those huge, messed-up HTML files.
Eclipse itself will add the @Override
annotation when you tell it to "generate unimplemented methods" during creation of a class that implements an interface.
You can check whether the connection was lost or not by using this function:-
var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});
Hope it will help you.
In your action you need first to load companies like so :
$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();
This will make the companies variable available in the view, and it should render the HTML correctly.
Try to use postman chrome extension to debug your view.
Here is a dplyr solution
library(dplyr)
library(stringr)
Censor_consistently <- function(x){
str_replace(x, '^\\s*([<>])\\s*(\\d+)', '\\1\\2')
}
test_df <- tibble(x = c('0.001', '<0.002', ' < 0.003', ' > 100'), y = 4:1)
mutate_all(test_df, funs(Censor_consistently))
# A tibble: 4 × 2
x y
<chr> <chr>
1 0.001 4
2 <0.002 3
3 <0.003 2
4 >100 1
from jquery api
Added to jQuery in version 1.4, the .delay()
method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show()
or .hide()
which do not use the effects queue.
CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
dim lastRow as long 'in VBA it's a long
lastrow = wks.range("A65000").end(xlup).row
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div
= document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i <
a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
_x000D_
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">home</a>
<a href="#base">contact</a>
</div>
</div>
_x000D_
I had this on a form where the Recordsource is dynamic.
The Sql was fine, answer is to trap the error!
Private Sub Form_Error(DataErr As Integer, Response As Integer)
' Debug.Print DataErr
If DataErr = 3075 Then
Response = acDataErrContinue
End If
End Sub
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text
Príliš žlutoucký kun
úpel dábelské ódy
and the file uses windows-1250 format. If you use FileReader you will get this result:
P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy
So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.
Example:
String encoding = "Cp1250";
File file = new File("foo.txt");
if (file.exists()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("file doesn't exist");
}
In case you want to read the file character after character do not use BufferedReader.
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
int data = isr.read();
while (data != -1) {
System.out.print((char) data);
data = isr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.
Here is how I did it:
CSS:
.my-flex-card > div > div.card {
height: calc(100% - 15px);
margin-bottom: 15px;
}
HTML:
<div class="row my-flex-card">
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
aaaa
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
bbbb
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
cccc
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
dddd
</div>
</div>
</div>
</div>
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
In my case the element that generated the Exception was a button belonging to a form. I replaced
WebElement btnLogin = driver.findElement(By.cssSelector("button"));
btnLogin.click();
with
btnLogin.submit();
My environment was chromedriver windows 10
My issue was resolved by updating the metadata part of the connection string. Apparently it was pointing at the wrong .csdl / .ssdl / .msl reference.
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at
carousel.carousel-fade
in the CSS of the following examples:
To convert an Array[Row] to DataFrame or Dataset, the following works elegantly:
Say, schema is the StructType for the row,then
val rows: Array[Row]=...
implicit val encoder = RowEncoder.apply(schema)
import spark.implicits._
rows.toDS
A tad more generic copy/paste function for your project.
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
The header field name registry is defined in RFC3864, and there's nothing special with "X-".
As far as I can tell, there are no guidelines for private headers; in doubt, avoid them. Or have a look at the HTTP Extension Framework (RFC 2774).
It would be interesting to understand more of the use case; why can't the information be added to the message body?
Box shadows can use commas to have multiple effects, just like with background images (in CSS3).
A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Don't want to check rather on MIME than on whatever extention the user is lying? If so then it's less than one line:
<input type="file" id="userfile" accept="image/*|video/*" required />
After multiple tests, this is the best way I found :)
Set<User> test = httpService.get(url).toResponseSet(User[].class);
All you need there
public <T> Set<T> toResponseSet(Class<T[]> setType) {
HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
return Sets.newHashSet(response.getBody());
}
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.
I use:
jps
Depending on your installation a running Zookeeper would look like
HQuorumPeer
or sth. with zookeeper in it's name.
You don't put a component in directives
You register it in @NgModule
declarations:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyChildComponent ],
bootstrap: [ App ]
})
and then You just put it in the Parent's Template HTML as : <my-child></my-child>
That's it.
You might be after something that the scrollTo plugin from Ariel Flesler does really well.
NSString *path = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
Use -H or --header
.
Man page: http://curl.haxx.se/docs/manpage.html#-H
If this command not help
git config http.postBuffer 524288000
Try to change ssh method to https
git remote -v
git remote rm origin
git remote add origin https://github.com/username/project.git
An idea would be that display:flex;
with flex-direction: row;
is filling the container
div with .flex-1
and .flex-2
, but that does not mean that .flex-2
has a default height:100%;
, even if it is extended to full height.
And to have a child element (.flex-2-child
) with height:100%;
, you'll need to set the parent to height:100%;
or use display:flex;
with flex-direction: row;
on the .flex-2
div too.
From what I know, display:flex
will not extend all your child elements height to 100%.
A small demo, removed the height from .flex-2-child
and used display:flex;
on .flex-2
:
http://jsfiddle.net/2ZDuE/3/
Working with Oracle, I was trying to insert a default value for an Enum
I found the following to work the best.
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private EnumType myProperty = EnumType.DEFAULT_VALUE;
The first thing you should try is:
sudo pip uninstall pip
On many environments that doesn't work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.
With rails >= 3.0, you can simply use the placeholder
option.
f.text_field :attr, placeholder: "placeholder text"
As others have said, # coding:
specifies the encoding the source file is saved in. Here are some examples to illustrate this:
A file saved on disk as cp437 (my console encoding), but no encoding declared
b = 'über'
u = u'über'
print b,repr(b)
print u,repr(u)
Output:
File "C:\ex.py", line 1
SyntaxError: Non-ASCII character '\x81' in file C:\ex.py on line 1, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for details
Output of file with # coding: cp437
added:
über '\x81ber'
über u'\xfcber'
At first, Python didn't know the encoding and complained about the non-ASCII character. Once it knew the encoding, the byte string got the bytes that were actually on disk. For the Unicode string, Python read \x81, knew that in cp437 that was a ü, and decoded it into the Unicode codepoint for ü which is U+00FC. When the byte string was printed, Python sent the hex value 81
to the console directly. When the Unicode string was printed, Python correctly detected my console encoding as cp437 and translated Unicode ü to the cp437 value for ü.
Here's what happens with a file declared and saved in UTF-8:
++ber '\xc3\xbcber'
über u'\xfcber'
In UTF-8, ü is encoded as the hex bytes C3 BC
, so the byte string contains those bytes, but the Unicode string is identical to the first example. Python read the two bytes and decoded it correctly. Python printed the byte string incorrectly, because it sent the two UTF-8 bytes representing ü directly to my cp437 console.
Here the file is declared cp437, but saved in UTF-8:
++ber '\xc3\xbcber'
++ber u'\u251c\u255dber'
The byte string still got the bytes on disk (UTF-8 hex bytes C3 BC
), but interpreted them as two cp437 characters instead of a single UTF-8-encoded character. Those two characters where translated to Unicode code points, and everything prints incorrectly.
The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.
The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.
The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.
Good ideas:
this > that ? alert(this) : alert(that); //nice and short, little loss of meaning
if(expression) //longer blocks but organized and can be grasped by humans
{
//35 lines of code here
}
else if (something_else)
{
//40 more lines here
}
else if (another_one) /etc, etc
{
...
Less good:
this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.
if(this != that) //Ternary would be done by now
{
x = this;
}
else
}
x = this + 2;
}
A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
use uniform js plugin
to style input of any type, select, textarea.
The URL is http://uniformjs.com/
A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.
+------------------+----------------------+
| Name Begins With | Variable Scope |
+------------------+----------------------+
| $ | A global variable |
| @ | An instance variable |
| [a-z] or _ | A local variable |
| [A-Z] | A constant |
| @@ | A class variable |
+------------------+----------------------+
Just edit your .git/config file. For example; if you have a "common" submodule you can do this in the super-module:
git config submodule.common.url /data/my_local_common
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
public Form1()
{
InitializeComponent();
comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
comboBox.DisplayMember = "Name";
}
public class EnumWithName<T>
{
public string Name { get; set; }
public T Value { get; set; }
public static EnumWithName<T>[] ParseEnum()
{
List<EnumWithName<T>> list = new List<EnumWithName<T>>();
foreach (object o in Enum.GetValues(typeof(T)))
{
list.Add(new EnumWithName<T>
{
Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
Value = (T)o
});
}
return list.ToArray();
}
}
public enum SearchType
{
Value_1,
Value_2
}
The modern approach is to move away from VBA for important code, and write a .NET managed Add-In using c# or vb.net, there are a lot of resources for this on the www, and you could use the Express version of MS Visual Studio
What about something like this :
cat texte.txt | sed -e 's/\s/,/g' > texte-new.txt
(Yes, with some useless catting and piping ; could also use < to read from the file directly, I suppose -- used cat first to output the content of the file, and only after, I added sed to my command-line)
EDIT : as @ghostdog74 pointed out in a comment, there's definitly no need for thet cat/pipe ; you can give the name of the file to sed :
sed -e 's/\s/,/g' texte.txt > texte-new.txt
If "texte.txt" is this way :
$ cat texte.txt
this is a text
in which I want to replace
spaces by commas
You'll get a "texte-new.txt" that'll look like this :
$ cat texte-new.txt
this,is,a,text
in,which,I,want,to,replace
spaces,by,commas
I wouldn't go just replacing the old file by the new one (could be done with sed -i, if I remember correctly ; and as @ghostdog74 said, this one would accept creating the backup on the fly) : keeping might be wise, as a security measure (even if it means having to rename it to something like "texte-backup.txt")
You can use the toLowerCase()
method:
public boolean contains( String haystack, String needle ) {
haystack = haystack == null ? "" : haystack;
needle = needle == null ? "" : needle;
// Works, but is not the best.
//return haystack.toLowerCase().indexOf( needle.toLowerCase() ) > -1
return haystack.toLowerCase().contains( needle.toLowerCase() )
}
Then call it using:
if( contains( str1, str2 ) ) {
System.out.println( "Found " + str2 + " within " + str1 + "." );
}
Notice that by creating your own method, you can reuse it. Then, when someone points out that you should use contains
instead of indexOf
, you have only a single line of code to change.
StandardScaler performs the task of Standardization. Usually a dataset contains variables that are different in scale. For e.g. an Employee dataset will contain AGE column with values on scale 20-70 and SALARY column with values on scale 10000-80000.
As these two columns are different in scale, they are Standardized to have common scale while building machine learning model.
In the ideal case we should have enough memory to read the file in one read operation. That would be the best performer because we let the system manage File System , allocation units and HDD at will. In practice you are fortunate to know the file sizes in advance, just use the average file size rounded up to 4K (default allocation unit on NTFS). And best of all : create a benchmark to test multiple options.
Create modal dialog in HTML with id="confirmation" and use function showConfirmation.
Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.
showConfirmation = function(title, message, success, cancel) {
title = title ? title : 'Are you sure?';
var modal = $("#confirmation");
modal.find(".modal-title").html(title).end()
.find(".modal-body").html(message).end()
.modal({ backdrop: 'static', keyboard: false })
.on('hidden.bs.modal', function () {
modal.unbind();
});
if (success) {
modal.one('click', '.modal-footer .btn-primary', success);
}
if (cancel) {
modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
}
};
// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
event.preventDefault();
var self = $(this);
var url = $(this).data('url');
var success = function(){
alert('window.location.href=url');
}
var cancel = function(){
alert('Cancel');
};
if (self.data('confirmation')) {
var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
var message = self.data('confirmation');
showConfirmation(title, message, success, cancel);
} else {
success();
}
});
Check your file: settings.gradle
for presence lines with included subprojects (for example:
include chapter1-bookstore
)
Just use Val()
:
currentLoad = Int(Val([f4]))
Now currentLoad
has a integer value, zero if [f4]
is not numeric.
Try this:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
ice
Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.
Since unable to run adb at all on my development machine, I found a different approach.
Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.
Master-machine : computer where development goes on, with only USB-C connectors
Slave-machine: another computer with USB and in same WiFi
adb usb && adb tcpip 5555
from thereOn master machine
deko$: adb devices
List of devices attached
deko$: adb connect 10.0.20.153:5555
connected to 10.0.20.153:5555
Now Android Studio or Xamarin can install and run app on the phone
Sidenote:
I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.
For one table
truncate table [table name]
For all tables
EXEC sp_MSforeachtable @command1="truncate table ?"
TL;DR
npm uninstall node-sass
npm install [email protected]
Or, if using yarn (default in newer CRA versions)
yarn remove node-sass
yarn add [email protected]
Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.
Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.
Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).
Uninstall node-sass
npm uninstall node-sass
Then install the latest version (before 5.0)
npm install [email protected]
Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass
instead, which is a node distribution of dart-sass compiled to pure JavaScript.
Be warned though:
Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation
Just to answer a native way to do this that finally worked, everything had to be casted as a varchar
ALTER PROCEDURE [clickpay].[sp_GetDocuments]
@Submid bigint
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @raw_sql varchar(max)
DECLARE @columnHeader VARCHAR(max)
SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'
DECLARE @ColumnList VARCHAR(max)
SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'
SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + 'Documents where Submid = ' + CAST(@Submid AS VARCHAR)
-- Insert statements for procedure here
exec(@raw_sql)
END
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
I had the same problem. In my case, the issue was that someone used BeanUtils to copy the properties of one entity to another, so we ended up having two entities referencing the same collection.
Given that I spent some time investigating this issue, I would recommend the following checklist:
Look for scenarios like entity1.setCollection(entity2.getCollection())
and getCollection
returns the internal reference to the collection (if getCollection() returns a new instance of the collection, then you don't need to worry).
Look if clone()
has been implemented correctly.
Look for BeanUtils.copyProperties(entity1, entity2)
.
Following Aditya Singh's answer the generated (unsigned) apk would not install on my phone. I had to generate a signed apk using the instructions here.
The following worked for me:
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
Place the my-release-key.keystore
file under the android/app
directory in your project folder. Then edit the file
~/.gradle/gradle.properties
and add the following (replace ****
with the correct keystore password, alias and key password)
MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=****
MYAPP_RELEASE_KEY_PASSWORD=****
If you're using MacOS, you can store your password in the keychain using the instructions here instead of storing it in plaintext.
Then edit app/build.gradle and ensure the following are there (the sections with signingConfigs signingConfig may need to be added) :
...
android {
...
defaultConfig { ... }
signingConfigs {
release {
if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
storeFile file(MYAPP_RELEASE_STORE_FILE)
storePassword MYAPP_RELEASE_STORE_PASSWORD
keyAlias MYAPP_RELEASE_KEY_ALIAS
keyPassword MYAPP_RELEASE_KEY_PASSWORD
}
}
}
buildTypes {
release {
...
signingConfig signingConfigs.release
}
}
}
...
Then run the command cd android && ./gradlew assembleRelease
,
For Windows 'cd android' and then run gradlew assembleRelease
command , and find your signed apk under android/app/build/outputs/apk/app-release.apk
Could you please try this ?
Create another item in post such as post.link then assign the link to it before send post to the render function.
post.link = '/posts/+ id.toString();
So, the above render function should be following instead.
return <li key={post.id}><a href={post.link}>{post.title}</a></li>
Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the "X" button:
def quit(self): # Your exit routine
self.root.destroy()
self.root.protocol("WM_DELETE_WINDOW", self.quit) # Sets the command for the "X" button
Button(text="Quit", command=self.quit) # No ()
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);
int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days
int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days
int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365
When I use a non-default modules in my scripts I call the function below. Beside the module name you can provide a minimum version.
# See https://www.powershellgallery.com/ for module and version info
Function Install-ModuleIfNotInstalled(
[string] [Parameter(Mandatory = $true)] $moduleName,
[string] $minimalVersion
) {
$module = Get-Module -Name $moduleName -ListAvailable |`
Where-Object { $null -eq $minimalVersion -or $minimalVersion -ge $_.Version } |`
Select-Object -Last 1
if ($null -ne $module) {
Write-Verbose ('Module {0} (v{1}) is available.' -f $moduleName, $module.Version)
}
else {
Import-Module -Name 'PowershellGet'
$installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
if ($null -ne $installedModule) {
Write-Verbose ('Module [{0}] (v {1}) is installed.' -f $moduleName, $installedModule.Version)
}
if ($null -eq $installedModule -or ($null -ne $minimalVersion -and $installedModule.Version -lt $minimalVersion)) {
Write-Verbose ('Module {0} min.vers {1}: not installed; check if nuget v2.8.5.201 or later is installed.' -f $moduleName, $minimalVersion)
#First check if package provider NuGet is installed. Incase an older version is installed the required version is installed explicitly
if ((Get-PackageProvider -Name NuGet -Force).Version -lt '2.8.5.201') {
Write-Warning ('Module {0} min.vers {1}: Install nuget!' -f $moduleName, $minimalVersion)
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force
}
$optionalArgs = New-Object -TypeName Hashtable
if ($null -ne $minimalVersion) {
$optionalArgs['RequiredVersion'] = $minimalVersion
}
Write-Warning ('Install module {0} (version [{1}]) within scope of the current user.' -f $moduleName, $minimalVersion)
Install-Module -Name $moduleName @optionalArgs -Scope CurrentUser -Force -Verbose
}
}
}
usage example:
Install-ModuleIfNotInstalled 'CosmosDB' '2.1.3.528'
Please let me known if it's usefull (or not)
Login Helper of your site
$loginUrl = $helper->getLoginUrl('xyz.com/user_by_facebook/', $permissions);
and in facebook application dashboard (Under products tab : Facebook Login )
Valid OAuth redirect URIs should also be same to xyz.com/user_by_facebook/
as mentioned earlier while making request from web
This is rather a method than just a single script but gives you much more flexibility.
First of all There are 3 objects:
ColumnActionList
] -> holds data as
parameter proc_PivotPrepare
] -> prepares our dataproc_PivotExecute
] -> execute the scriptCREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO
CREATE PROCEDURE [dbo].[proc_PivotPrepare]
(
@DB_Name nvarchar(128),
@TableName nvarchar(128)
)
AS
SELECT @DB_Name = ISNULL(@DB_Name,db_name())
DECLARE @SQL_Code nvarchar(max)
DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));
SELECT @SQL_Code = 'SELECT [<| SQL_Code |>] = '' '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
+ 'UNION ALL '
+ 'SELECT ''-----|'''
+ 'UNION ALL '
+ 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''INSERT INTO @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
+ 'FROM [' + @DB_Name + '].sys.columns '
+ 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
EXECUTE SP_EXECUTESQL @SQL_Code;
GO
CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions ColumnActionList ReadOnly
,@TableName nvarchar(128)
)
AS
--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################
IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions;
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;
--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################
DECLARE @ColumnName nvarchar(128)
DECLARE @Destiny nchar(1)
DECLARE @ListOfColumns_Stable nvarchar(max)
DECLARE @ListOfColumns_Dimension nvarchar(max)
DECLARE @ListOfColumns_Variable nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################
DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
END
CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;
--############################
--###| Cursor for List of Dimension Columns
--############################
DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
END
CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;
--############################
--###| Cursor for List of Variable Columns
--############################
DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
END
CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;
SELECT @ListOfColumns_Variable = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);
--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';
DECLARE @DIM_ID smallint;
SELECT @DIM_ID = 1;
DECLARE @SQL_Dimentions nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions;
SELECT @SQL_Dimentions = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
+ ' INTO ##ALL_Dimentions '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
END
SELECT @SQL_Dimentions = @SQL_Dimentions + ' )x';
EXECUTE SP_EXECUTESQL @SQL_Dimentions;
--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @StabPos_ID smallint;
SELECT @StabPos_ID = 1;
DECLARE @SQL_MainStableColumnTable nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns;
SELECT @SQL_MainStableColumnTable = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
+ ' INTO ##ALL_StableColumns '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
BEGIN
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
END
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + ' )x';
EXECUTE SP_EXECUTESQL @SQL_MainStableColumnTable;
--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################
DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''
DECLARE @i smallint
IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab;
SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
+ ' INTO ##FinalTab '
+ 'FROM ' + @TableName + ' t '
+ 'JOIN ##ALL_Dimentions dim '
+ 'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
SELECT @i = 2
WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
SELECT @i = @i +1
END
EXECUTE SP_EXECUTESQL @FULL_SQL_1
--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';
DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;
DECLARE @FinalCode nvarchar(max)
SELECT @FinalCode = ' SELECT ID1.*'
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @z = 1
WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] = ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
SELECT @z = @z + 1
END
SELECT @y = @y + 1
END
SELECT @FinalCode = @FinalCode +
' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @x = 1
SELECT @FinalCode = @FinalCode
+ ' LEFT JOIN (SELECT ' + @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable
+ ' FROM ##FinalTab WHERE [xxx_ID_xxx] = '
+ CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))
+ ' ON 1 = 1'
WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
SELECT @x = @x +1
END
SELECT @y = @y + 1
END
SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;
From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)
Names and datatypes will be defined automatically!
I cant recommend it for any production environments but does the job for adhoc BI requests.
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
You could us the 'net use' command:
var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);
If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2
Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).
A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with
for (const field of Object.keys(this.formErrors)) {
I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.
Just type COMMIT and execute it F5
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
String.prototype.startsWith = function(needle)
{
return this.indexOf(needle) === 0;
};
You can use this function instead if curl is installed on your system:
function get_url_contents($url){
if (function_exists('file_get_contents')) {
$result = @file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
For mysql you have limit, you can fire query as :
SELECT * FROM table limit 100` -- get 1st 100 records
SELECT * FROM table limit 100, 200` -- get 200 records beginning with row 101
For Oracle you can use rownum
See mysql select syntax and usage for limit
here.
For SQLite, you have limit, offset
. I haven't used SQLite but I checked it on SQLite Documentation. Check example for SQLite here.
Use:
(/bookstore/book[@location='US'])[1]
This will first get the book elements with the location attribute equal to 'US'. Then it will select the first node from that set. Note the use of parentheses, which are required by some implementations.
Note, this is not the same as /bookstore/book[1][@location='US']
unless the first element also happens to have that location attribute.
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
The jQuery documentation says this "It is also displayed [the handler execution result] if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered.".
Try the keyup and keydown events, like this:
$("#kat").keydown(function(){
alert("Hello");
});
If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.
<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
Use the shell error handling for unset variables (note the double $
):
$ cat Makefile
foo:
echo "something is set to $${something:?}"
$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127
$ make foo something=x
echo "something is set to ${something:?}"
something is set to x
If you need a custom error message, add it after the ?
:
$ cat Makefile
hello:
echo "hello $${name:?please tell me who you are via \$$name}"
$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127
$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus
I know this is an old post but I would like to add my answer for future reference.
I use jQuery and css to style my tooltips: easiest-tooltip-and-image-preview-using-jquery
(for a demo: http://cssglobe.com/lab/tooltip/02/)
On my static websites this just worked great. However, during migrating to Wordpress it stopped. My solution was to change tags like <br> and <span>
into this: <br> and <span>
This works for me.
To illustrate the mechanics of Antoine's answer:
protocol SomeProtocol {
func aMethod()
}
extension SomeProtocol {
func aMethod() {
print("extensionImplementation")
}
}
class protocolImplementingObject: SomeProtocol {
}
class protocolImplementingMethodOverridingObject: SomeProtocol {
func aMethod() {
print("classImplementation")
}
}
let noOverride = protocolImplementingObject()
let override = protocolImplementingMethodOverridingObject()
noOverride.aMethod() //prints "extensionImplementation"
override.aMethod() //prints "classImplementation"
Here is a more strict version:
^([-+]?\d{1,2}[.]\d+),\s*([-+]?\d{1,3}[.]\d+)$
-90
-- +90
-180
-- +180
Another option is
devtools::unload("your-package")
This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
I saw this somewhere else. I am using 2016 Excel. What worked for me was to use YYYY Quarters (I was looking for quarterly data). So, I had the source data sorted as YYYY xQ. 2016 1Q, 2016 2Q, 2016 3Q, 2016, 4Q, 2017 1Q, 2017 2Q... You get the idea.
The String
class exposes some methods to enable this, such as IndexOf
and LastIndexOf
, so that you may do this:
Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then
End If
var test = parseInt($("#testid").val());
What about SYSDATE() ?
<?php
$db = mysql_connect('localhost','user','pass');
mysql_select_db('test_db');
$stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}','{$last}','SYSDATE())";
$rslt = mysql_query($stmt);
?>
Look at Difference between NOW(), SYSDATE() & CURRENT_DATE() in MySQL for more info about NOW() and SYSDATE().
Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).
The binding flag you will need is: System.Reflection.BindingFlags.NonPublic
Any given Spring context can only have one bean for any given id or name. In the case of the XML id
attribute, this is enforced by the schema validation. In the case of the name
attribute, this is enforced by Spring's logic.
However, if a context is constructed from two different XML descriptor files, and an id
is used by both files, then one will "override" the other. The exact behaviour depends on the ordering of the files when they get loaded by the context.
So while it's possible, it's not recommended. It's error-prone and fragile, and you'll get no help from Spring if you change the ID of one but not the other.
The UPDATE syntax is:
[ WITH [ RECURSIVE ] with_query [, ...] ] UPDATE [ ONLY ] table [ [ AS ] alias ] SET { column = { expression | DEFAULT } | ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...] [ FROM from_list ] [ WHERE condition | WHERE CURRENT OF cursor_name ] [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
In your case I think you want this:
UPDATE vehicles_vehicle AS v
SET price = s.price_per_vehicle
FROM shipments_shipment AS s
WHERE v.shipment_id = s.id
Something like this will list and extract the files one by one, if you want to use SharpZipLib:
var zip = new ZipInputStream(File.OpenRead(@"C:\Users\Javi\Desktop\myzip.zip"));
var filestream = new FileStream(@"C:\Users\Javi\Desktop\myzip.zip", FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
Console.WriteLine(item.Name);
using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
{
// stream with the file
Console.WriteLine(s.ReadToEnd());
}
}
Based on this example: content inside zip file
For Chrome to display the page icon (favicon), you need to check your website from a hosting server or you can use local host while developing and testing your website on your PC.
With that row
var element = {};
you define element
to be a plain object. The native JavaScript object has no push()
method. To add new items to a plain object use this syntax:
element[ yourKey ] = yourValue;
On the other hand you could define element
as an array using
var element = [];
Then you can add elements using push()
.
That's a loop that says, okay, for every time that i
is smaller than 8, I'm going to do whatever is in the code block. Whenever i
reaches 8, I'll stop. After each iteration of the loop, it increments i
by 1 (i++
), so that the loop will eventually stop when it meets the i < 8
(i
becomes 8, so no longer is smaller than) condition.
For example, this:
for (int i = 0; i < 8; i++)
{
Console.WriteLine(i);
}
Will output: 01234567
See how the code was executed 8 times?
In terms of arrays, this can be helpful when you don't know the size of the array, but you want to operate on every item of it. You can do:
Disclaimer: This following code will vary dependent upon language, but the principle remains the same
Array yourArray;
for (int i = 0; i < yourArray.Count; i++)
{
Console.WriteLine(yourArray[i]);
}
The difference here is the number of execution times is entirely dependent on the size of the array, so it's dynamic.
OK! never mind; I found the solution. with 403 Suspected that the HTTP is not going to the right URL.
Change the file which has the login credentials stored the ~/.docker/config.json
from the default generated of
{
"auths": {
"docker.io": {
"auth": "XXXXXXXXXXXXX",
"email": "[email protected]"
}
}
}
to - Note the change from docker.io -> index.docker.io/v1. That is the change.
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "XXXXXXXXXXXXX",
"email": "[email protected]"
}
}
}
Hope that helps.
Note that the auth field should be 'username:password" base64 encoded. for example: "username:password" base64 encoded is "dXNlcm5hbWU6cGFzc3dvcmQ="
so your file would contain:
"auth": "dXNlcm5hbWU6cGFzc3dvcmQ="
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
The idiomatic way would be to use list comprehension:
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]
or, if you need to maintain the reference to the original list:
myList[:] = [x / myInt for x in myList]
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
Given an instance of the struct, you set the values.
student thisStudent;
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
thisStudent.s_id = int.Parse(Console.ReadLine());
thisStudent.s_name = Console.ReadLine();
thisStudent.c_name = Console.ReadLine();
thisStudent.s_dob = Console.ReadLine();
Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.
Best way to do this is to use a function:
html
<div ng-repeat="product in products | filter: myFilter">
javascript
$scope.myFilter = function (item) {
return item === 'red' || item === 'blue';
};
Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.
From Files and Filegroups Architecture
Secondary data files
Secondary data files make up all the data files, other than the primary data file. Some databases may not have any secondary data files, while others have several secondary data files. The recommended file name extension for secondary data files is .ndf.
Also from file extension NDF - Microsoft SQL Server secondary data file
See Understanding Files and Filegroups
Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.
The recommended file name extension for secondary data files is .ndf.
/
For example, three files, Data1.ndf, Data2.ndf, and Data3.ndf, can be created on three disk drives, respectively, and assigned to the filegroup fgroup1. A table can then be created specifically on the filegroup fgroup1. Queries for data from the table will be spread across the three disks; this will improve performance. The same performance improvement can be accomplished by using a single file created on a RAID (redundant array of independent disks) stripe set. However, files and filegroups let you easily add new files to new disks.
Have a look at the link below, which suggests it is possible to alter the contents of an iFrame within your page with Javascript, although you are most likely to run into a few cross browser issues. If you can do this you can use the javascript in your page to add hidden dom elements to the iFrame containing your values, which the iFrame can read. Accessing the document inside an iFrame
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
Further to @pmg's answer, note that you can do both operations in one statement:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;
This will likely work as expected but behavior is undefined in C standard.
Screen.FromControl
, Screen.FromPoint
and Screen.FromRectangle
should help you with this. For example in WinForms it would be:
class MyForm : Form
{
public Rectangle GetScreen()
{
return Screen.FromControl(this).Bounds;
}
}
I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method.
static class ExtensionsForWPF
{
public static System.Windows.Forms.Screen GetScreen(this Window window)
{
return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
}
}
See docs.python.org:
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
If you need to see the output of the execute, use CALL
together with or instead of START
.
Example:
CALL "C:\Program Files\Certain Directory\file.exe" -param
PAUSE
This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE
after the call or else the window may close instantly.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984";
var d1 = new Date(dString);
var d2 = new Date();
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
Code sample taken from here.
That one shows up correctly as HTML5-Tag for those looking for this:
<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />
I end up with this solutions. As we tap back button viewDidDisappear method called. we can check by calling isMovingFromParentViewController selector which return true. we can pass data back (Using Delegate).hope this help someone.
-(void)viewDidDisappear:(BOOL)animated{
if (self.isMovingToParentViewController) {
}
if (self.isMovingFromParentViewController) {
//moving back
//pass to viewCollection delegate and update UI
[self.delegateObject passBackSavedData:self.dataModel];
}
}
Variations on a theme: a simple solution with jQuery, no CSS editing needed.
// make iframe active on click, disable on mouseleave
$('iframe.google_map').each( function(i, iframe) {
$(iframe).parent().hover( // make inactive on hover
function() { $(iframe).css('pointer-events', 'none');
}).click( // activate on click
function() { $(iframe).css('pointer-events', 'auto');
}).trigger('mouseover'); // make it inactive by default as well
});
Hover listener is attached to the parent element, so if the current parent is bigger, you can just simply wrap the iframe with a div before the 3rd line.
Hope it'll be useful for somebody.
You can also reference a local gem with git if you happen to be working on it.
gem 'foo',
:git => '/Path/to/local/git/repo',
:branch => 'my-feature-branch'
Then, if it changes I run
bundle exec gem uninstall foo
bundle update foo
But I am not sure everyone needs to run these two steps.
For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();
The clear()
method removes all the elements of a single ArrayList
. It's a fast operation, as it just sets the array elements to null
.
The removeAll(Collection)
method, which is inherited from AbstractCollection
, removes all the elements that are in the argument collection from the collection you call the method on. It's a relatively slow operation, as it has to search through one of the collections involved.
\s
means "one space", and \s+
means "one or more spaces".
But, because you're using the /g
flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.
It depends on the situation.
If There is only one sharing entity or more than one.
See full working example here
A small introduction.
Threads and shareable entities
It is possible for multiple threads to access same entity, for eg multiple connectionThreads sharing a single messageQueue. Since the threads run concurrently there may be a chance of overriding one's data by another which may be a messed up situation.
So we need some way to ensure that shareable entity is accessed only by one thread at a time. (CONCURRENCY).
Synchronized block
synchronized() block is a way to ensure concurrent access of shareable entity.
First, a small analogy
Suppose There are two-person P1, P2 (threads) a Washbasin (shareable entity) inside a washroom and there is a door (lock).
Now we want one person to use washbasin at a time.
An approach is to lock the door by P1 when the door is locked P2 waits until p1 completes his work
P1 unlocks the door
then only p1 can use washbasin.
syntax.
synchronized(this)
{
SHARED_ENTITY.....
}
"this" provided the intrinsic lock associated with the class (Java developer designed Object class in such a way that each object can work as monitor).
Above approach works fine when there are only one shared entity and multiple threads (1: N).
N shareable entities-M threads
Now think of a situation when there is two washbasin inside a washroom and only one door. If we are using the previous approach, only p1 can use one washbasin at a time while p2 will wait outside. It is wastage of resource as no one is using B2 (washbasin).
A wiser approach would be to create a smaller room inside washroom and provide them one door per washbasin. In this way, P1 can access B1 and P2 can access B2 and vice-versa.
washbasin1;
washbasin2;
Object lock1=new Object();
Object lock2=new Object();
synchronized(lock1)
{
washbasin1;
}
synchronized(lock2)
{
washbasin2;
}
See more on Threads----> here
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds
The option is called Modify
:
This will show you the T-SQL code for your stored procedure in a new query window, with an ALTER PROCEDURE ...
lead-in, so you can easily change or amend your procedure and update it
JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters
HTML:
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
Javascript:
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});
You can just echo all the HTML as normal:
<?php
echo '<input type="button" onclick="alert(\'Clicky!\')"/>';
?>
#include <windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!\n";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/PCFreq;
}
int main()
{
StartCounter();
Sleep(1000);
cout << GetCounter() <<"\n";
return 0;
}
This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).
The StartCounter()
function records the number of ticks the performance counter has in the CounterStart
variable. The GetCounter()
function returns the number of milliseconds since StartCounter()
was last called as a double, so if GetCounter()
returns 0.001 then it has been about 1 microsecond since StartCounter()
was called.
If you want to have the timer use seconds instead then change
PCFreq = double(li.QuadPart)/1000.0;
to
PCFreq = double(li.QuadPart);
or if you want microseconds then use
PCFreq = double(li.QuadPart)/1000000.0;
But really it's about convenience since it returns a double.
Simplest way is to use the dot operator in place of source, which is the sh equivalent of the bash source
command:
Instead of:
RUN source /usr/local/bin/virtualenvwrapper.sh
Use:
RUN . /usr/local/bin/virtualenvwrapper.sh
HTML
<a href="#" class="button"> HOME </a>
CSS
.button {
background-color: #00CCFF;
padding: 8px 16px;
display: inline-block;
text-decoration: none;
color: #FFFFFF;
border-radius: 3px;
}
.button:hover{ background-color: #0066FF;}
I did it like this, a variation on Vadims code but to me a bit more readable:
' Returns TRUE if item is already contained in collection, otherwise FALSE
Public Function Contains(col As Collection, item As String) As Boolean
Dim i As Integer
For i = 1 To col.Count
If col.item(i) = item Then
Contains = True
Exit Function
End If
Next i
Contains = False
End Function
Depending on what you're wanting, you can use…
rake db:create
…to build the database from scratch from config/database.yml
, or…
rake db:schema:load
…to build the database from scratch from your schema.rb
file.
The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)
<input type="button" value="Increment" id="increment"/>
<script type="text/javascript">
var count = 0;
// JQuery way
$('#increment').click(function (e) {
e.preventDefault();
count++;
});
// YUI way
YAHOO.util.Event.on('increment', 'click', function (e) {
YAHOO.util.Event.preventDefault(e);
count++;
});
// Simple way
document.getElementById('increment').onclick = function (e) {
count++;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
};
</script>
chucknorris
starts with c
, and the browser reads it into a hexadecimal value.
Because A, B, C, D, E, and F are characters in hexadecimal.
The browser converts chucknorris
to a hexadecimal value, C00C00000000
.
Then the C00C00000000
hexadecimal value is converted to RGB format (divided by 3):
C00C00000000
?R:C00C, G:0000, B:0000
The browser needs only two digits to indicate the colour:
R:C00C, G:0000, B:0000
?R:C0, G:00, B:00
?C00000
Finally, show bgcolor = C00000
in the web browser.
Here's an example demonstrating it:
<table>
<tr>
<td bgcolor="chucknorris" cellpadding="10" width="150" align="center">chucknorris</td>
<td bgcolor="c00c00000000" cellpadding="10" width="150" align="center">c00c00000000</td>
<td bgcolor="c00000" cellpadding="10" width="150" align="center">c00000</td>
</tr>
</table>
_x000D_
You don't need to wrap everything in a DIV to achieve basic styling on inputs.
input[type="text"] {margin: 0 0 10px 0;}
will do the trick in most cases.
Semantically, one <br/> tag is okay between elements to position them. When you find yourself using multiple <br/>'s (which are semantic elements) to achieve cosmetic effects, that's a flag that you're mixing responsibilities, and you should consider getting back to basics.
you can use below code to get email address after ? in the URL
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
echo $_GET['email'];_x000D_
}
_x000D_
This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:
git checkout some-branch # where some-branch can be replaced by any other branch
git branch base-branch -D # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch # recreating branch with correct commits
Note: You can combine these all by putting && between them
Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?
Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.
Ex:
git checkout feature-old # some branch with the extra commits
git log # gives commits (write down the id of the ones you want)
git checkout base-branch # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch
Now feature-new is your branch without the extra (possibly bad) commits!
If I understand correctly. In order to group your results as requested, your Group By clause needs to have the same expression as your select statement.
GROUP BY MONTH(date) + '.' + YEAR(date)
To display the date as "month-date" format change the '.' to '-' The full syntax would be something like this.
SELECT MONTH(date) + '-' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS
SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date) + '.' + YEAR(date)
When you are declaring a pointer variable or function parameter, use the *:
int *x = NULL;
int *y = malloc(sizeof(int)), *z = NULL;
int* f(int *x) {
...
}
NB: each declared variable needs its own *.
When you want to take the address of a value, use &. When you want to read or write the value in a pointer, use *.
int a;
int *b;
b = f(&a);
a = *b;
a = *f(&a);
Arrays are usually just treated like pointers. When you declare an array parameter in a function, you can just as easily declare it is a pointer (it means the same thing). When you pass an array to a function, you are actually passing a pointer to the first element.
Function pointers are the only things that don't quite follow the rules. You can take the address of a function without using &, and you can call a function pointer without using *.
Basically we can create spring container object in two ways
both are the interfaces,
using implementation classes we can create object for spring container
coming to the differences
BeanFactory :
Does not support the Annotation based dependency Injection.
Doesn't Support I18N.
By default its support Lazy loading.
it doesn't allow configure to multiple configuration files.
ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));
ApplicationContext
Support Annotation based dependency Injection.-@Autowired, @PreDestroy
Support I18N
Its By default support Aggresive loading.
It allow to configure multiple configuration files.
ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");
In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file