import time
import datetime
def Local2UTC(LocalTime):
EpochSecond = time.mktime(LocalTime.timetuple())
utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
return utcTime
>>> LocalTime = datetime.datetime.now()
>>> UTCTime = Local2UTC(LocalTime)
>>> LocalTime.ctime()
'Thu Feb 3 22:33:46 2011'
>>> UTCTime.ctime()
'Fri Feb 4 05:33:46 2011'
i use price.ToString("0.00")
for getting the leading 0s
Should't the .htaccess
use add
instead of set
?
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
You can use stuff and patindex.
stuff(Col, 1, patindex('%[0-9]%', Col)-1, '')
and the version to work on the array type:
select
array_to_string(
array(select distinct unnest(zip_codes) from table),
', '
);
for wamp server use 10.0.2.2
for local host
e.g. 10.0.2.2/phpMyAdmin
and for tomcat use 10.0.2.2:8080/server
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
To call one constructor from another you need to use this()
and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:
Using Windows Explorer, navigate to:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013
In that folder, you'll see a shortcut named Visual Studio Tools
that maps to (assuming default installation):
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
Double-click the shortcut (or go to the folder above).
From that folder, copy the shortcut named Developer Command Prompt for VS2013
(and any others you find useful) to the first directory (for the Start Menu
). You'll likely be prompted for administrative access (do so).
Once you've done that, you'll now have an icon available for the 2013 command prompt.
You should just use something like:
YourModel.update_all(
ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
)
That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.
public String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
Simply type:
. ~/.bash_profile
However, if you want to source it to run automatically when terminal starts instead of running it every time you open terminal, you might add . ~/.bash_profile
to ~/.bashrc
file.
Note:
When you open a terminal, the terminal starts bash in (non-login) interactive mode, which means it will source ~/.bashrc
.
~/.bash_profile
is only sourced by bash when started in interactive login mode. That is typically only when you login at the console (Ctrl+Alt+F1..F6), or connecting via ssh
.
Use Selenium for webbased unit tests. There's a Firefox plugin called Selenium IDE which can record actions on the webpage and export to JUnit testcases which uses Selenium RC to run the test server.
Use quit()
in this context. break
expects to be inside a loop, and return
expects to be inside a function.
I just crafted this as I needed a good, simple way.
If it gets to the final digit, and if it is a zero, it will stay.
You could also use a foreach loop instead for super long strings.
I just replace each leading oldChar with the newChar.
This is great for a problem I just solved, after formatting an int into a string.
/* Like this: */
int counterMax = 1000;
int counter = ...;
string counterString = counter.ToString($"D{counterMax.ToString().Length}");
counterString = RemoveLeadingChars('0', ' ', counterString);
string fullCounter = $"({counterString}/{counterMax})";
// = ( 1/1000) ... ( 430/1000) ... (1000/1000)
static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
{
string result = "";
bool stop = false;
for (int i = 0; i < chars.Length; i++)
{
if (i == (chars.Length - 1)) stop = true;
if (!stop && chars[i] == oldChar) chars[i] = newChar;
else stop = true;
result += chars[i];
}
return result;
}
static string RemoveLeadingChars(char oldChar, char newChar, string text)
{
return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
}
I always tend to make my functions suitable for my own library, so there are options.
The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.
template <typename T> struct whatever {};
template <typename T> struct rebind
{
typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};
rebind<int>::type variable;
template <typename U> struct bar { typename rebind<U>::type _var_member; }
But using syntax simplifies this use case.
template <typename T> using my_type = whatever<T>;
my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }
You'll have to pass the pointer to the vector, not the vector itself. Note the additional '&' here:
found = binarySearch(first, last, search4, &random);
In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.
Absolutely. You can use the LINQ Dynamic Query Library, found on Scott Guthrie's blog. There's also an updated version available on CodePlex.
It lets you create OrderBy
clauses, Where
clauses, and just about everything else by passing in string parameters. It works great for creating generic code for sorting/filtering grids, etc.
var result = data
.Where(/* ... */)
.Select(/* ... */)
.OrderBy("Foo asc");
var query = DbContext.Data
.Where(/* ... */)
.Select(/* ... */)
.OrderBy("Foo ascending");
I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository
If you are running Ansible >= 2.0 there is also the dirname filter you can use to extract the directory part of a path. That way you can just use one variable to hold the entire path to make sure both tasks never get out of sync.
So for example if you have playbook with dest_path
defined in a variable like this you can reuse the same variable:
- name: My playbook
vars:
dest_path: /home/ubuntu/some_dir/some_file.txt
tasks:
- name: Make sure destination dir exists
file:
path: "{{ dest_path | dirname }}"
state: directory
recurse: yes
# now this task is always save to run no matter how dest_path get's changed arround
- name: Add file or template to remote instance
template:
src: foo.txt.j2
dest: "{{ dest_path }}"
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
Java 11+:
URI uri = URI.create("http://www.google.com");
HttpRequest request = HttpRequest.newBuilder(uri).build();
String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();
Well yes arrays do exist, and no they're not different to lists when it comes to things like del
and append
:
>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>
Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression
or arr.append(expression)
, and lvalue = arr[i]
In case you are using zsh you can use for example the -E
or -i
switch:
history -E
If you do a man zshoptions
or man zshbuiltins
you can find out more information about these switches as well as other info related to history:
Also when listing,
-d prints timestamps for each event
-f prints full time-date stamps in the US `MM/DD/YY hh:mm' format
-E prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
-i prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
-t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions described for the %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1). The resulting formatted string must be no more than 256 characters or will not be printed
-D prints elapsed times; may be combined with one of the options above
For those, who want to do it automatically, I have wrote a little two-lines bash script which does next two things:
Renames extracted classes.jar to be like the aar but with a new extension
find . -name '*.aar' -exec sh -c 'unzip -d `dirname {}` {} classes.jar' \;
find . -name '*.aar' -exec sh -c 'mv `dirname {}`/classes.jar `echo {} | sed s/aar/jar/g`' \;
That's it!
Basically here we are dealing with communication between Fragments. Communication between fragments can never be directly possible. It involves activity under the context of which both the fragments are created.
You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.
There is a conflict between (Safari) and (Opera) and (Chrome) !!!
The above codes couldn't work properly
This is my code, and it works very well without any conflict:
function ExactBrowserName()
{
$ExactBrowserNameUA=$_SERVER['HTTP_USER_AGENT'];
if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
// OPERA
$ExactBrowserNameBR="Opera";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
// CHROME
$ExactBrowserNameBR="Chrome";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
// INTERNET EXPLORER
$ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
// FIREFOX
$ExactBrowserNameBR="Firefox";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
// SAFARI
$ExactBrowserNameBR="Safari";
} else {
// OUT OF DATA
$ExactBrowserNameBR="OUT OF DATA";
};
return $ExactBrowserNameBR;
}
Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;
public class MyClass {
public static void main(String[] args) {
System.out.println(U.formatXml("<a>\n <b></b>\n <b></b>\n</a>",
Xml.XmlStringBuilder.Step.COMPACT));
}
}
// output: <a><b></b><b></b></a>
String^ exePath = Application::ExecutablePath;<br>
MessageBox::Show(exePath);
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
Arguments are passed by assignment. The rationale behind this is twofold:
So:
If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.
To make it even more clear, let's have some examples.
Let's try to modify the list that was passed to a method:
def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
outer_list = ['one', 'two', 'three']
print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
Since the parameter passed in is a reference to outer_list
, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.
Now let's see what happens when we try to change the reference that was passed in as a parameter:
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
Since the the_list
parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list
was a copy of the outer_list
reference, and we had the_list
point to a new list, but there was no way to change where outer_list
pointed.
It's immutable, so there's nothing we can do to change the contents of the string
Now, let's try to change the reference
def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
Output:
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
Again, since the the_string
parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string
was a copy of the outer_string
reference, and we had the_string
point to a new string, but there was no way to change where outer_string
pointed.
I hope this clears things up a little.
EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.
As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:
def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:
def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
Although this seems a little cumbersome.
You can also try this:
CREATE function [dbo].[fn_FormatPhone](@Phone varchar(30))
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)
set @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
Case
When isNumeric(@Phone) = 1 Then
case
when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
when len(@Phone) = 7 then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
else @Phone
end
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
Else @Phone
End
return @FormattedPhone
end
use on it select
(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'
Output will be
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
Based on this test (for-vs-forEach-vs-reduce) and this (loops)
I can say that:
var total = 0;
for (var i = 0, n = array.length; i < n; ++i)
{
total += array[i];
}
For you case you won't need this, but it adds a lot of flexibility.
Array.prototype.Aggregate = function(fn) {
var current
, length = this.length;
if (length == 0) throw "Reduce of empty array with no initial value";
current = this[0];
for (var i = 1; i < length; ++i)
{
current = fn(current, this[i]);
}
return current;
};
Usage:
var total = array.Aggregate(function(a,b){ return a + b });
Then comes forEach
and reduce
which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.
Using youtube-dl
and jq
:
views() {
id=$1
youtube-dl -j https://www.youtube.com/watch?v=$id |
jq -r '.["view_count"]'
}
views fOX1EyHkQwc
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
Rails 4.1 added Hash#compact and Hash#compact! as a core extensions to Ruby's Hash
class. You can use them like this:
hash = { a: true, b: false, c: nil }
hash.compact
# => { a: true, b: false }
hash
# => { a: true, b: false, c: nil }
hash.compact!
# => { a: true, b: false }
hash
# => { a: true, b: false }
{ c: nil }.compact
# => {}
Heads up: this implementation is not recursive. As a curiosity, they implemented it using #select
instead of #delete_if
for performance reasons. See here for the benchmark.
In case you want to backport it to your Rails 3 app:
# config/initializers/rails4_backports.rb
class Hash
# as implemented in Rails 4
# File activesupport/lib/active_support/core_ext/hash/compact.rb, line 8
def compact
self.select { |_, value| !value.nil? }
end
end
Do install latest version instead of the recommended stable version. It will give you freedom to use latest ES6 Features on node.
Can be Found here Node JS.
sudo npm i -g npm@latest
All your projects will work fine.
Update: 2020 another good option is to use nvm
for node which can then support multiple versions.
use nvm install --lts
to always be able to update to latest node version use nvm ls-remote
command to to check new versions of node.
Other option for mac :: brew update && brew install node && npm -g npm
The difference between getHeight()
and getMeasuredHeight()
is that first method will return actual height of the View
, the second one will return summary height of View
's children. In ohter words, getHeight()
returns view height, getMeasuredHeight()
returns height which this view needs to show all it's elements
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):
function clearForm(form) {
// iterate over all of the inputs for the given form element
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
... or as a jQuery plugin...
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
li:before {
content: '';
height: 5px;
background-color: green;
position: relative;
display: block;
top: 50%;
left: 50%;
width: 9px;
margin-left: -15px;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
li:after {
content: '';
height: 5px;
background-color: green;
position: relative;
display: block;
top: 50%;
left: 50%;
width: 20px;
margin-left: -11px;
margin-top: -6px;
-ms-transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
}
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
SELECT a.salesorderid, a.orderdate, s.orderdate, s.salesorderid
FROM A a
OUTER APPLY (SELECT top(1) *
FROM B b WHERE a.salesorderid = b.salesorderid) as s
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
I have resolve this issue at my GIT repository. No need to rebase
or force
commit in this case. Use below steps to resolve this -
local_barnch> git branch --set-upstream to=origin/<local_branch_name>
local_barnch>git pull origin <local_branch_name>
local_barnch> git branch --set-upstream to=origin/master
local_barnch>git push origin <local_branch_name>
hope it will help.
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
This issue is related to Byte Order Mark in the JSON file. JSON file is not encoded as UTF8 encoding data when saved. Using File.ReadAllText(pathFile)
fix this issue.
When we are operating on Byte data and converting that to string and then passing to JsonConvert.DeserializeObject, we can use UTF32 encoding to get the string.
byte[] docBytes = File.ReadAllBytes(filePath);
string jsonString = Encoding.UTF32.GetString(docBytes);
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
Try this.
<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />
<script type="text/javascript">
function ShowButton() {
var buttonID = '<%= myButton.ClientID %>';
var button = document.getElementById(buttonID);
if(button) { button.style.display = 'inherit'; }
}
</script>
Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.
The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
Others have answered sufficiently. I would just like to add a few examples of frequent extensions:
The main
function returning void
. This is not defined by the standard, meaning it will only work on some compilers (including GCC), but not on others. By the way, int main()
and int main(int, char**)
are the two signatures that the standard does define.
Another popular extension is being able to declare and define functions inside other functions:
void f()
{
void g()
{
// ...
}
// ...
g();
// ...
}
This is nonstandard. If you want this kind of behavior, check out C++11 lambdas
You can list breakpoints with:
info break
This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:
del 3
For example:
(gdb) info b
Num Type Disp Enb Address What
3 breakpoint keep y 0x004018c3 in timeCorrect at my3.c:215
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
(gdb) del 3
(gdb) info b
Num Type Disp Enb Address What
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
Building on Chaz's answer, in .NET 5 there is a breaking change, so two modifications are required in the project file, i.e. changing OutputType
and adding DisableWinExeOutputInference
. Example:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>
scanf("%2000s %2000[^\n]", a, b);
I had the same issue and for me it had nothing to do with namespace or project naming.
But as several users hinted at it had to do with an old assembly still being referenced.
I recommend to delete all "bin"/binary folders of all projects and to re-build the whole solution. This washed out any potentially outdated assemblies and after that MEF exported all my plugins without issue.
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
Since 1.10 release, you can now add multiple tags at once on build:
docker build -t name1:tag1 -t name1:tag2 -t name2 .
For C, at least, per C11 6.7.5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
for an object, causes storage to be reserved for that object;
for a function, includes the function body;
for an enumeration constant, is the (only) declaration of the identifier;
for a typedef name, is the first (or only) declaration of the identifier.
Per C11 6.7.9.8-10:
An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.
So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.
Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).
So, if you define an automatic variable without specifying an initial value for it, such as:
int myfunc(void) {
int myvar;
...
You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.
It is probably better to kill the parent before the children; otherwise the parent may likely spawn new children again before he is killed himself. These will survive the killing.
My version of ps is different from that above; maybe too old, therefore the strange grepping...
To use a shell script instead of a shell function has many advantages...
However, it is basically zhigangs idea
#!/bin/bash
if test $# -lt 1 ; then
echo >&2 "usage: kiltree pid (sig)"
fi ;
_pid=$1
_sig=${2:-TERM}
_children=$(ps j | grep "^[ ]*${_pid} " | cut -c 7-11) ;
echo >&2 kill -${_sig} ${_pid}
kill -${_sig} ${_pid}
for _child in ${_children}; do
killtree ${_child} ${_sig}
done
The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:
Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
<div style="width:800px;">
now really long text like this can be put in the text area and it will really <br/>
look and act more like a real text area bla bla bla <br/>
</div>
</div>
Probably, you are trying to point the tomcat directory having the source folder. Please download the tomcat binary version from here .For Linux environments, there you can find .zip and .tar.gz files under core section. Please download and extract them. after that, if you point this extracted directory, eclipse will be able to identify the tomcat version. Eclipse was not able to find the version of tomcat, since the directory you pointed out didn't contain the conf folder. Hope this helps!
Didn't find a satisfactory answer here, so I wrote a new one.
To understand why "prefer composition over inheritance", we need first get back the assumption omitted in this shortened idiom.
There are two benefits of inheritance: subtyping and subclassing
Subtyping means conforming to a type (interface) signature, i.e. a set of APIs, and one can override part of the signature to achieve subtyping polymorphism.
Subclassing means implicit reuse of method implementations.
With the two benefits comes two different purposes for doing inheritance: subtyping oriented and code reuse oriented.
If code reuse is the sole purpose, subclassing may give one more than what he needs, i.e. some public methods of the parent class don't make much sense for the child class. In this case, instead of favoring composition over inheritance, composition is demanded. This is also where the "is-a" vs. "has-a" notion comes from.
So only when subtyping is purposed, i.e. to use the new class later in a polymorphic manner, do we face the problem of choosing inheritance or composition. This is the assumption that gets omitted in the shortened idiom under discussion.
To subtype is to conform to a type signature, this means composition has always to expose no less amount of APIs of the type. Now the trade offs kick in:
Inheritance provides straightforward code reuse if not overridden, while composition has to re-code every API, even if it's just a simple job of delegation.
Inheritance provides straightforward open recursion via the internal polymorphic site this
, i.e. invoking overriding method (or even type) in another member function, either public or private (though discouraged). Open recursion can be simulated via composition, but it requires extra effort and may not always viable(?). This answer to a duplicated question talks something similar.
Inheritance exposes protected members. This breaks encapsulation of the parent class, and if used by subclass, another dependency between the child and its parent is introduced.
Composition has the befit of inversion of control, and its dependency can be injected dynamically, as is shown in decorator pattern and proxy pattern.
Composition has the benefit of combinator-oriented programming, i.e. working in a way like the composite pattern.
Composition immediately follows programming to an interface.
Composition has the benefit of easy multiple inheritance.
With the above trade offs in mind, we hence prefer composition over inheritance. Yet for tightly related classes, i.e. when implicit code reuse really make benefits, or the magic power of open recursion is desired, inheritance shall be the choice.
Class2 class2 = new Class2();
Instead of calling the main, perhaps you should call individual methods where and when you need them.
Check this Official Link
Normally we consider the remote branches recently. So try this
git fetch
git for-each-ref --sort=-committerdate refs/remotes/origin
Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.
So, if I have the following NewFile.xml:
<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />
And the eclipse encoding is UTF-8:
The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.
The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.
EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.
When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.
I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.
You can find those maven properties in the super pom.
You find the jar here:
${M2_HOME}/lib/maven-model-builder-3.0.3.jar
Open the jar with 7-zip or some other archiver (or use the jar tool).
Navigate to
org/apache/maven/model
There you'll find the pom-4.0.0.xml
.
It contains all those "short cuts":
<project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
After some lobbying I am adding a link to the pom-4.0.0.xml
. This allows you to see the properties without opening up the local jar file.
I don't work in WordPress much, but for forms outside of WordPress, this works well.
location = ""; // Declare variable
if($_POST) {
if(!$_POST["location"]) {
$error .= "Location is required.<br />"; // If not selected, add string to error message
}else{
$location = $_POST["location"]; // If selected, assign to variable
}
<select name="location">
<option value="0">Choose...</option>
<option value="1" <?php if (isset($location) && $location == "1") echo "selected" ?>>location 1</option>
<option value="2" <?php if (isset($location) && $location == "2") echo "selected" ?>>location 2</option>
</select>
Enclose the string in single quote it should work. Try this.
var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);
This blog came with a pretty good solution using XML in T-SQL.
This is the function I came up with based on that blog (change function name and result type cast per need):
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitIntoBigints]
(@List varchar(MAX), @Splitter char)
RETURNS TABLE
AS
RETURN
(
WITH SplittedXML AS(
SELECT CAST('<v>' + REPLACE(@List, @Splitter, '</v><v>') + '</v>' AS XML) AS Splitted
)
SELECT x.v.value('.', 'bigint') AS Value
FROM SplittedXML
CROSS APPLY Splitted.nodes('//v') x(v)
)
GO
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
How about alert(JSON.stringify(object))
with a modern browser?
In case of TypeError: Converting circular structure to JSON
, here are more options: How to serialize DOM node to JSON even if there are circular references?
The documentation: JSON.stringify()
provides info on formatting or prettifying the output.
I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection
, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection
.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
private void Handle(object sender, PropertyChangedEventArgs args)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (object t in e.NewItems) {
((T) t).PropertyChanged += Handle;
}
}
if (e.OldItems != null) {
foreach (object t in e.OldItems) {
((T) t).PropertyChanged -= Handle;
}
}
base.OnCollectionChanged(e);
}
While Items are added or removed the class forwards the items PropertyChanged
event to the collections PropertyChanged
event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
protected readonly CultureInfo Ci = new CultureInfo("en-US");
private string _value;
public string Value {
get { return _value; }
set {
if (value == _value) return;
_value = value;
OnPropertyChanged();
}
}
}
public class AItem {
public NotifyObservableCollection<ParameterBase> Parameters {
get { return _parameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_parameters != null) _parameters.CollectionChanged -= cceh;
_parameters = value;
//needed for Binding to AItem at xaml directly
_parameters.CollectionChanged += cceh;
}
}
public NotifyObservableCollection<ParameterBase> DefaultParameters {
get { return _defaultParameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
_defaultParameters = value;
//needed for Binding to AItem at xaml directly
_defaultParameters.CollectionChanged += cceh;
}
}
public class MyViewModel {
public NotifyObservableCollection<AItem> DataItems { get; set; }
}
If now a property of an item in DataItems
changes, the following xaml will get a notification, though it binds to Parameters[0]
or to the item itself except to the changing property Value
of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Aqua" />
<Style.Triggers>
<DataTrigger Value="False">
<!-- Bind to Items with changing properties -->
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ParameterCompareConverter}">
<Binding Path="DefaultParameters[0]" />
<Binding Path="Parameters[0]" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="DeepPink" />
</DataTrigger>
<!-- Binds to AItem directly -->
<DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
<Setter Property="FontWeight" Value="ExtraBold" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
Here's the answer to all your questions: http://wiki.python.org/moin/PythonEditors
For xCode 10, first you need to add the image in your assetsCatalogue and then type this:
let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))
For beginners, let imageView
is the name of the UIImageView
object we are about to create.
An example for embedding an image into a viewControler
file would look like this:
import UIKit
class TutorialViewCotroller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
view.addSubview(imageView)
}
}
Please notice that I did not use any extension for the image file name, as in my case it is a group of images.
Try this:
$("#test-element").on("click" ,function() {
alert("click");
});
The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.
15 - Using some crazy construct and application logic instead of a simple COALESCE.
This will add a global function to access to the queryString variables as a map.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
Enjoy.
you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to be clear you can also do
if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to have the not (one or the other)
phrase in the code (remember the (silent) brackets)
Multiply it by -1.
A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)
In Python...
ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)
Anyway cookamunga provided good inline solution using python!
You can use a dynamic array when you don't know the number of values it will contain until run-time:
Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)
Or you could do everything with one statement if you're creating an array that's local to a procedure:
ReDim Zombies(NumberOfZombies) As Integer
Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.
You could use a constant if you knew the value of the variable was not going to change:
Const NumberOfZombies = 2000
but there's no way to cast between constants and variables. They have distinctly different meanings.
This will remove the option
tag and just leave the letters in vim:
:%s/<option.*>//g
I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:
logging {
channel default_file {
file "/var/log/named/default.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel general_file {
file "/var/log/named/general.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel database_file {
file "/var/log/named/database.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel security_file {
file "/var/log/named/security.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel config_file {
file "/var/log/named/config.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel resolver_file {
file "/var/log/named/resolver.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-in_file {
file "/var/log/named/xfer-in.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-out_file {
file "/var/log/named/xfer-out.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel notify_file {
file "/var/log/named/notify.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel client_file {
file "/var/log/named/client.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel unmatched_file {
file "/var/log/named/unmatched.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel queries_file {
file "/var/log/named/queries.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel network_file {
file "/var/log/named/network.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel update_file {
file "/var/log/named/update.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dispatch_file {
file "/var/log/named/dispatch.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dnssec_file {
file "/var/log/named/dnssec.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel lame-servers_file {
file "/var/log/named/lame-servers.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
category default { default_file; };
category general { general_file; };
category database { database_file; };
category security { security_file; };
category config { config_file; };
category resolver { resolver_file; };
category xfer-in { xfer-in_file; };
category xfer-out { xfer-out_file; };
category notify { notify_file; };
category client { client_file; };
category unmatched { unmatched_file; };
category queries { queries_file; };
category network { network_file; };
category update { update_file; };
category dispatch { dispatch_file; };
category dnssec { dnssec_file; };
category lame-servers { lame-servers_file; };
};
Hope this helps.
I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.
this is what you need, the child combinator:
select>option:hover
{
color: #1B517E;
cursor: pointer;
}
Try it, works perfect.
Here's the reference: http://www.w3schools.com/css/css_combinators.asp
The problem is you're not doing anything with the result of replace
. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
All solution that call length from array, add your code redundant null checkersconsider example:
int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
//What if array a comes as local parameter? You need to use null check:
public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}
I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:
public void someMethod(int[] a) {
int[] b = ArrayUtils.clone(a);
}
Apache commons you can find there
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame() {
setSize(400,400);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
check out the below link
http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html
This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.
Syntax example :
// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]>
This is the safest approach, considering it prevents accessing indexes out of the boundaries.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
& { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }
Tests :
var myFixedLengthArray: FixedLengthArray< [string, string, string]>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? INVALID INDEX ERROR
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR
(*) This solution requires the noImplicitAny
typescript configuration directive to be enabled in order to work (commonly recommended practice)
This solution behaves as an augmentation of the Array
type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.
Syntax example :
let foo: FixedLengthArray<string, 3>
Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
& {
readonly length: L
[ I : number ] : T
[Symbol.iterator]: () => IterableIterator<T>
}
Tests :
var myFixedLengthArray: FixedLengthArray<string,3>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? SHOULD FAIL
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL
It is still one intersting moment:
ev.preventDefault()
ev.stopPropagation();
ev.nativeEvent.stopImmediatePropagation();
Use this construction, if your function is wrapped by tag
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
You don't need root to pull the apk files from /data/app
. Sure, you might not have permissions to list the contents of that directory, but you can find the file locations of APKs with:
adb shell pm list packages -f
Then you can use adb pull
:
adb pull <APK path from previous command>
and then aapt
to get the information you want:
aapt dump badging <pulledfile.apk>
Here's a very simple, fast dplyr
/tidy
solution:
Remove rows that are entirely the same:
library(dplyr)
iris %>%
distinct(.keep_all = TRUE)
Remove rows that are the same only in certain columns:
iris %>%
distinct(Sepal.Length, Sepal.Width, .keep_all = TRUE)
Use this code everywhere for unregisterReceiver:
if (batteryNotifyReceiver != null) {
unregisterReceiver(batteryNotifyReceiver);
batteryNotifyReceiver = null;
}
This seems like the simplest solution that I've found to retrieve the last value in an ever-expanding column:
=INDEX(A:A,COUNTA(A:A),1)
In my case, I needed to change the color of just one menu item - "Logout". I had to run a recursion and changed the title color:
NavigationView nvDrawer;
Menu menu = nvDrawer.getMenu();
for (int i = 0; i < menu.size(); i ++){
MenuItem menuItem = menu.getItem(i);
if (menuItem.getTitle().equals("Logout")){
SpannableString spanString = new SpannableString(menuItem.getTitle().toString());
spanString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 0, spanString.length(), 0);
menuItem.setTitle(spanString);
}
}
I did this in the Activity's onCreate method.
For Windows 7:
My Computer
Properties
Advanced System Settings
Advanced
tabEnvironment Variables
Path
under System Variables
Edit
buttonIn Variable value editor paste this at the start of the line
C:\Program Files\Java\jdk1.7.0_72\bin;
Click Ok then Ok again
java -version
in command prompt.Notes on Step 6:
1. This sets the path for the computer, not for the individual user. It may be that you're working on a computer which other developers also use, in which case you'd rather set the user variables, rather than the system variables
Project:Spring Boot Tool:STS
Resolve Steps:
There is one more solution to set column Full text to true.
These solution for example didn't work for me
ALTER TABLE news ADD FULLTEXT(headline, story);
My solution.
NEXT STEPS
Refresh
Version of mssql 2014
I could solve this installing Newtonsoft Json in the web project with nugget packages
You're probably using
document.getElementById('element').innerHTML = "New content"
Try this instead:
document.getElementById('element').innerHTML += "New content"
Or, preferably, use DOM Manipulation:
document.getElementById('element').appendChild(document.createElement("div"))
Dom manipulation would be preferred compared to using innerHTML
, because innerHTML
simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.
Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html
Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd()
method doesn't work as expected. This is what I would do:
import os
# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))
print(curDir) # print current directory
Define a function like this:
def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
for _ in range(n):
path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that
# the function iterates proper number of times
return(path)
The use of this function is fairly simple - all you need is your path and number of directories up.
print(dir_up(curDir,3)) # print 3 directories above the current one
The only minus is that it doesn't stop on drive letter, it just will show you empty string.
I have also faced such problems many time in web develoment carrier. Actually its not JS conflict, When we load html website to the browser we face no such error, but when we load these type of website through localhost we face such problem. That's because of localhost. When we load scripts through the localhost it scans the script and renders the output. But when we didn't use localhost. It just scan the output. Example, when we write php code putside the localhost and run without host we get error. But if the code is correct and is run through host we get actual output, and when we use inspect element we get the output code in HTMl format but not in PHP format this is because of rendering of the code.
This is rendering error. So to fix these jquery code error one of the solution may be using this method.
jQuery(document).ready(function($){
/******** Body of Jquery Code*****/
});
What this code does is register '$' as the varible to the function by applying jquery. Else by default the .js file is only read as javascript.
You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:
CREATE TABLE #tmp(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(1000);
SET @sql = N'BULK INSERT #tmp ...' + @variables;
EXEC master.sys.sp_executesql @sql;
SELECT * FROM #tmp;
This makes it tougher to maintain (readability) but gets by the scoping issue:
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
BULK INSERT #tmp ...' + @variables + ';
SELECT * FROM #tmp;';
EXEC master.sys.sp_executesql @sql;
EDIT 2011-01-12
In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:
CREATE TABLE #outer(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SET NOCOUNT ON;
CREATE TABLE #inner(a INT, b INT, c INT);
BULK INSERT #inner ...' + @variables + ';
SELECT * FROM #inner;';
INSERT #outer EXEC master.sys.sp_executesql @sql;
In vim if you are confused which all lines will be affected, Use below
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that
:wq
You can use find_all
in the following way to find every a
element that has an href
attribute, and print each one:
from BeautifulSoup import BeautifulSoup
html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
The output would be:
Found the URL: some_url
Found the URL: another_url
Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll
. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all
instead.
If you want all tags with an href
, you can omit the name
parameter:
href_tags = soup.find_all(href=True)
If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.
$this->load->model('Order_Model','order_model');
You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well
$result = $this->order_model->get_order_details($orderID);
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.
You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.
For convenience, you may use this extension function in Kotlin
/**
* Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
*/
fun <T> MutableList<T>.insert(index: Int, element: T) {
if (index <= size) {
add(index, element)
} else {
add(element)
}
}
afaik to make a request to information_schema
you need privileges. If you need simple list of keys you can use this command:
SHOW INDEXES IN <tablename>
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226
public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
{
List<dynamic> result = new List<dynamic>();
Dictionary<string, object> d;
foreach (DataRow dr in dt.Rows)
{
d = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
d.Add(dc.ColumnName, dr[dc]);
result.Add(GetDynamicObject(d));
}
return result.AsEnumerable<dynamic>();
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
try this trick
div{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.
My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"
output=$(echo "$input" | sed 's,\\,/,g')
echo "$output"
This is how I solved the problem:
In main.js of the 'request' module I added one line:
Request.prototype.request = function () {
var self = this
self.setMaxListeners(0); // Added line
This defines unlimited listeners http://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners
In my code I set the 'maxRedirects' value explicitly:
var options = {uri:headingUri, headers:headerData, maxRedirects:100};
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.
You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.
For instance, the iPad Pro (12.9") would have the following media queries:
/* Landscape */
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }
/*Portrait*/
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }
Whereas the iPad Pro (10.5") will have:
/* Landscape */
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }
/*Portrait*/
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }
Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:
git config remote.origin.url url-to-my-other-remote
One of the simplest way is to use flatten()
, like this example :
import numpy as np
batch_y =train_output.iloc[sample, :]
batch_y = np.array(batch_y).flatten()
My array it was like this :
0
0 6
1 6
2 5
3 4
4 3
.
.
.
After using flatten()
:
array([6, 6, 5, ..., 5, 3, 6])
It's also the solution of errors of this type :
Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)'
$("#filter").click(function(){
//Put your code here
});
I use AQTime, it is one of the best profiling tools I've ever used. It isn't free but you can get a 30 day trial, so if you plan on a optimizing and profiling only one project and 30 days are enough for you then I would recommend using this application. (http://www.automatedqa.com/downloads/aqtime/index.asp)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
My JSON
file:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
I succeeded in integrating a JSON
file to HTML
table after working a day on it!!!
(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3
Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
If using Vagrant try reloading your box. This solved my issue.
var token = 'spo';
switch(token){
case ( (token.match(/spo/) )? token : undefined ) :
console.log('MATCHED')
break;;
default:
console.log('NO MATCH')
break;;
}
--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case
--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.
The ternary test can be anything for instance in your case
( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined
===========================================
(token.match(/spo/) )? token : undefined )
is a ternary expression.
The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).
If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).
Obviously token === token so the switch statement is matched and the case evaluated
It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.
You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:
txtBox.CaretIndex=txtBox.Text.Length;
You need to set the caret index at the length, not length-1, because this would put the caret before the last character.
With Comodo PositiveSSL we have received 4 files.
When we followed the instructions on comodo site - we would get an error that our certificate was missing an intermediate certificate file.
Basically the syntax is
cat our_domain.crt COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > domain-ssl_bundle.crt
You can try below query:
select
count(*)
from
all_tab_columns
where
table_name = 'your_table'
use this code
while ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;
?>
Angular 1.3 now has ng-model-options, and you can set the option to { 'updateOn': 'blur'}
for example, and you can even debounce, when the use is either typing too fast, or you want to save a few expensive DOM operations (like a model writing to multiple DOM places and you don't want a $digest cycle happening on every key down)
https://docs.angularjs.org/guide/forms#custom-triggers and https://docs.angularjs.org/guide/forms#non-immediate-debounced-model-updates
By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options="{ updateOn: 'blur' }" will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options="{ updateOn: 'mousedown blur' }"
And debounce
You can delay the model update/validation by using the debounce key with the ngModelOptions directive. This delay will also apply to parsers, validators and model flags like $dirty or $pristine.
I.e. ng-model-options="{ debounce: 500 }" will wait for half a second since the last content change before triggering the model update and form validation.
Working code :
{
DataBaseEntity db = new DataBaseEntity (); //This is EF entity
string dateCheck="5/21/2018";
var list= db.tbl
.where(x=>(x.DOE.Value.Month
+"/"+x.DOE.Value.Day
+"/"+x.DOE.Value.Year)
.ToString()
.Contains(dateCheck))
}
You can use the following command: jar xf rt.jar
Where X
stands for extraction and the f
would be any options that indicate that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
If you are using fragments, you need to call hideKeyboard every time in onResume and onCreate if you want to hide the keyboard.
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "SectionMyFragment onResume");
hideKeyboard();
}
private void hideKeyboard() {
if (getActivity() != null) {
InputMethodManager inputMethodManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
if (getActivity().getCurrentFocus() != null) {
Log.d(TAG, "hideSoftInputFromWindow 1");
inputMethodManager.hideSoftInputFromWindow((getActivity().getCurrentFocus()).getWindowToken(), 0);
}
}
}
}
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:
stringnamehere.decode('utf-8', 'ignore')
You are overwriting your object file runexp.o
by running this command :
gcc -o runexp.o scd.o data_proc.o -lm -fopenmp
In fact, the -o
is for the output file.
You need to run :
gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp
runexp.out will be you binary file.
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
Loads of answers here, but haven't seen the one I use:
input[type="text"]:read-only { color: blue; }
Note the dash in the pseudo selector. If the input is readonly="false"
it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false
is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:
input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
textarea
works the same way:
textarea:read-only:not([read-only="false"]) { color: blue; }
Keep in mind that html now supports not only type="text"
, but a slew of other textual types such a number
, tel
, email
, date
, time
, url
, etc. Each would need to be added to the selector.
Yes:
#include <iostream>
#include <functional>
struct null_ref_t {
template <typename T>
operator T&() {
union TypeSafetyBreaker {
T *ptr;
// see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
std::reference_wrapper<T> ref;
};
TypeSafetyBreaker ptr = {.ptr = nullptr};
// unwrap the reference
return ptr.ref.get();
}
};
null_ref_t nullref;
int main() {
int &a = nullref;
// Segmentation fault
a = 4;
return 0;
}
What you can do and what you should do are different matters.
If the list is very short, or you are only ever going to call find once then use the linear approach above.
However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.
var
just tells the compiler to infer the type you wanted at compile time...it cannot infer from null
(though there are cases it could).
So, no you are not allowed to do this.
When you say "some empty value"...if you mean:
var s = string.Empty;
//
var s = "";
Then yes, you may do that, but not null
.
Maybe
SELECT count(*) FROM (
SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total
although that would not be the sum of all the movies, just how many have 4 genre's.
So maybe you want
SELECT sum(
SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total
If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:
Thread t = new Thread(myRunnable); // myRunnable does your calculations
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;
t.start(); // Kick off calculations
while (System.currentTimeMillis() < endTime) {
// Still within time theshold, wait a little longer
try {
Thread.sleep(500L); // Sleep 1/2 second
} catch (InterruptedException e) {
// Someone woke us up during sleep, that's OK
}
}
t.interrupt(); // Tell the thread to stop
t.join(); // Wait for the thread to cleanup and finish
That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.
Your runnable's run would look something like this:
public void run() {
while (true) {
try {
// Long running work
calculateMassOfUniverse();
} catch (InterruptedException e) {
// We were signaled, clean things up
cleanupStuff();
break; // Leave the loop, thread will exit
}
}
Update based on Dmitri's answer
Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.
Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
Dim i As Long
For i = 1 To table_array.Rows.Count
If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
Exit For
End If
Next i
End Function
There is a simple work around. The alert only comes up when you have a large amount of data in your clipboard. Just copy a random cell before you close the workbook and it won't show up anymore!
In a single line of code:
bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))
\040
matches exactly the space character.
New Link
Escape sequences for Regex PHP
You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.
I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :
compile fileTree(dir: 'libs', include: '*.jar')}
BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries
http://tools.android.com/recent
Hope this helps people!
Despite all the explanations, LEA is an arithmetic operation:
LEA Rt, [Rs1+a*Rs2+b] => Rt = Rs1 + a*Rs2 + b
It's just that its name is extremelly stupid for a shift+add operation. The reason for that was already explained in the top rated answers (i.e. it was designed to directly map high level memory references).
Use FormData
and fetch
to grab and send data
fetch(form.action, {method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action, {method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="[email protected]">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before/after 'submit'
_x000D_
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
Replace void *disconnectFunc;
with void (*disconnectFunc)();
to declare function pointer type variable. Or even better use a typedef
:
typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
fptr = func;
}
void D::disconnected()
{
fptr();
connected = false;
}
I had the same problem on OSX OpenSSL 1.0.1i from Macports, and also had to specify CApath as a workaround (and as mentioned in the Ubuntu bug report, even an invalid CApath will make openssl look in the default directory). Interestingly, connecting to the same server using PHP's openssl functions (as used in PHPMailer 5) worked fine.
You can still use NSDictionaries in Swift:
For Swift 4
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
For Swift 3+
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
let myDict = NSDictionary(contentsOfFile: path){
// Use your myDict here
}
And older versions of Swift
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
// Use your dict here
}
The NSClasses are still available and perfectly fine to use in Swift. I think they'll probably want to shift focus to swift soon, but currently the swift APIs don't have all the functionality of the core NSClasses.
Your server is imposing some resource limit that your site is hitting. This is usually RAM, CPU, or INODES.
Ask your server administrator what the limits are and what it is you are hitting to solve.
Here is the implementation of LinkedList<T>#toArray(T[])
:
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
In short, you could only create generic arrays through Array.newInstance(Class, int)
where int
is the size of the array.
Here is a complete solution to add a UIButton
programmatically with the targetAction.
Swift 2.2
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .greenColor()
button.setTitle("Test Button", forState: .Normal)
button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
It is probably better to use NSLayoutConstraint
rather than frame
to correctly place the button for each iPhone screen.
Updated code to Swift 3.1:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
Updated code to Swift 4.2:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func buttonAction(sender: UIButton!) {
print("Button tapped")
}
The above still works if func buttonAction
is declared private
or internal
.
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
You can use http_response_code()
to set HTTP response code.
If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.
http_response_code(201); // Set response status code to 201
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here
This may help you ;D
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float Stukprijs;
float Aantal;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
}
private void button1_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
errorProvider2.Clear();
if (float.TryParse(textBox1.Text, out Stukprijs))
{
if (float.TryParse(textBox2.Text, out Aantal))
{
float Totaal = Stukprijs * Aantal;
string Output = Totaal.ToString();
textBox3.Text = Output;
if (Totaal >= 100)
{
float korting = Totaal - 100;
float korting2 = korting / 100 * 15;
string Output2 = korting2.ToString();
textBox4.Text = Output2;
if (korting2 >= 10)
{
textBox4.BackColor = Color.LightGreen;
}
else
{
textBox4.BackColor = SystemColors.Control;
}
}
else
{
textBox4.Text = "0";
textBox4.BackColor = SystemColors.Control;
}
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
else
{
errorProvider1.SetError(textBox1, "Bedrag plz!");
if (float.TryParse(textBox2.Text, out Aantal))
{
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
}
private void BTNwissel_Click(object sender, EventArgs e)
{
//LL, LU, LR, LD.
Color c = LL.BackColor;
LL.BackColor = LU.BackColor;
LU.BackColor = LR.BackColor;
LR.BackColor = LD.BackColor;
LD.BackColor = c;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
}
}
}
Here is a generic script you can use in SQL server. just amend the start and end dates:
IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END
CREATE TABLE [Calendar]
(
[CalendarDate] DATETIME
)
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)
WHILE @StartDate <= @EndDate
BEGIN
INSERT INTO [Calendar]
(
CalendarDate
)
SELECT
@StartDate
SET @StartDate = DATEADD(dd, 1, @StartDate)
END
If you want a more advanced calendar here is one I found on the net a while ago:
CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go
CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
@Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT
SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO
CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
[Date] datetime NOT NULL,
[Year] int NOT NULL,
[Quarter] int NOT NULL,
[Month] int NOT NULL,
[Week] int NOT NULL,
[Day] int NOT NULL,
[DayOfYear] int NOT NULL,
[Weekday] int NOT NULL,
[Fiscal_Year] int NOT NULL,
[Fiscal_Quarter] int NOT NULL,
[Fiscal_Month] int NOT NULL,
[KindOfDay] varchar(10) NOT NULL,
[Description] varchar(50) NULL,
PRIMARY KEY CLUSTERED ([Date])
)
GO
ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/
ADD CONSTRAINT [Calendar_ck] CHECK ( ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week] BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO
SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),
DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),
Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,
-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,
CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
WHEN (DATEPART(DayOfYear, d.Date) = 1) -- New Year's Day
OR (d.Date = Auxiliary.Computus(YEAR(Date))-7) -- Palm Sunday
OR (d.Date = Auxiliary.Computus(YEAR(Date))-3) -- Maundy Thursday
OR (d.Date = Auxiliary.Computus(YEAR(Date))-2) -- Good Friday
OR (d.Date = Auxiliary.Computus(YEAR(Date))) -- Easter Sunday
OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1) -- Labour day
OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17) -- Constitution day
OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25) -- Cristmas day
OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26) -- Boxing day
THEN 'HOLIDAY'
WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
WHEN (DATEPART(DayOfYear, d.Date) = 1) THEN 'New Year''s Day'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7) THEN 'Palm Sunday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3) THEN 'Maundy Thursday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2) THEN 'Good Friday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))) THEN 'Easter Sunday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1) THEN 'Labour day'
WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17) THEN 'Constitution day'
WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25) THEN 'Cristmas day'
WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26) THEN 'Boxing day'
END Description
FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
inner join Weeks w
on d.Thursday = w.Thursday
OPTION(MAXRECURSION 0)
GO
CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO
CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO
Also, spark is a nice little bar graph in your shell.
using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener
then add the variable Button button1;
then add this to your onCreate()
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
when you implement OnClickListener you need to add the inherited method onClick()
where you will handle your clicks
The RemoveInvalidXmlChars method provided by Irishman does not support surrogate characters. To test it, use the following example:
static void Main()
{
const string content = "\v\U00010330";
string newContent = RemoveInvalidXmlChars(content);
Console.WriteLine(newContent);
}
This returns an empty string but it shouldn't! It should return "\U00010330" because the character U+10330 is a valid XML character.
To support surrogate characters, I suggest using the following method:
public static string RemoveInvalidXmlChars(string text)
{
if (string.IsNullOrEmpty(text))
return text;
int length = text.Length;
StringBuilder stringBuilder = new StringBuilder(length);
for (int i = 0; i < length; ++i)
{
if (XmlConvert.IsXmlChar(text[i]))
{
stringBuilder.Append(text[i]);
}
else if (i + 1 < length && XmlConvert.IsXmlSurrogatePair(text[i + 1], text[i]))
{
stringBuilder.Append(text[i]);
stringBuilder.Append(text[i + 1]);
++i;
}
}
return stringBuilder.ToString();
}
if ([recognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation1 = [recognizer translationInView:main_view];
img12.center=CGPointMake(img12.center.x+translation1.x, img12.center.y+ translation1.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:main_view];
recognizer.view.center=CGPointMake(recognizer.view.center.x+translation1.x, recognizer.view.center.y+ translation1.y);
}
-(void)move:(UIPanGestureRecognizer*)recognizer
{
if ([recognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center=CGPointMake(recognizer.view.center.x+translation.x, recognizer.view.center.y+ translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
}
In my environment, I encounter this issue in unit test. After appending one library dependency to *.pom, that's fixed.
e.g.:
error message:
java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt
pom:
<dependency>
<groupId>com.abc.def</groupId>
<artifactId>foo</artifactId>
<scope>test</scope>
</dependency>
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
Android studio 4.0.1 Kotlin 1.3.72
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
I have had this error when connecting to a RabbitMQ MQTT server via TLS. I'm pretty sure the server is broken but anyway it worked with OpenSSL 1.0.1, but not OpenSSL 1.0.2.
You can check your version in Python using this:
import ssl
ssl.OPENSSL_VERSION
I'm not sure how to downgrade OpenSSL within Python (it seems to be statically linked on Windows at least), other than using an older version of Python.
Try with below command, and it will ask all values to INT
select case when isnumeric(YourColumn + '.0e0') = 1 then cast(YourColumn as int) else NULL end /* case */ from YourTable
You can use the XMLHttpRequest
object as follows:
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
That code would post someStuff
to url
. Just make sure that when you create your XMLHttpRequest
object, it will be cross-browser compatible. There are endless examples out there of how to do that.
You have to add android:exported="true"
in the manifest file in the activity you are trying to start.
From the android:exported documentation:
android:exported
Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".
This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).
Finally it works for me.
private VideoView videoView;
videoView = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse("http://www.servername.com/projects/projectname/videos/1361439400.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoView.start();
}
});
Hope this would help others.
If your branch is behind by master then do:
git checkout master (you are switching your branch to master)
git pull
git checkout yourBranch (switch back to your branch)
git merge master
After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:
git push
If there is a conflict then fix your file(s), then:
git add yourFile(s)
git commit -m 'updating my branch'
git push
It's the EXIF data that your Samsung phone incorporates.
For SQL Server 2017
Download and run the installer, you are given 3 options:
Download Media <- pick this one!
Extract ISO using your preferred archive utility or mount
Here's a simple CSS solution that'll work:
#fix-footer{
position: fixed;
left: 0px;
bottom: 0px;
height: 35px;
width: 100%;
background: #1abc9c;
}
you can also pyramid of stars like this
for (var i = 5; i >= 1; i--) {
var py = "";
for (var j = i; j >= 1; j--) {
py += j;
}
console.log(py);
}
Try:
C:\Users\USERNAME\.nuget\packages\
That worked for me.
For 2020 Mac OS X Catalina users:
Forget about other useless answers, here only two steps needed:
Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH
.
E.g. 80-vscode
with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/
in my case.
Move that file to /etc/paths.d/
. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH
to check that your path is added!
Notice: this method only appends your path to PATH
.
If you just want a maximum length, use StringUtils.left
! No if
or ternary ?:
needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
Using awk, and based in some of the options below, using a for loop makes a bit more flexible; sometimes I may want to delete the first 9 columns ( if I do an "ls -lrt" for example), so I change the 2 for a 9 and that's it:
awk '{ for(i=0;i++<2;){$i=""}; print $0 }' your_file.txt
Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish,
it should handle writableStream's finish
event.
var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });
I faced the similar situation and it turned out that with the actualisation of Docker Desktop I was signed out and after I signed back in all works fine again.
Jenkins lets you set up multiple times, separated by line breaks.
If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.
H 7 * * *
H 16 * * 0
If you want to go to the previous page without knowing the url, you could use the new History api.
history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.
But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API
For more information see the doc
If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.
If at all possible, use generics. This includes:
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)