To accomplish what you're describing will take two steps...
Step 1: To add the file to the source tarball, include it in the MANIFEST
Create a MANIFEST template in the folder that contains setup.py
The MANIFEST is basically a text file with a list of all the files that will be included in the source tarball.
Here's what the MANIFEST for my project look like:
Note: While sdist does add some files automatically, I prefer to explicitly specify them to be sure instead of predicting what it does and doesn't.
Step 2: To install the data file to the source folder, modify setup.py
Since you're looking to add a data file (LICENSE.txt) to the source install folder you need to modify the data install path to match the source install path. This is necessary because, by default, data files are installed to a different location than source files.
To modify the data install dir to match the source install dir...
Pull the install dir info from distutils with:
from distutils.command.install import INSTALL_SCHEMES
Modify the data install dir to match the source install dir:
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
And, add the data file and location to setup():
data_files=[('', ['LICENSE.txt'])]
Note: The steps above should accomplish exactly what you described in a standard manner without requiring any extension libraries.
If you are in a scenario where you are using one of the latest versions of Ubuntu (or variants like Linux Mint), one which comes with Python 3.8, then you will NOT be able to have Python3.7 distutils
, alias not be able to use pip
or pipenv
with Python 3.7, see:
How to install python-distutils for old python versions
Obviously using Python3.8 is no problem.
It works fine if you follow the official documentation:
import setuptools
setuptools.setup(...)
Source: https://packaging.python.org/tutorials/packaging-projects/#creating-setup-py
My simple answer.
def get_files_tree(src="src_path"):
req_files = []
for r, d, files in os.walk(src):
for file in files:
src_file = os.path.join(r, file)
src_file = src_file.replace('\\', '/')
if src_file.endswith('.db'):
continue
req_files.append(src_file)
return req_files
def copy_tree_force(src_path="",dest_path=""):
"""
make sure that all the paths has correct slash characters.
"""
for cf in get_files_tree(src=src_path):
df= cf.replace(src_path, dest_path)
if not os.path.exists(os.path.dirname(df)):
os.makedirs(os.path.dirname(df))
shutil.copy2(cf, df)
I use this and it works fine
#/bin/bash
/usr/bin/python python python_script.py
Step-1: Change the file name src/App.js to src/app.js
Step-2: Click on "Yes" for "Update imports for app.js".
Step-3: Restart the server again.
Here is my suggested validation:
var isValid = false;
// Check whether this entered value is numeric.
function checkNumeric() {
var numericVal = document.getElementById("txt_numeric").value;
if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
alert("Please, enter a numeric value!");
isValid = false;
} else {
isValid = true;
}
}
No. As the documentation shows, you can only grant access to one object at a time.
The trick for me was I had ssh
conflict.
I have Git installed on my Windows path, which includes ssh. cwrsync also installs ssh.
The trick is to have make a batch file to set the correct paths:
rsync.bat
@echo off
SETLOCAL
SET CWRSYNCHOME=c:\commands\cwrsync
SET HOME=c:\Users\Petah\
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%
%~dp0\cwrsync\bin\rsync.exe %*
On Windows you can type where ssh
to check if this is an issue. You will get something like this:
where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
C:\Program Files\cwRsync\ssh.exe
There are three methods you can pass values in the function
Pass by value
void f(int n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 3. Disadvantage: When parameter x
pass through f
function then compiler creates a copy in memory in of x. So wastage of memory.
Pass by reference
void f(int& n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference
Constant reference
void f(const int& n){
n = n + 10; // Error: assignment of read-only reference ‘n’
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: Throw error at n = n + 10
because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.
You should add the following lines in your gradle build file (build.gradle)
dependencies {
compile files('/usr/share/stuff')
..
}
In Python 3.5, isinstance(x, date)
works to me:
>>> from datetime import date
>>> x = date(2012, 9, 1)
>>> type(x)
<class 'datetime.date'>
>>> isinstance(x, date)
True
>>> type(x) is date
True
You can do this:
public int Property { get { ... } private set { ... } }
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
in ubuntu 16.04 when i tried to connect to phpmyadmin a white blank paged appeared so i ran the above command and phpmyadmin works
sudo apt-get install php-mbstring php7.0-mbstring php-gettext
for mysql support install
sudo apt-get install php7.0-mysql
tested in ubuntu 16.04 with php 7 version
I wanted something that would purge all local branches that were tracking a remote branch, on origin
, where the remote branch has been deleted (gone
). I did not want to delete local branches that were never set up to track a remote branch (i.e.: my local dev branches). Also, I wanted a simple one-liner that just uses git
, or other simple CLI tools, rather than writing custom scripts. I ended up using a bit of grep
and awk
to make this simple command, then added it as an alias in my ~/.gitconfig
.
[alias]
prune-branches = !git remote prune origin && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D
Here is a git config --global ...
command for easily adding this as git prune-branches
:
git config --global alias.prune-branches '!git remote prune origin && git branch -vv | grep '"'"': gone]'"'"' | awk '"'"'{print $1}'"'"' | xargs -r git branch -d'
NOTE: Use of the -D
flag to git branch
can be very dangerous. So, in the config command above I use the -d
option to git branch
rather than -D
; I use -D
in my actual config. I use -D
because I don't want to hear Git complain about unmerged branches, I just want them to go away. You may want this functionality as well. If so, simply use -D
instead of -d
at the end of that config command.
Most opensource projects use GetText for this purpose. I don't know how and if it's ever been used on a .Net project before.
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+------+----------------------+
select group_concat(name) from Pets
group by type
Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values
Result:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+
Well, you could make it static
:
static const int t = 100;
or you could use a member initializer:
T1() : t(100)
{
// Other constructor stuff here
}
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
FYI, to access any script via command-line like you were trying, you need to have the script registered as a shell-script (or any kind of script like .js, .rb) in the system like these files in the the dir
/usr/bin
in UNIX. And, system must know where to find them. i.e. the location must be loaded in$PATH
array.
In your case, the script webpack-dev-server
is already installed somewhere inside ./node_modules
directory, but system does not know how to access it. So, to access the command webpack-dev-server
, you need to install the script in global scope as well.
$ npm install webpack-dev-server -g
Here, -g
refers to global scope.
However, this is not recommended way because you might face version conflicting issues; so, instead you can set a command in npm
's package.json
file like:
"scripts": {
"start": "webpack-dev-server -d --config webpack.dev.config.js --content-base public/ --progress --colors"
}
This setting will let you access the script you want with simple command
$ npm start
So short to memorize and play. And, npm
knows the location of the module webpack-dev-server
.
This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");
breaking up the script keyword because VStudio / asp.net compiler doesn't like it
If you indeed wanna use scp, there's a indirect way.Say we want to copy all .jpg file under local folder '/src' to folder '/dst' in remote server 10.1.1.2:
#make a clean temp folder
mkdir /tmp/ttt
#copy all .jpg file and retain folder structure as-is
find /src -type f -name *.jpg -exec cp --parents \{\} /tmp/ttt \;
#copy to remote target folder as-is and retain original time attributes
scp -rp /tmp/ttt/* 10.1.1.2:/dst
#if copy ok, remove temp folder
rm -rf /tmp/ttt
The ability to have git ignore files you don't wish it to track is very useful.
To ignore a file or set of files you supply a pattern. The pattern syntax for git is fairly simple, but powerful. It is applicable to all three of the different files I will mention bellow.
Great Example from the gitignore(5) man page:
$ git status
[...]
# Untracked files:
[...]
# Documentation/foo.html
# Documentation/gitignore.html
# file.o
# lib.a
# src/internal.o
[...]
$ cat .git/info/exclude
# ignore objects and archives, anywhere in the tree.
*.[oa]
$ cat Documentation/.gitignore
# ignore generated html files,
*.html
# except foo.html which is maintained by hand
!foo.html
$ git status
[...]
# Untracked files:
[...]
# Documentation/foo.html
[...]
Generally there are three different ways to ignore untracked files.
1) Ignore for all users of the repository:
Add a file named .gitignore to the root of your working copy.
Edit .gitignore to match your preferences for which files should/shouldn't be ignored.
git add .gitignore
and commit when you're done.
2) Ignore for only your copy of the repository:
Add/Edit the file $GIT_DIR/info/exclude in your working copy, with your preferred patterns.
Ex: My working copy is ~/src/project1 so I would edit ~/src/project1/.git/info/exclude
You're done!
3) Ignore in all situations, on your system:
Global ignore patterns for your system can go in a file named what ever you wish.
Mine personally is called ~/.gitglobalignore
I can then let git know of this file by editing my ~/.gitconfig file with the following line:
core.excludesfile = ~/.gitglobalignore
You're done!
I find the gitignore man page to be the best resource for more information.
There is likely whitespace outside of your php tags.
Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:
I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.
I had this:
return(
data.frame(
user_id = gift$email,
sourced_from_agent_id = gift$source,
method_used = method,
given_to = gift$account,
recurring_subscription_id = NULL,
notes = notes,
stringsAsFactors = FALSE
)
)
turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.
When I checked out a new project from the repository, I did not see the icon overlays.
I started looking for solutions and came to this question.
While reading answers, I noticed the icon overlays appeared on my checkout project.
I guess it just took a few minutes for the icons to appear.
I thought this might be useful before people panic quickly and start editing the registry.
On the basis of @BBonifield answer, I wrote a utility function so that semaphore logic is not spread in all the ajax calls.
untilAjax
is the utility function which invokes a callback function when all the ajaxCalls are completed.
ajaxObjs
is a array of ajax setting objects [http://api.jquery.com/jQuery.ajax/]
.
fn
is callback function
function untilAjax(ajaxObjs, fn) {
if (!ajaxObjs || !fn) {
return;
}
var ajaxCount = ajaxObjs.length,
succ = null;
for (var i = 0; i < ajaxObjs.length; i++) { //append logic to invoke callback function once all the ajax calls are completed, in success handler.
succ = ajaxObjs[i]['success'];
ajaxObjs[i]['success'] = function(data) { //modified success handler
if (succ) {
succ(data);
}
ajaxCount--;
if (ajaxCount == 0) {
fn(); //modify statement suitably if you want 'this' keyword to refer to another object
}
};
$.ajax(ajaxObjs[i]); //make ajax call
succ = null;
};
Example: doSomething
function uses untilAjax
.
function doSomething() {
// variable declarations
untilAjax([{
url: 'url2',
dataType: 'json',
success: function(data) {
//do something with success data
}
}, {
url: 'url1',
dataType: 'json',
success: function(data) {
//do something with success data
}
}, {
url: 'url2',
dataType: 'json',
success: function(response) {
//do something with success data
}
}], function() {
// logic after all the calls are completed.
});
}
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.
At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.
<script type="text/javascript">
$(function() {
// this code detects a button click and sets an `option` attribute
// in the form to be the `name` attribute of whichever button was clicked
$('form input[type=submit]').click(function() {
var $form = $('form');
form.removeAttr('option');
form.attr('option', $(this).attr('name'));
});
// this code updates the URL before the form is submitted
$("form").submit(function(e) {
var option = $(this).attr("option");
if (option) {
e.preventDefault();
var currentUrl = $(this).attr("action");
$(this).attr('action', currentUrl + "/" + option).submit();
}
});
});
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />
Now at the server side we can add a new route to handle the excel request
routes.MapRoute(
name: "ExcelExport",
url: "SearchDisplay/Submit/excel",
defaults: new
{
controller = "SearchDisplay",
action = "SubmitExcel",
});
You can setup 2 distinct actions
public ActionResult SubmitExcel(SearchCostPage model)
{
...
}
public ActionResult Submit(SearchCostPage model)
{
...
}
Or you can use the ActionName
attribute as an alias
public ActionResult Submit(SearchCostPage model)
{
...
}
[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
...
}
This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:
#include <stdio.h>
typedef struct foo_t {
int a; int b; int c;
} foo_t;
static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
// or a pointer
static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
int main (int argc, char **argv) {
const foo_t *const f1 = &s_FooInit;
const foo_t *const f2 = s_pFooInit;
printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
return 0;
}
(change)
event bound to classical input change event.
https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">
(ngModelChange)
is the @Output
of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code, (ngModelChange)
emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
// do something with new value
}
Basically, it seems like there is no big difference between two, but ngModel
events gains the power when you use [ngValue]
.
<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
<option *ngFor="let currentData of allData" [ngValue]="currentData">
{{data.name}}
</option>
</select>
dataChanged(newObj) {
// here comes the object as parameter
}
assume you try the same thing without "ngModel
things"
<select (change)="changed($event)">
<option *ngFor="let currentData of allData" [value]="currentData.id">
{{data.name}}
</option>
</select>
changed(e){
// event comes as parameter, you'll have to find selectedData manually
// by using e.target.data
}
Since Django 2.x, on_delete
is required.
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
Short answer:
Use Delimiter='/'
. This avoids doing a recursive listing of your bucket. Some answers here wrongly suggest doing a full listing and using some string manipulation to retrieve the directory names. This could be horribly inefficient. Remember that S3 has virtually no limit on the number of objects a bucket can contain. So, imagine that, between bar/
and foo/
, you have a trillion objects: you would wait a very long time to get ['bar/', 'foo/']
.
Use Paginators
. For the same reason (S3 is an engineer's approximation of infinity), you must list through pages and avoid storing all the listing in memory. Instead, consider your "lister" as an iterator, and handle the stream it produces.
Use boto3.client
, not boto3.resource
. The resource
version doesn't seem to handle well the Delimiter
option. If you have a resource, say a bucket = boto3.resource('s3').Bucket(name)
, you can get the corresponding client with: bucket.meta.client
.
Long answer:
The following is an iterator that I use for simple buckets (no version handling).
import boto3
from collections import namedtuple
from operator import attrgetter
S3Obj = namedtuple('S3Obj', ['key', 'mtime', 'size', 'ETag'])
def s3list(bucket, path, start=None, end=None, recursive=True, list_dirs=True,
list_objs=True, limit=None):
"""
Iterator that lists a bucket's objects under path, (optionally) starting with
start and ending before end.
If recursive is False, then list only the "depth=0" items (dirs and objects).
If recursive is True, then list recursively all objects (no dirs).
Args:
bucket:
a boto3.resource('s3').Bucket().
path:
a directory in the bucket.
start:
optional: start key, inclusive (may be a relative path under path, or
absolute in the bucket)
end:
optional: stop key, exclusive (may be a relative path under path, or
absolute in the bucket)
recursive:
optional, default True. If True, lists only objects. If False, lists
only depth 0 "directories" and objects.
list_dirs:
optional, default True. Has no effect in recursive listing. On
non-recursive listing, if False, then directories are omitted.
list_objs:
optional, default True. If False, then directories are omitted.
limit:
optional. If specified, then lists at most this many items.
Returns:
an iterator of S3Obj.
Examples:
# set up
>>> s3 = boto3.resource('s3')
... bucket = s3.Bucket(name)
# iterate through all S3 objects under some dir
>>> for p in s3ls(bucket, 'some/dir'):
... print(p)
# iterate through up to 20 S3 objects under some dir, starting with foo_0010
>>> for p in s3ls(bucket, 'some/dir', limit=20, start='foo_0010'):
... print(p)
# non-recursive listing under some dir:
>>> for p in s3ls(bucket, 'some/dir', recursive=False):
... print(p)
# non-recursive listing under some dir, listing only dirs:
>>> for p in s3ls(bucket, 'some/dir', recursive=False, list_objs=False):
... print(p)
"""
kwargs = dict()
if start is not None:
if not start.startswith(path):
start = os.path.join(path, start)
# note: need to use a string just smaller than start, because
# the list_object API specifies that start is excluded (the first
# result is *after* start).
kwargs.update(Marker=__prev_str(start))
if end is not None:
if not end.startswith(path):
end = os.path.join(path, end)
if not recursive:
kwargs.update(Delimiter='/')
if not path.endswith('/'):
path += '/'
kwargs.update(Prefix=path)
if limit is not None:
kwargs.update(PaginationConfig={'MaxItems': limit})
paginator = bucket.meta.client.get_paginator('list_objects')
for resp in paginator.paginate(Bucket=bucket.name, **kwargs):
q = []
if 'CommonPrefixes' in resp and list_dirs:
q = [S3Obj(f['Prefix'], None, None, None) for f in resp['CommonPrefixes']]
if 'Contents' in resp and list_objs:
q += [S3Obj(f['Key'], f['LastModified'], f['Size'], f['ETag']) for f in resp['Contents']]
# note: even with sorted lists, it is faster to sort(a+b)
# than heapq.merge(a, b) at least up to 10K elements in each list
q = sorted(q, key=attrgetter('key'))
if limit is not None:
q = q[:limit]
limit -= len(q)
for p in q:
if end is not None and p.key >= end:
return
yield p
def __prev_str(s):
if len(s) == 0:
return s
s, c = s[:-1], ord(s[-1])
if c > 0:
s += chr(c - 1)
s += ''.join(['\u7FFF' for _ in range(10)])
return s
Test:
The following is helpful to test the behavior of the paginator
and list_objects
. It creates a number of dirs and files. Since the pages are up to 1000 entries, we use a multiple of that for dirs and files. dirs
contains only directories (each having one object). mixed
contains a mix of dirs and objects, with a ratio of 2 objects for each dir (plus one object under dir, of course; S3 stores only objects).
import concurrent
def genkeys(top='tmp/test', n=2000):
for k in range(n):
if k % 100 == 0:
print(k)
for name in [
os.path.join(top, 'dirs', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_foo_a'),
os.path.join(top, 'mixed', f'{k:04d}_foo_b'),
]:
yield name
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
executor.map(lambda name: bucket.put_object(Key=name, Body='hi\n'.encode()), genkeys())
The resulting structure is:
./dirs/0000_dir/foo
./dirs/0001_dir/foo
./dirs/0002_dir/foo
...
./dirs/1999_dir/foo
./mixed/0000_dir/foo
./mixed/0000_foo_a
./mixed/0000_foo_b
./mixed/0001_dir/foo
./mixed/0001_foo_a
./mixed/0001_foo_b
./mixed/0002_dir/foo
./mixed/0002_foo_a
./mixed/0002_foo_b
...
./mixed/1999_dir/foo
./mixed/1999_foo_a
./mixed/1999_foo_b
With a little bit of doctoring of the code given above for s3list
to inspect the responses from the paginator
, you can observe some fun facts:
The Marker
is really exclusive. Given Marker=topdir + 'mixed/0500_foo_a'
will make the listing start after that key (as per the AmazonS3 API), i.e., with .../mixed/0500_foo_b
. That's the reason for __prev_str()
.
Using Delimiter
, when listing mixed/
, each response from the paginator
contains 666 keys and 334 common prefixes. It's pretty good at not building enormous responses.
By contrast, when listing dirs/
, each response from the paginator
contains 1000 common prefixes (and no keys).
Passing a limit in the form of PaginationConfig={'MaxItems': limit}
limits only the number of keys, not the common prefixes. We deal with that by further truncating the stream of our iterator.
This is how I implemented my URL builder. I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
@Component
public class ParamsProviderImp implements ParamsProvider {
@Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
@Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it. Example for that is below.
Class Mock{
@Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
This may be helpful install pynput with -- pip install pynput
from pynput.keyboard import Key, Listener
def on_release(key):
if key == Key.esc:
# Stop listener
return False
# Collect events until released
while True:
with Listener(
on_release=on_release) as listener:
listener.join()
break
use the below code please :
Properties p = new Properties();
StringBuffer path = new StringBuffer("com/al/common/email/templates/");
path.append("foo.properties");
InputStream fs = getClass().getClassLoader()
.getResourceAsStream(path.toString());
if(fs == null){
System.err.println("Unable to load the properties file");
}
else{
try{
p.load(fs);
}
catch (IOException e) {
e.printStackTrace();
}
}
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Templates (<template>
, or <ng-template>
since 4.x) are added as embedded views and get passed a context.
With let-col
the context property $implicit
is made available as col
within the template for bindings.
With let-foo="bar"
the context property bar
is made available as foo
.
For example if you add a template
<ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
See also this answer and ViewContainerRef#createEmbeddedView.
*ngFor
also works this way. The canonical syntax makes this more obvious
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
where NgFor
adds the template as embedded view to the DOM for each item
of items
and adds a few values (item
, index
, odd
) to the context.
I'm guessing you get the error on accessing audioSounds
and minTime
, right?
The problem is you can't access instance members
from static methods
. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).
Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds
list it should access?
Like others said, make your audioSounds
and minTime
static, or you could make your method an instance method, if your design permits it.
http://dev.mysql.com/doc/refman/5.6/en/load-data-local.html
Put this in my.cnf - the [client]
section should already be there
(if you're not too concerned about security).
[client]
loose-local-infile=1
https://github.com/bkdotcom/PHPDebugConsole
Support for all the javascript console methods:
assert, clear, count, error, group, groupCollapsed, groupEnd, info, log, table, trace, time, timeEnd, warn
plus a few more:
alert, groupSummary, groupUncollapse, timeGet
$debug = new \bdk\Debug(array(
'collect' => true,
'output' => true,
'outputAs' => 'script',
));
$debug->log('hello world');
$debug->info('all of the javascript console methods are supported');
\bdk\Debug::_log('can use static methods');
$debug->trace();
$list = array(
array('userId'=>1, 'name'=>'Bob', 'sex'=>'M', 'naughty'=>false),
array('userId'=>10, 'naughty'=>true, 'name'=>'Sally', 'extracol' => 'yes', 'sex'=>'F'),
array('userId'=>2, 'name'=>'Fred', 'sex'=>'M', 'naughty'=>false),
);
$debug->table('people', $list);
this will output the appropriate <script>
tag upon script shutdown
alternatively, you can output as html, chromeLogger, FirePHP, file, plaintext, websockets, etc
upcomming release includes a psr-3 (logger) implementation
In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env
folder and each file contains settings for particular env.
Sails first looks in config/env folder and then look forward to config/ *.js
Now lets setup ssl in config/local.js
.
var local = {
port: process.env.PORT || 1337,
environment: process.env.NODE_ENV || 'development'
};
if (process.env.NODE_ENV == 'production') {
local.ssl = {
secureProtocol: 'SSLv23_method',
secureOptions: require('constants').SSL_OP_NO_SSLv3,
ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
};
local.port = 443; // This port should be different than your default port
}
module.exports = local;
Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)
Or in production.js
module.exports = {
port: 443,
ssl: {
secureProtocol: 'SSLv23_method',
secureOptions: require('constants').SSL_OP_NO_SSLv3,
ca: [
require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
],
key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
}
};
Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.
There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.
So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.
In config/bootstrap.js (Create http server and redirect all request to https)
module.exports.bootstrap = function(cb) {
var express = require("express"),
app = express();
app.get('*', function(req, res) {
if (req.isSocket)
return res.redirect('wss://' + req.headers.host + req.url)
return res.redirect('https://' + req.headers.host + req.url)
}).listen(80);
cb();
};
Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Add class Startup.cs to root of project with next code:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(ProjectName.Startup))]
namespace ProjectName
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
You could select and style this with JavaScript or jQuery, but CSS alone can't do this.
For example, if you have jQuery implemented on the site, you could just do:
var last_visible_element = $('div:visible:last');
Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:
var last_visible_element = $('#some-wrapper div:visible:last');
Another alternative that seems faster than REGEXP on my computer is
SELECT * FROM myTable WHERE col1*0 != col1;
This will select all rows where col1 starts with a numeric value.
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
you need to decode the bytes
of you want a string:
b = b'1234'
print(b.decode('utf-8')) # '1234'
I would be very careful if you are considering adopting this hashbang convention.
Once you hashbang, you can’t go back. This is probably the stickiest issue. Ben’s post put forward the point that when pushState is more widely adopted then we can leave hashbangs behind and return to traditional URLs. Well, fact is, you can’t. Earlier I stated that URLs are forever, they get indexed and archived and generally kept around. To add to that, cool URLs don’t change. We don’t want to disconnect ourselves from all the valuable links to our content. If you’ve implemented hashbang URLs at any point then want to change them without breaking links the only way you can do it is by running some JavaScript on the root document of your domain. Forever. It’s in no way temporary, you are stuck with it.
You really want to use pushState instead of hashbangs, because making your URLs ugly and possibly broken -- forever -- is a colossal and permanent downside to hashbangs.
Here is how I do it. You will need to get the namespace URL and the element name from your generated code.
new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
new String("").getClass(),testDN);
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
If you are using Swift, the Just library does this for you. Example from it's readme file:
// talk to registration end point
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
if (r.ok) { /* success! */ }
}
You can simply use padding-left:60% (for ex) to align your content to right and simultaneously wrap the content in responsive container (I required navbar in my case) to ensure it works in all examples.
If you want to allow a comma delimiter which will pass the following test cases:
0,00 => true
0.00 => true
01,00 => true
01.00 => true
0.000 => false
0-01 => false
then use this:
^\d+(\.|\,)\d{2}$
First of all need to understand what is CSV and how to write it.
(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)
/r/n
) is next "table" row.\t
or ,
./r/n
symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO
library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
Simple example of using my library:
Csv csv = new Csv("\t");//delimiter symbol
csv.FileOpen("c:\\file1.csv");
var row1Cell6Value = csv.Rows[0][5];
csv.AddRow("asdf","asdffffff","5")
csv.FileSave("c:\\file2.csv");
You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter
This library code is really fast in work and source code is really short.
PS: In the same time this solution will not work for unity.
PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.
You have this bad but usefull technic:
$var = json_decode(json_encode([]), FALSE);
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
You could do this:
if (!discount.nil? && !discount.zero?)
The order is important here, because if discount
is nil
, then it will not have a zero?
method. Ruby's short-circuit evaluation should prevent it from trying to evaluate discount.zero?
, however, if discount
is nil
.
My Source: http://htmlhelp.com/tools/validator/problems.html#amp
Another common error occurs when including a URL which contains an ampersand ("&"):
This is invalid:
a href="foo.cgi?chapter=1§ion=2©=3&lang=en"
Explanation:
This example generates an error for "unknown entity section" because the
"&"
is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert ©=3 to ©=3, which may cause the link to fail. Since 〈 is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting §ion=2 to §ion=2.
So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &
when writing a URL in your markup.
Note that replacing
&
with&
; is only done when writing the URL in HTML, where"&"
is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use"&"
and not"&"
. With HTML, the browser translates"&"
to"&"
so the Web server would only see"&"
and not"&"
in the query string of the request.
Hope this helps : )
This is more of an example where TABLOCK did not work for me and TABLOCKX did.
I have 2 sessions, that both use the default (READ COMMITTED) isolation level:
Session 1 is an explicit transaction that will copy data from a linked server to a set of tables in a database, and takes a few seconds to run. [Example, it deletes Questions] Session 2 is an insert statement, that simply inserts rows into a table that Session 1 doesn't make changes to. [Example, it inserts Answers].
(In practice there are multiple sessions inserting multiple records into the table, simultaneously, while Session 1 is running its transaction).
Session 1 has to query the table Session 2 inserts into because it can't delete records that depend on entries that were added by Session 2. [Example: Delete questions that have not been answered].
So, while Session 1 is executing and Session 2 tries to insert, Session 2 loses in a deadlock every time.
So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ LEFT JOIN tblX on ... LEFT JOIN tblA a ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...
The deadlock seems to be caused from contention between querying tblA while Session 2, [3, 4, 5, ..., n] try to insert into tblA.
In my case I could change the isolation level of Session 1's transaction to be SERIALIZABLE. When I did this: The transaction manager has disabled its support for remote/network transactions.
So, I could follow instructions in the accepted answer here to get around it: The transaction manager has disabled its support for remote/network transactions
But a) I wasn't comfortable with changing the isolation level to SERIALIZABLE in the first place- supposedly it degrades performance and may have other consequences I haven't considered, b) didn't understand why doing this suddenly caused the transaction to have a problem working across linked servers, and c) don't know what possible holes I might be opening up by enabling network access.
There seemed to be just 6 queries within a very large transaction that are causing the trouble.
So, I read about TABLOCK and TabLOCKX.
I wasn't crystal clear on the differences, and didn't know if either would work. But it seemed like it would. First I tried TABLOCK and it didn't seem to make any difference. The competing sessions generated the same deadlocks. Then I tried TABLOCKX, and no more deadlocks.
So, in six places, all I needed to do was add a WITH (TABLOCKX).
So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ q LEFT JOIN tblX x on ... LEFT JOIN tblA a WITH (TABLOCKX) ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
When working with continuations I find it useful to think of the place where I write .ContinueWith as the place from which execution immediately continues to the statements following it, not the statements 'inside' it. In that case it becomes clear that you would get an empty string returned in Send. If your only processing of the response is writing it to the console, you don't need any Wait in Ito's solution - the console printout will happen without waits but both Send and Print should return void in that case. Run this in console app and you will get printout of the page.
IMO, waits and Task.Result calls (which block) are necessary sometimes, depending on your desired flow of control, but more often they are a sign that you don't really use asynchronous functionality correctly.
namespace TaskTest
{
class Program
{
static void Main(string[] args)
{
Send();
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
private static void Send()
{
HttpClient client = new HttpClient();
Task<HttpResponseMessage> responseTask = client.GetAsync("http://google.com");
responseTask.ContinueWith(x => Print(x));
}
private static void Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
Task continuation = task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
});
}
}
}
http://code.google.com/p/google-api-javascript-client/wiki/Authentication
See the area where it reads:
Setting up Authentication
The client's implementation of OAuth 2.0 uses a popup window to prompt the user to sign-in and approve the application. The first call to gapi.auth.authorize can trigger popup blockers, as it opens the popup window indirectly. To prevent the popup blocker from triggering on auth calls, call gapi.auth.init(callback) when the client loads. The supplied callback will be executed when the library is ready to make auth calls.
I would guess its relating to the real answer above in how it explains if there is an immediate response, it won't trip the popup alarm. The "gapi.auth.init" is making it so the api happens immediately.
Practical Application
I made an open source authentication microservice using node passport on npm and the various passport packages for each provider. I used a standard redirect approach to the 3rd party giving it a redirect URL to come back to. This was programmatic so I could have different places to redirect back to if login/signup and on particular pages.
Try applying the clear:none
css attribute to the label.
.label {
clear:none;
}
Actually NULL filter is not being ignored. Thing is this is how joining two tables work.
I will try to walk down with the steps performed by database server to make it understand.
For example when you execute the query which you said is ignoring the NULL condition.
SELECT
*
FROM
shipments s
LEFT OUTER JOIN returns r
ON s.id = r.id
AND r.id is null
WHERE
s.day >= CURDATE() - INTERVAL 10 DAY
1st thing happened is all the rows from table SHIPMENTS get selected
on next step database server will start selecting one by one record from 2nd(RETURNS) table.
on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)
note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.
And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.
if you do not intend to have static functions just get rid of the "this" keyword in the arguments.
Ok, after some work I'm able to get a "bubble" to pop up and go away at all the right times. There is a LOT of styling that needs to happen still but this is basically the code i used.
<script type="text/javascript">
//--indicates the mouse is currently over a div
var onDiv = false;
//--indicates the mouse is currently over a link
var onLink = false;
//--indicates that the bubble currently exists
var bubbleExists = false;
//--this is the ID of the timeout that will close the window if the user mouseouts the link
var timeoutID;
function addBubbleMouseovers(mouseoverClass) {
$("."+mouseoverClass).mouseover(function(event) {
if (onDiv || onLink) {
return false;
}
onLink = true;
showBubble.call(this, event);
});
$("." + mouseoverClass).mouseout(function() {
onLink = false;
timeoutID = setTimeout(hideBubble, 150);
});
}
function hideBubble() {
clearTimeout(timeoutID);
//--if the mouse isn't on the div then hide the bubble
if (bubbleExists && !onDiv) {
$("#bubbleID").remove();
bubbleExists = false;
}
}
function showBubble(event) {
if (bubbleExists) {
hideBubble();
}
var tPosX = event.pageX + 15;
var tPosY = event.pageY - 60;
$('<div ID="bubbleID" style="top:' + tPosY + '; left:' + tPosX + '; position: absolute; display: inline; border: 2px; width: 200px; height: 150px; background-color: Red;">TESTING!!!!!!!!!!!!</div>').mouseover(keepBubbleOpen).mouseout(letBubbleClose).appendTo('body');
bubbleExists = true;
}
function keepBubbleOpen() {
onDiv = true;
}
function letBubbleClose() {
onDiv = false;
hideBubble();
}
//--TESTING!!!!!
$("document").ready(function() {
addBubbleMouseovers("temp1");
});
</script>
Here is a snippet of the html that goes with it:
<a href="" class="temp1">Mouseover this for a terribly ugly red bubble!</a>
This is what I use to output parameter lists for a stored procedure into the debug console:
string query = (from SqlParameter p in sqlCmd.Parameters where p != null where p.Value != null select string.Format("Param: {0} = {1}, ", p.ParameterName, p.Value.ToString())).Aggregate(sqlCmd.CommandText, (current, parameter) => current + parameter);
Debug.WriteLine(query);
This will generate a console outputt simlar to this:
Customer.prGetCustomerDetails: @Offset = 1, Param: @Fetch = 10, Param: @CategoryLevel1ID = 3, Param: @VehicleLineID = 9, Param: @SalesCode1 = bce,
I place this code directly below any procedure I wish to debug and is similar to a sql profiler session but in C#.
public static class Utilities
{
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html
About DataContractJsonSerializer Class
you can read here.
What? Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
line = lineinput(1)
dim namevalue() as string = split(line, "=")
if namevalue(0) = "line name value that i want to edit" then
currentpos = seek(1)
fileclose()
dim fs as filestream("test.ini", filemode.open)
dim sw as streamwriter(fs)
fs.seek(currentpos, seekorigin.begin)
sw.write(null)
sw.write(namevalue + "=" + newvalue)
sw.close()
fs.close()
exit while
end if
msgbox("org ternate jua bisa, no line found")
end while
that's all..use #d
The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.
Pseudocode:
MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations,
// then we're inside the mandelbrot set!!!
foreach (x-pixel)
foreach (y-pixel)
calculate x,y as mathematical coordinates from your pixel coordinates
value = (x, y)
count = 0
while value.absolutevalue < 1 billion and count < MAX_COUNT
value = value * value + (x, y)
count = count + 1
// the following should really be one statement, but I split it for clarity
if count == MAX_COUNT
pixel_at (x-pixel, y-pixel) = BLACK
else
pixel_at (x-pixel, y-pixel) = colors[count] // some color map.
Notes:
value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.
File format
This tool parses .CRX version 2 format documented by Google. In general, .CRX file format consist of few parts:
Magic header
Version of file format
Public Key information and a package signature
Zipped contents of the extension source code
Magic header is a signature of the file telling that this file is Chrome Extension. Using this header the operating system can determine the actual type of the file (MIME type is application/x-chrome-extension), and how should it be treaten (is it executable? is it a text file?). Then the window system can show beautiful icon to the user.
In .CRX files the magic header has a constant value Cr24 or 0x43723234.
The version is provided by vendor. The version bytes are 0x02000000.
The next part of the file contains the length of the public key information and the length of a digital signature.
All .CRX packages distributed via Chrome WebStore should have public key information and digital signature in order to make possible for browser to check that the package has been transmitted without modifications and that no additions or replacements were made.
After all of the header stuff, typically ending up on 307'th byte, comes the code of extension, stored as zip-archive. So the remainder of the .crx file is the well-known .zip archive.
.crx file opened in the hex editor called HexFiend (on Mac) The header part of a .crx file selected on the picture above. Obviously, you can extract the remaining .zip archive "by hand" using any simple hex editor. In this example, we use handy HexFiend editor on Mac.
The CRX Extractor loads a file provided, checks a magic header, version and trims the file, so only .zip archive remains. Then it returns obtained .zip archive to user.
Probably very late to the answer but I just read this while preparing for my 70-480
exam, and found this to work -
var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }
Notice the event as onclick
instead of onClick
.
JS Bin example.
For those using Cobertura and only have the Coverage Session View like I do,just try closing Eclipse and starting it up again. This got rid of the highlighting for me.
I think I found a way to do this with the Compile Include=".\Code***.cs" What I wanted is to include code recursively under my Code folder.
Here is the project file sample.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="15.0" DefaultTargets="BuildTarget">
<PropertyGroup>
<OutputType>Library</OutputType>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup>
<RootNamespace>Autogen</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Remove="@(Compile)" />
<Compile Include=".\Code\**\*.cs" />
</ItemGroup>
<Target Name="BuildTarget">
<Message Text="Build selected" Importance="high"/>
</Target>
</Project>
You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.
ImageView iv = (ImageView)findViewById(R.id.ImageView01);
iv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and str.join
was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported str
methods including join
) was released in Oct 2000.
str.join(seq)
seq.join(str)
seq.reduce(str)
join
as a built-in functionlist
s, tuple
s, but all sequences/iterables.seq.reduce(str)
is difficult for new-comers.seq.join(str)
introduces unexpected dependency from sequences to str/unicode.join()
as a built-in function would support only specific data types. So using a built in namespace is not good. If join()
supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__
method then it's O(n²).sep
) should not be omitted. Explicit is better than implicit.There are no other reasons offered in this thread.
Here are some additional thoughts (my own, and my friend's):
Guido's decision is recorded in a historical mail, deciding on str.join(seq)
:
Funny, but it does seem right! Barry, go for it...
--Guido van Rossum
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
Try this
plt.imshow(im.reshape(im.shape[0], im.shape[1]), cmap=plt.cm.Greys)
It would help in some cases.
SELECT p.LastName, p.FirstName, o.OrderNo
FROM persons AS p
LEFT JOIN
orders AS o
ON o.orderNo = p.p_id
UNION ALL
SELECT NULL, NULL, orderNo
FROM orders
WHERE orderNo NOT IN
(
SELECT p_id
FROM persons
)
You should not be using buttons of the same name. It's bad semantics. Instead, you should modify your backend to look for different name values being set:
<input type="submit" name="COMMAND_PREV" value="‹ Prev">
<input type="submit" name="COMMAND_SAVE" value="Save">
<input type="reset" name="NOTHING" value="Reset">
<input type="submit" name="COMMAND_NEXT" value="Next ›">
<input type="button" name="NOTHING" value="Skip ›" onclick="window.location = 'yada-yada.asp';">
Since I don't know what language you are using on the backend, I'll give you some pseudocode:
if (input name COMMAND_PREV is set) {
} else if (input name COMMAND_SAVE is set) {
} else if (input name COMMENT_NEXT is set) {
}
To clear the whole thing use the reset_session method in a controller.
reset_session
Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668
Resets the session by clearing out all the objects stored within and initializing a new session object.
Good luck!
Simplest way for me was just using a string/template litteral:
elementName.style.cssText = `
width:80%;
margin: 2vh auto;
background-color: rgba(5,5,5,0.9);
box-shadow: 15px 15px 200px black; `;
Great option cause you can use multiple line strings making life easy.
Check out string/template litterals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
It's not a direct answer to your question but there is a much easier way to do what you want. If you are using .NET 3.5 or later, at least. It is called Enumerable.Contains
bool found = sList.Contains("ok");
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.
Literal way:
function Obj( prop ) {
return {
p : prop,
sayHello : function(){ alert(this.p); },
};
}
Prototype way:
function Obj( prop ) {
this.p = prop;
}
Obj.prototype.sayHello = function(){alert(this.p);};
Both ways allow creation of instances of Obj
like this:
var foo = new Obj( "hello" );
However, with the literal way, you carry a copy of the sayHello
method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances.
If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.
You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""
Although a bit unstandard, a possible solution is to contain the content you want to show/hide inside the <a>
so it can be reachable through CSS:
a .hidden {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
a:visited .hidden {_x000D_
visibility: visible;_x000D_
}
_x000D_
<div id="container">_x000D_
<a href="#">_x000D_
A_x000D_
<div class="hidden">hidden content</div>_x000D_
</a>_x000D_
</div>
_x000D_
It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64
are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so
is probably a 32 bit library and cannot be used for your application.
So you either need a 64 bit version of libaio or you create a 32 bit version of your application.
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
WINDOWS
(Alt+F12 or View->Tool Windows->Terminal).
Then type "move file_path/google-services.json app/"
without double quotes.
eg
move C:\Users\siva\Downloads\google-services.json app/
LINUX
scp file_path/google-services.json app/
eg:
scp '/home/developer/Desktop/google-services.json' 'app/'
In response to question edits here is how it works for Anonymous classes
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
It looks like you're using python 3.x. In python3, filter
, map
, zip
, etc return an object which is iterable, but not a list. In other words,
filter(func,data) #python 2.x
is equivalent to:
list(filter(func,data)) #python 3.x
I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.
If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:
( x for x in data if func(x) )
As opposed to:
[ x for x in data if func(x) ]
in python 2.x
querySelectorAll returns a NodeList which has its own forEach method:
document.querySelectorAll('input').forEach( input => {
// ...
});
getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:
Array.from(document.getElementsByTagName('input')).forEach( input => {
// ...
});
I've had success mutex-promise.
I agree with other answers that you might not need locking in your case. But it's not true that one never needs locking in Javascript. You need mutual exclusivity when accessing external resources that do not handle concurrency.
At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.
private void add(final List<Track> trackList) {
MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);
list = (ListView) findViewById(R.id.my_list); // TODO
list.setAdapter(bindingData);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ShowPlacePref(places, position);
AlertDialog.Builder showPlace = new AlertDialog.Builder(
Favoriler.this);
showPlace.setMessage("Remove from list?");
showPlace.setPositiveButton("DELETE", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
list.setAdapter(null); // THEN EMPTY YOUR ADAPTER
add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)
}
});
showPlace.setNegativeButton("CANCEL", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
showPlace.show();
}
});
}
If you want to have bare run
command in gdb
to execute your program with redirections and arguments, you can use set args
:
% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run
I was unable to achieve the same behaviour with --args
parameter, gdb
fiercely escapes the redirections, i.e.
% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...
This one actually redirects the input of gdb itself, not what we really want here
% gdb --args echo 1 2 <file
zsh: no such file or directory: file
You can do this using Cygwin’s setup.exe from Windows command line. Example:
cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim
For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:
wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin
Now that apt-cyg
is installed. Here are a few examples of installing some
packages:
apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates
I use the jQuery clueTip plugin for this.
Chrome "Remote device" stop working after a few months when I didn't use it.
I resolved this issue : in "development option" of my device (samsung J3) I canceled usb debugging authorization then in my computer, I execute "adb devices" in "C:\Program Files (x86)\Android\android-sdk\platform-tools" folder a prompt appears in my device asking me weather I allow my computer to debug apps or not. I click yes then chrome has detected my device
In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.
---
- hosts: webservers
remote_user: root
tasks:
- name: test connection
ping:
remote_user: yourname
See http://docs.ansible.com/playbooks_intro.html#hosts-and-users
Here is a helpful website on using appcmd to export/import a site configuration. http://www.microsoftpro.nl/2011/01/27/exporting-and-importing-sites-and-app-pools-from-iis-7-and-7-5/
If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).
library(dplyr)
library(lubridate)
# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
"2016-01-03",
"2016-01-04",
"2018-12-30",
"2018-12-31",
"2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"
# this codes provides correct year-week numbers
test <- test %>%
mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
yes = yearweek + 100,
no = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
yes = yearweek - 100,
no = yearweek)))
# print the result
print(test)
date_txt date yearweek yearweek2
1 2015-12-31 2015-12-31 201553 201553
2 2016-01-03 2016-01-03 201653 201553
3 2016-01-04 2016-01-04 201601 201601
4 2018-12-30 2018-12-30 201852 201852
5 2018-12-31 2018-12-31 201801 201901
6 2019-01-01 2019-01-01 201901 201901
Before showing the code, it's worth mentioning that IE8 supports :first-child
but not :last-child
, so in similar situations, you should use the :first-child
pseudo-class.
#menu {
list-style: none;
}
#menu li {
display: inline;
padding: 0 10px;
border-left: solid 1px black;
}
#menu li:first-child {
border-left: none;
}
_x000D_
<ul id="menu">
<li>Dogs</li>
<li>Cats</li>
<li>Lions</li>
<li>More animals</li>
</ul>
_x000D_
Similar error as well. Realized I had an .htpasswd setup for the particular host. Uncommented it from the .htaccess file and worked fine.
IPv4 uses 32 bits, in the form of:
255.255.255.255
I suppose it depends on your datatype, whether you're just storing as a string with a CHAR type or if you're using a numerical type.
IPv6 uses 128 bits. You won't have IPs longer than that unless you're including other information with them.
IPv6 is grouped into sets of 4 hex digits seperated by colons, like (from wikipedia):
2001:0db8:85a3:0000:0000:8a2e:0370:7334
You're safe storing it as a 39-character long string, should you wish to do that. There are other shorthand ways to write addresses as well though. Sets of zeros can be truncated to a single 0, or sets of zeroes can be hidden completely by a double colon.
As of PHP 7.0 type declarations allow scalar types, so these types are now available: self
, array
, callable
, bool
, float
, int
, string
. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer
or boolean
) that will be interpreted as a class name.
I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:
String cannot be resolved to a variable
With this Java code:
if (true)
String my_variable = "somevalue";
System.out.println("foobar");
You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?
Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.
If you put braces around the conditional block like this:
if (true){
String my_variable = "somevalue"; }
System.out.println("foobar");
Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.
For me, it was because I forgot to setup firewall rule on database server for my Django.
np.where(pd.isnull(df))
returns the row and column indices where the value is NaN:
In [152]: import numpy as np
In [153]: import pandas as pd
In [154]: np.where(pd.isnull(df))
Out[154]: (array([2, 5, 6, 6, 7, 7]), array([7, 7, 6, 7, 6, 7]))
In [155]: df.iloc[2,7]
Out[155]: nan
In [160]: [df.iloc[i,j] for i,j in zip(*np.where(pd.isnull(df)))]
Out[160]: [nan, nan, nan, nan, nan, nan]
Finding values which are empty strings could be done with applymap:
In [182]: np.where(df.applymap(lambda x: x == ''))
Out[182]: (array([5]), array([7]))
Note that using applymap
requires calling a Python function once for each cell of the DataFrame. That could be slow for a large DataFrame, so it would be better if you could arrange for all the blank cells to contain NaN instead so you could use pd.isnull
.
You can try this:
Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();
Keep in mind, HashMap
does not guarantee the insertion order. Use a LinkedHashMap
to keep the order intact.
Eg:
Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);
Output:
Active
33
Taking the answer above as guidance;
I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.
Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.
The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.
Thanks to the guy above for the idea!
If you don't know how to enable php_mbstring extension in windows, open your php.ini and remove the semicolon before the extension:
change this
;extension=php_mbstring.dll
to this
extension=php_mbstring.dll
after modification, you need to reset your php server.
The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.
For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php
if(isset($_GET['api_call'])){
switch($_GET['api_call']){
case 'userlogin':
//perform your userlogin task here
break;
}
}
Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.
In this case the PHP script is called a RESTful API.
You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.
=INDEX(A:A, COUNTA(A:A), 1)
taken from here
import java.util.*;
imports everything within java.util including the Date class.
import java.util.Date;
just imports the Date class.
Doing either of these could not make any difference.
Here is another CSS solution. its take less line of code.
ul li:before
{content:'\2713';
display:inline-block;
color:red;
padding:0 6px 0 0;
}
ul li{list-style-type:none;font-size:1em;}
<ul>
<li>test1</li>
<li>test</li>
</ul>
Here is the Demo link http://jsbin.com/keliguqi/1/
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
Because abstract classes have state (fields) and somethimes they need to be initialized somehow.
Php curl function (POST,GET,DELETE,PUT)
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, 1);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// curl_setopt($ch, CURLOPT_HEADER, 0);
$r = curl_exec($ch);
if (curl_error($ch)) {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
print_r('Error: ' . $err . ' Status: ' . $statusCode);
// Add error
$this->error = $err;
}
curl_close($ch);
return $r;
}
import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
n= cv2.imread(img)
cv_img.append(n)`
If you limit yourself to repeating either a 0 or a space you can do:
For spaces:
printf("%*s", count, "");
For zeros:
printf("%0*d", count, 0);
SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
+ '''' + REPLACE(ProductName, '''', '''''') + ''','
+ CONVERT(VARCHAR(12), Fk_CompanyId) + ','
+ CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;
There should be
$('.send_upload')
but not $('.upload')
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
The command yum
that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum
command to fix that.
Your code could show this error this way:
import subprocess
try:
subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.
Here's a flowchart based on this answer. See also, using script
to emulate a terminal.
If you can manipulate the common interface, you could do add in an enum and have each class return a unique value. You won't need instanceof or a visitor pattern.
For me, the logic needed to be in the written in the switch statement, not the object itself. This was my solution:
ClassA, ClassB, and ClassC implement CommonClass
Interface:
public interface CommonClass {
MyEnum getEnumType();
}
Enum:
public enum MyEnum {
ClassA(0), ClassB(1), ClassC(2);
private int value;
private MyEnum(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
Impl:
...
switch(obj.getEnumType())
{
case MyEnum.ClassA:
ClassA classA = (ClassA) obj;
break;
case MyEnum.ClassB:
ClassB classB = (ClassB) obj;
break;
case MyEnum.ClassC:
ClassC classC = (ClassC) obj;
break;
}
...
If you are on java 7, you can put string values for the enum and the switch case block will still work.
You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify()
.
Updated your line below,
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
or if you have JSON stored in some variable:
JSON.parse(JSON.stringify(yourJSONobject));
Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.
Here is another solution, which is more general than the others -- it supports splitting output (written to sys.stdout
) to any number of file-like objects. There's no requirement that __stdout__
itself is included.
import sys
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')
NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps methods of the file-like objects (e.g. write
), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.
What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to write
, flush
, os.dup2
, etc.
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar --stop
We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).
The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.
It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.
Addition to previous answer make sure that your curl installation supports https.
You can use curl --version
to get information about supported protocols.
If your curl supports https follow the previous answer.
curl --cert certificate_path:password https://www.example.com
If it does not support https, you need to install a cURL version that supports https.
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds
This query (which is similar to what bayuah posted) shows a nice summary of all tables count inside a database: (simplified version of stored procedure by Ivan Cachicatari which I highly recommend).
SELECT TABLE_NAME AS 'Table Name', TABLE_ROWS AS 'Rows' FROM information_schema.TABLES WHERE TABLES.TABLE_SCHEMA = '`YOURDBNAME`' AND TABLES.TABLE_TYPE = 'BASE TABLE';
Example:
+-----------------+---------+
| Table Name | Rows |
+-----------------+---------+
| some_table | 10278 |
| other_table | 995 |
You can do it like this:
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
Use a wild card selector *
for this purpose.
#div * { /* Narrowing, to specific elements, like input, textarea is PREFFERED */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Now, every element inside a div with id div
will have no selection.
Marc's answer got me most of the way to what I needed, but I had to go with patIndex
rather than charIndex
because sometimes characters other than spaces mark the ends of my data's words. Here I'm using '%[ /-]%'
to look for space, slash, or dash.
Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
When 0 Then LTrim (race_description)
Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation
from tbl_races
Results...
race_id race_description race_abbreviation
------- ------------------------- -----------------
1 White White
2 Black or African American Black
3 Hispanic/Latino Hispanic
Caveat: this is for a small data set (US federal race reporting categories); I don't know what would happen to performance when scaled up to huge numbers.
If you even did not get scroll after doing what is written above .....
Set the android:layout_height="250dp"
or you can say xdp
where x
can be any numerical value.
Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.
An example is included in the code below.
//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
public XOBJ<T> Obj = null;
public XOUT(T value)
{
Obj = new XOBJ<T>(value);
}
public XOUT()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(this);
}
public XREF<T> Ref()
{
return(Obj.Ref());
}
};
//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************
public class XREF<T>
{
public XOBJ<T> Obj = null;
public XREF(T value)
{
Obj = new XOBJ<T>(value);
}
public XREF()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(Obj.Out());
}
public XREF<T> Ref()
{
return(this);
}
};
//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
*
* @author jsimms
*/
/*
XOBJ is the base object that houses the value. XREF and XOUT are classes that
internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
the object to be used as XREF or XOUT parameter; This is important, because
objects of these types are interchangeable.
See Method:
XXX.Ref()
XXX.Out()
The below example shows how to use XOBJ, XREF, and XOUT;
//
// Reference parameter example
//
void AddToTotal(int a, XREF<Integer> Total)
{
Total.Obj.Value += a;
}
//
// out parameter example
//
void Add(int a, int b, XOUT<Integer> ParmOut)
{
ParmOut.Obj.Value = a+b;
}
//
// XOBJ example
//
int XObjTest()
{
XOBJ<Integer> Total = new XOBJ<>(0);
Add(1, 2, Total.Out()); // Example of using out parameter
AddToTotal(1,Total.Ref()); // Example of using ref parameter
return(Total.Value);
}
*/
public class XOBJ<T> {
public T Value;
public XOBJ() {
}
public XOBJ(T value) {
this.Value = value;
}
//
// Method: Ref()
// Purpose: returns a Reference Parameter object using the XOBJ value
//
public XREF<T> Ref()
{
XREF<T> ref = new XREF<T>();
ref.Obj = this;
return(ref);
}
//
// Method: Out()
// Purpose: returns an Out Parameter Object using the XOBJ value
//
public XOUT<T> Out()
{
XOUT<T> out = new XOUT<T>();
out.Obj = this;
return(out);
}
//
// Method get()
// Purpose: returns the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public T get() {
return Value;
}
//
// Method get()
// Purpose: sets the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public void set(T anotherValue) {
Value = anotherValue;
}
@Override
public String toString() {
return Value.toString();
}
@Override
public boolean equals(Object obj) {
return Value.equals(obj);
}
@Override
public int hashCode() {
return Value.hashCode();
}
}
Here is your code in a jsfiddle example. I have tested it and it looks fine.
http://jsfiddle.net/dimshik/9DbEP/4/
I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.
<table border="1" cellpadding="3" id="printTable">
<tbody><tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "
And you expect the answer to be
"this string have lots of space"
, you can use the following solution:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
Mat image1;
IplImage* image2=cvCloneImage(&(IplImage)image1);
Guess this will do the job.
Edit: If you face compilation errors, try this way:
cv::Mat image1;
IplImage* image2;
image2 = cvCreateImage(cvSize(image1.cols,image1.rows),8,3);
IplImage ipltemp=image1;
cvCopy(&ipltemp,image2);
Ways to show animated GIF on Android:
https://github.com/koral--/android-gif-drawable - decoder is implemented in C, so it's very efficient.
https://code.google.com/p/giffiledecoder - decoder is implemented in Java, so it's easier to work with. Still reasonably efficient, even with large files.
You'll also find many libraries based on GifDecoder class. That's also a Java-based decoder, but it works by loading the entire file into memory, so it's only applicable to small files.
There is a new option called validateStatus
in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:
const {status} = axios.get('foo.com', {validateStatus: () => true})
I accidentally set the wrong file permissions. After chmod 644 phpinfo.php
the info indeed showed up as expected.
Reinstalling Compass worked for me.. It's a magic!
sudo gem install -n /usr/local/bin compass
GoDaddy SSL CCertificate
I've experienced this while trying to connect to our backend API server with GoDaddy certificate and here is the code that I used to solve the problem.
var rootCas = require('ssl-root-cas/latest').create();
rootCas
.addFile(path.join(__dirname, '../config/ssl/gd_bundle-g2-g1.crt'))
;
// will work with all https requests will all libraries (i.e. request.js)
require('https').globalAgent.options.ca = rootCas;
PS:
Use the bundled certificate and don't forget to install the library npm install ssl-root-cas
In Objective-C, a @synchronized
block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.
Basically, @synchronized (...)
is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.
ContextLoaderListner is a Servlet listener that loads all the different configuration files (service layer configuration, persistence layer configuration etc) into single spring application context.
This helps to split spring configurations across multiple XML files.
Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definition and stores it in the ServletContext of your web application.
I faced this issue on Node 10.X version. below is my working code.
const https = require('https');
exports.handler = (event,context,callback) => {
let body='';
let jsonObject = JSON.stringify(event);
// the post options
var optionspost = {
host: 'example.com',
path: '/api/mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'blah blah',
}
};
let reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Result", body.toString());
context.succeed("Sucess")
});
res.on('error', function () {
console.log("Result Error", body.toString());
context.done(null, 'FAILURE');
});
});
reqPost.write(jsonObject);
reqPost.end();
};
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
public class StringSplit {
public static void main(String[] args) {
// TODO Auto-generated method stub
date(5, 3);
date(5, 4);
}
public static String date(int month, int week) {
LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
String Fudate = futureDate.toString();
String[] arr = Fudate.split("-", 3);
String a1 = arr[0];
String a2 = arr[1];
String a3 = arr[2];
String date = a3 + "/" + a2 + "/" + a1;
System.out.println(date);
return date;
}
}
Output:
10/03/2020
17/03/2020
As for your second problem:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line
1365, in load encoding=encoding,
errors=errors).load() EOFError
After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:
file.seek(0)
What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.
Finally, cPickle is a faster implementation of the pickle module in C. So:
In [1]: import _pickle as cPickle
In [2]: d = {"a": 1, "b": 2}
In [4]: with open(r"someobject.pickle", "wb") as output_file:
...: cPickle.dump(d, output_file)
...:
# pickle_file will be closed at this point, preventing your from accessing it any further
In [5]: with open(r"someobject.pickle", "rb") as input_file:
...: e = cPickle.load(input_file)
...:
In [7]: print e
------> print(e)
{'a': 1, 'b': 2}
use the built in float() function in a list comprehension.
A2 = [float(v.replace('"','').strip()) for v in A1]
The root cause for the question asked was the deployment/job/replicasets spec attribute strategy->type
which defines what should happen when the pod will be destroyed (either implicitly or explicitly). In my case, it was Recreate
.
As per @nomad's answer, deleting the deployment/job/replicasets is the simple fix to avoid experimenting with deadly combos before messing up the cluster as a novice user.
Try the following commands to understand the behind the scene actions before jumping into debugging :
kubectl get all -A -o name
kubectl get events -A | grep <pod-name>
on particular computer color codes can be assigned to different RGB color by editing color values in cmd window properties. Easy click color on color palete and change their rgb values.
Change your model to specify what columns you want selected:
public function user() {
return $this->belongs_to('User')->select(array('id', 'username'));
}
And don't forget to include the column you're joining on.
It's Unicode.
Just put the variable between str()
, and it will work fine.
But in case you have two lists like the following:
a = ['co32','co36']
b = [u'co32',u'co36']
If you check set(a)==set(b)
, it will come as False, but if you do as follows:
b = str(b)
set(a)==set(b)
Now, the result will be True.
Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:
column: 0 row: 0 value:1.0 column: 0 row: 1 value:4.0 column: 0 row: 2 value:7.0 column: 1 row: 0 value:2.0 column: 1 row: 1 value:5.0 column: 1 row: 2 value:8.0 column: 2 row: 0 value:3.0 column: 2 row: 1 value:6.0 column: 2 row: 2 value:9.0
I just copied and pasted your code into a Swift playground and defined two constants:
let NumColumns = 3, NumRows = 3
This is for Android, testing for IPv4
and IPv6
Note: the commonly used InetAddressUtils
is deprecated. Use new InetAddress
classes
public static Boolean isIPv4Address(String address) {
if (address.isEmpty()) {
return false;
}
try {
Object res = InetAddress.getByName(address);
return res instanceof Inet4Address || res instanceof Inet6Address;
} catch (final UnknownHostException exception) {
return false;
}
}
Well, I guess the question is, what do you mean by 'roll back'? If you can't reset
because it's public and you want to keep the commit history intact, do you mean you just want your working copy to reflect a specific commit? Use git checkout
and the commit hash.
Edit: As was pointed out in the comments, using git checkout
without specifying a branch will leave you in a "no branch" state. Use git checkout <commit> -b <branchname>
to checkout into a branch, or git checkout <commit> .
to checkout into the current branch.
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
Disclaimer: Everything below is only anecdotal and drawn directly from my personal experience. Anyone that feels up to conducting a more empirically rigorous analysis is welcome to carry it out and down vote if I'm. I am also aware that SQL is a declarative language and you're not supposed to have to consider HOW your code is processed when you write it, but, because I value my time, I do.
There are infinite logically equivalent statements, but I'll consider three(ish).
Case 1: Two Comparisons in a standard order (Evaluation order fixed)
A >= MinBound AND A <= MaxBound
Case 2: Syntactic sugar (Evaluation order is not chosen by author)
A BETWEEN MinBound AND MaxBound
Case 3: Two Comparisons in an educated order (Evaluation order chosen at write time)
A >= MinBound AND A <= MaxBound
Or
A <= MaxBound AND A >= MinBound
In my experience, Case 1 and Case 2 do not have any consistent or notable differences in performance as they are dataset ignorant.
However, Case 3 can greatly improve execution times. Specifically, if you're working with a large data set and happen to have some heuristic knowledge about whether A is more likely to be greater than the MaxBound or lesser than the MinBound you can improve execution times noticeably by using Case 3 and ordering the comparisons accordingly.
One use case I have is querying a large historical dataset with non-indexed dates for records within a specific interval. When writing the query, I will have a good idea of whether or not more data exists BEFORE the specified interval or AFTER the specified interval and can order my comparisons accordingly. I've had execution times cut by as much as half depending on the size of the dataset, the complexity of the query, and the amount of records filtered by the first comparison.
I recommend using the HTML <base>
element:
<head>
<base href="http://www.example.com/default/">
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
In this example, the stylesheet is located in http://www.example.com/default/style.css
, the script in http://www.example.com/default/script.js
. The advantage of <base>
over /
is that it is more flexible. Your whole website can be located in a subdirectory of a domain, and you can easily alter the default directory of your website.
There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.
The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.
It is not automatic. Your top function looks ok.
props.children
represents the content between the opening and the closing tags when invoking/rendering a component:
const Foo = props => (
<div>
<p>I'm {Foo.name}</p>
<p>abc is: {props.abc}</p>
<p>I have {props.children.length} children.</p>
<p>They are: {props.children}.</p>
<p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
</div>
);
const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;
invoke/call/render Foo
:
<Foo abc={123}>
<Baz />
<Bar />
</Foo>
Simply, you can test like this.
<script>
(function($) {
$(document).ready(function() {
console.log("ready....");
var i = 0;
var img;
for(i=1; i<13; i++) {
img = new Image();
img.src = 'img/' + i + '.jpg';
console.log("name : " + img.src);
img.onload = function() {
if(this.height > this.width) {
console.log(this.src + " : portrait");
}
else if(this.width > this.height) {
console.log(this.src + " : landscape");
}
else {
console.log(this.src + " : square");
}
}
}
});
}(jQuery));
</script>
In an IDE like Spyder, import the module and then run the module individually. enter image description here
I just did this -
$("#myform").bind('ajax:complete', function() {
// tasks to do
});
And things worked perfectly .
See this api documentation for more specific details.
declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.
CREATE PROCEDURE SP1 AS
EXEC SP2
PRINT 'Done'
If you missed to check the "generate web.xml" option when creating a new project, no worries If it is a Dynamic Web Project in your project right click on "Deployment Descriptor:...." and Click on "Generate Deployment Descriptor Stub" this will create a minimal /webapp/WEB-INF/web.xml.
Use the same file.sh
#!/bin/bash
echo $1
Build the image using the existing Dockerfile:
docker build -t test .
Run the image with arguments abc
or xyz
or something else.
docker run -ti --rm test /file.sh abc
docker run -ti --rm test /file.sh xyz
I had this issue and I solved it by creating a directory in mysite folder to hold my db.sqlite3 file. so I did /home/user/src/mysite/database/db.sqlite3
. In my django setting file I change my
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': "/home/user/src/mysite/database/db.sqlite3" ,
}}
I did this to make Django aware that I am storing my database in a sub directory of the base directory, which mysite in my case. Now you need to grant the permission to apache to be able read write the database.
chown user:www-data database/db.sqlite3
chown user:www-data database
chmod 755 database
chmod 755 database/db.sqlite3
This solved my problem. Here is a list of the different permissions. You can use choose the one that fits you but avoid 777 and 666
-rw------- (600) -- Only the user has read and write permissions.
-rw-r--r-- (644) -- Only user has read and write permissions; the group and others can read only.
-rwx------ (700) -- Only the user has read, write and execute permissions.
-rwxr-xr-x (755) -- The user has read, write and execute permissions; the group and others can only read and execute.
-rwx--x--x (711) -- The user has read, write and execute permissions; the group and others can only execute.
-rw-rw-rw- (666) -- Everyone can read and write to the file. Bad idea.
-rwxrwxrwx (777) -- Everyone can read, write and execute. Another bad idea.
Here are a couple common settings for directories:
drwx------ (700) -- Only the user can read, write in this directory.
drwxr-xr-x (755) -- Everyone can read the directory, but its contents can only be changed by the user.
here is a link to an article to [learn more][1]
[1]: http://ftp.kh.edu.tw/Linux/Redhat/en_6.2/doc/gsg/s1-navigating-chmodnum.htm#:~:text=%2Drwxr%2Dxr%2Dx%20(,and%20others%20can%20only%20execute.
Assuming that "part within rectangle don't have content color" means that you want different fills within the rectangle; you need to draw a rectangle within your rectangle then with stroke width 0 and the desired fill colour(s).
For example:
DrawView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(30, 30, 80, 80, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(33, 60, 77, 77, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(33, 33, 77, 60, paint );
}
}
The activity to start it:
StartDraw.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class StartDraw extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
...will turn out this way:
Your script, when in your home directory will not be found when the shell looks at the $PATH
environment variable to find your script.
The ./
says 'look in the current directory for my script rather than looking at all the directories specified in $PATH
'.
As said before, VBA does not support Multithreading.
But you don't need to use C# or vbScript to start other VBA worker threads.
I use VBA to create VBA worker threads.
First copy the makro workbook for every thread you want to start.
Then you can start new Excel Instances (running in another Thread) simply by creating an instance of Excel.Application (to avoid errors i have to set the new application to visible).
To actually run some task in another thread i can then start a makro in the other application with parameters form the master workbook.
To return to the master workbook thread without waiting i simply use Application.OnTime in the worker thread (where i need it).
As semaphore i simply use a collection that is shared with all threads. For callbacks pass the master workbook to the worker thread. There the runMakroInOtherInstance Function can be reused to start a callback.
'Create new thread and return reference to workbook of worker thread
Public Function openNewInstance(ByVal fileName As String, Optional ByVal openVisible As Boolean = True) As Workbook
Dim newApp As New Excel.Application
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & fileName
If openVisible Then newApp.Visible = True
Set openNewInstance = newApp.Workbooks.Open(ThisWorkbook.Path & "\" & fileName, False, False)
End Function
'Start macro in other instance and wait for return (OnTime used in target macro)
Public Sub runMakroInOtherInstance(ByRef otherWkb As Workbook, ByVal strMakro As String, ParamArray var() As Variant)
Dim makroName As String
makroName = "'" & otherWkb.Name & "'!" & strMakro
Select Case UBound(var)
Case -1:
otherWkb.Application.Run makroName
Case 0:
otherWkb.Application.Run makroName, var(0)
Case 1:
otherWkb.Application.Run makroName, var(0), var(1)
Case 2:
otherWkb.Application.Run makroName, var(0), var(1), var(2)
Case 3:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3)
Case 4:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3), var(4)
Case 5:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3), var(4), var(5)
End Select
End Sub
Public Sub SYNCH_OR_WAIT()
On Error Resume Next
While masterBlocked.Count > 0
DoEvents
Wend
masterBlocked.Add "BLOCKED", ThisWorkbook.FullName
End Sub
Public Sub SYNCH_RELEASE()
On Error Resume Next
masterBlocked.Remove ThisWorkbook.FullName
End Sub
Sub runTaskParallel()
...
Dim controllerWkb As Workbook
Set controllerWkb = openNewInstance("controller.xlsm")
runMakroInOtherInstance controllerWkb, "CONTROLLER_LIST_FILES", ThisWorkbook, rootFold, masterBlocked
...
End Sub
Just to add. If you right-click on an eclipse project and select Properties
, select the Java Build Path
link on the left. Then select the Source
Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src
folder is the classpath folder.
I have used Mockito.verify in this way
@UnitTest
public class JUnitServiceTest
{
@Mock
private MyCustomService myCustomService;
@Test
public void testVerifyMethod()
{
Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); // no other method called except this
}
}
An alternative that worked for me is to tell Maven to use http: instead of https: when using Maven Central by adding the following to settings.xml:
<settings>
.
.
.
<mirrors>
<mirror>
<id>central-no-ssl</id>
<name>Central without ssl</name>
<url>http://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
.
.
.
</settings>
Your mileage may vary of course.
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity
As suggested by user7860670, right-click on the project, select properties, navigate to C/C++ -> Preprocessor and add _USE_MATH_DEFINES
to the Preprocessor Definitions.
That's what worked for me.
Exception object also contains original response e.response
, that could be useful if need to see error body in response from the server. For example:
try:
r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
DAO provides abstraction on database/data files or any other persistence mechanism so that, persistence layer could be manipulated without knowing its implementation details.
Whereas in Repository classes, multiple DAO classes can be used inside a single Repository method to get an operation done from "app perspective". So, instead of using multiple DAO at Domain layer, use repository to get it done. Repository is a layer which may contain some application logic like: If data is available in in-memory cache then fetch it from cache otherwise, fetch data from network and store it in in-memory cache for next time retrieval.
Try Ctrl+Alt+U
Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S
The header <math.h>
is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath>
is the C++ version of that header. It defines essentially the same stuff in namespace std
. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h>
doesn't exist.
Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std
. Or there's some macro magic for parsing the same header with or without namespace std
wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath>
be a one-liner including some other header with a .h
extension. Or some would map all includes matching <cblah>
to <blah.h>
(which, through macro magic, becomes the C++ header when __cplusplus
is defined, and otherwise becomes the C header) or <cblah.h>
or whatever.
That's the reason why on some platforms including things like <cmath.h>
, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.
I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath>
maps to <cmath.h>
with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.
Note, however, that this code still ought not to compile:
#include <cmath>
double f(double d)
{
return abs(d);
}
There shouldn't be an abs()
in the global namespace (it's std::abs()
). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.