You can checkout remote branch /n git fetch && git checkout remotebranch
Note that one difference between git remote --prune
and git fetch --prune
is being fixed, with commit 10a6cc8, by Tom Miller (tmiller
) (for git 1.9/2.0, Q1 2014):
When we have a remote-tracking branch named "
frotz/nitfol
" from a previous fetch, and the upstream now has a branch named "**frotz"**,fetch
would fail to remove "frotz/nitfol
" with a "git fetch --prune
" from the upstream.
git would inform the user to use "git remote prune
" to fix the problem.
So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune
was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune
was failing.
Not anymore:
Change the way "
fetch --prune
" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.
You have set the upstream of that branch
(see:
--set-upstream-to
all the time?"git branch -f --track my_local_branch origin/my_remote_branch # OR (if my_local_branch is currently checked out): $ git branch --set-upstream-to my_local_branch origin/my_remote_branch
(git branch -f --track
won't work if the branch is checked out: use the second command git branch --set-upstream-to
instead, or you would get "fatal: Cannot force update the current branch.
")
That means your branch is already configured with:
branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch
Git already has all the necessary information.
In that case:
# if you weren't already on my_local_branch branch:
git checkout my_local_branch
# then:
git pull
is enough.
If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch
', then a simple git push -u origin my_local_branch:my_remote_branch
would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull
or git push
would, again, have been enough.
If you use BitBucket,
you can use import Repository, this will import all git history ( all the branches and commits)
I had a similar problem. None of the answers helped. In my case, I had two removed remote repositories showing up permanently.
My last idea was to remove all references to it by hand.
Let's say the repository is called “Repo”. I did:
find .git -name Repo
So, I deleted the corresponding files and directories from the .git folder (this folder could be found in your Rails app or on your computer https://stackoverflow.com/a/19538763/6638513).
Then I did:
grep Repo -r .git
This found some text files in which I removed the corresponding lines. Now, everything seems to be fine.
Usually, you should leave this job to git.
After fetching a zillion times still added remotes didn't show up, although the blobs were in the pool. Turns out the --tags option shouldn't be given to git remote add
for whatever reason. You can manually remove it from the .git/config to make git fetch create the refs.
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
Other guys and gals give the solutions, but maybe I can tell you why.
git checkout test which does nothing
Does nothing
doesn't equal doesn't work
, so I guess when you type 'git checkout test' in your terminal and press enter key, no message appears and no error occurs. Am I right?
If the answer is 'yes', I can tell you the cause.
The cause is that there is a file (or folder) named 'test' in your work tree.
When git checkout xxx
parsed,
xxx
as a branch name at first, but there isn't any branch named test.xxx
is a path, and fortunately (or unfortunately), there is a file named test. So git checkout xxx
means discard any modification in xxx
file.xxx
either, then Git will try to create the xxx
according to some rules. One of the rules is create a branch named xxx
if remotes/origin/xxx
exists.I would use:
git branch -av
This command not only shows you the list of all branches, including remote branches starting with /remote
, but it also provides you the *
feedback on what you updated and the last commit comments.
use below method
let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)
println(output)
I wanted to use Realm for Android and that required Retrolambda. Problem is Retrolambda conflicts with Jack.
So I removed my Jack options config from my gradle shown in original answer below and made the following changes:
// ---------------------------------------------
// Project build.gradle file
// ---------------------------------------------
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'me.tatarka:gradle-retrolambda:3.6.1'
classpath "io.realm:realm-gradle-plugin:3.1.4"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and
// ---------------------------------------------
// Module build.gradle file
// ---------------------------------------------
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'realm-android'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
...
If you made those changes above and you still get the following error:
Execution failed for task ':app:compileDebugJavaWithJavac'.
com.sun.tools.javac.util.Context.put(Ljava/lang/Class;Ljava/lang/Object;)V
Try removing the following file:
/Library/Java/Extensions/tools.jar
Then:
All the changes fixed it for me.
Note:
I am not sure what tools.jar does or whether it's important. Like other uses in this Stackoverflow question:
Can't build Java project on OSX yosemite
We were unfortunate enough to have to use AUSKey (some ancient dinosaur Java authentication key system used by Australian Government to authenticate our computer before we can log into Australian business portal website).
My speculation is tools.jar
might have been a JAR file for/by AUSKey.
If you're worried, instead of deleting this file, you can make a backup of the whole folder and save it somewhere just in case you can't login to Australian Business Portal again.
Hope that helps :D
I came across this problem today (27/06/2016).
I downloaded Android Studio 2.2 and updated JDK to 1.8.
In addition to the above answers of pointing to the correct JDK path, I had to additionally specify the JDK version in my build.gradle(Module: app)
file:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
The resulting file looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.mycompany.appname"
minSdkVersion 17
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
}
Please also notice if you came across an error about Java 8 language features requires Jack enabled
, you need to add the following to your gradle file (as shown above):
jackOptions {
enabled true
}
After doing that, I finally got my new project app running on my phone.
What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -
$handle = opendir("scripts/");
while (($file = readdir($handle))!== false) {
echo '<script type="text/javascript" src="' . $file . '"></script>';
}
closedir($handle);
simplest way to center your div element is to use this class with following properties.
.light {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
Use from
to directly convert a previously created Promise to an Observable.
import { from } from 'rxjs';
// getPromise() is called once, the promise is passed to the Observable
const observable$ = from(getPromise());
observable$
will be a hot Observable that effectively replays the Promises value to Subscribers.
It's a hot Observable because the producer (in this case the Promise) is created outside of the Observable. Multiple subscribers will share the same Promise. If the inner Promise has been resolved a new subscriber to the Observable will get its value immediately.
Use defer
with a Promise factory function as input to defer the creation and conversion of a Promise to an Observable.
import { defer } from 'rxjs';
// getPromise() is called every time someone subscribes to the observable$
const observable$ = defer(() => getPromise());
observable$
will be a cold Observable.
It's a cold Observable because the producer (the Promise) is created inside of the Observable. Each subscriber will create a new Promise by calling the given Promise factory function.
This allows you to create an observable$
without creating and thus executing a Promise right away and without sharing this Promise with multiple subscribers.
Each subscriber to observable$
effectively calls from(promiseFactory()).subscribe(subscriber)
. So each subscriber creates and converts its own new Promise to a new Observable and attaches itself to this new Observable.
Most RxJS operators that combine (e.g. merge
, concat
, forkJoin
, combineLatest
...) or transform observables (e.g. switchMap
, mergeMap
, concatMap
, catchError
...) accept promises directly. If you're using one of them anyway you don't have to use from
to wrap a promise first (but to create a cold observable you still might have to use defer
).
// Execute two promises simultaneously
forkJoin(getPromise(1), getPromise(2)).pipe(
switchMap(([v1, v2]) => v1.getPromise(v2)) // map to nested Promise
)
Check the documentation or implementation to see if the operator you're using accepts ObservableInput
or SubscribableOrPromise
.
type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
// Note the PromiseLike ----------------------------------------------------v
type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>;
The difference between from
and defer
in an example: https://stackblitz.com/edit/rxjs-6rb7vf
const getPromise = val => new Promise(resolve => {
console.log('Promise created for', val);
setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000);
});
// the execution of getPromise('FROM') starts here, when you create the promise inside from
const fromPromise$ = from(getPromise('FROM'));
const deferPromise$ = defer(() => getPromise('DEFER'));
fromPromise$.subscribe(console.log);
// the execution of getPromise('DEFER') starts here, when you subscribe to deferPromise$
deferPromise$.subscribe(console.log);
Hey You can Use this insted
<iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=%C4%B0ikaneir+(Mumma's%20Bakery)&ie=UTF8&t=&z=14&iwloc=B&output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>
$(document).ready(function () {
$('input:radio[name=bedStatus]:checked').change(function () {
if ($("input:radio[name='bedStatus']:checked").val() == 'allot') {
alert("Allot Thai Gayo Bhai");
}
if ($("input:radio[name='bedStatus']:checked").val() == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
There is only one object that is used for protypal chaining. This object obviously has a name and a value: __proto__
is its name, and prototype
is its value. That's all.
to make it even easier to grasp, look at the diagram on the top of this post (Diagram by dmitry soshnikov), you'll never find __proto__
points to something else other than prototype
as its value.
The gist is this: __proto__
is the name that references the prototypal object, and prototype
is the actual prototypal object.
It's like saying:
let x = {name: 'john'};
x
is the object name (pointer), and {name: 'john'}
is the actual object (data value).
NOTE: this just a massively simplified hint on how they are related on a high level.
Update: Here is a simple concrete javascript example for better illustration:
let x = new String("testing") // Or any other javascript object you want to create
Object.getPrototypeOf(x) === x.__proto__; // true
This means that when Object.getPrototypeOf(x)
gets us the actual value of x
(which is its prototype), is exactly what the __proto__
of x
is pointing to. Therefore __proto__
is indeed pointing to the prototype of x
. Thus __proto__
references x
(pointer of x
), and prototype
is the value of x
(its prototype).
I hope it's a bit clear now.
When I saw the same error, I tried to resolve it like:
__block CGFloat docHeight = 0.0;
[self evaluateJavaScript:@"document.height" completionHandler:^(id height, NSError *error) {
//height
NSLog(@"=========>document.height:@%@",height);
docHeight = [height floatValue];
}];
and its working fine
Just add "__block" before Variable.
Switch to some other branch and delete Test_Branch
, as follows:
$ git checkout master
$ git branch -d Test_Branch
If above command gives you error - The branch 'Test_Branch' is not fully merged. If you are sure you want to delete it
and still you want to delete it, then you can force delete it using -D
instead of -d
, as:
$ git branch -D Test_Branch
To delete Test_Branch
from remote as well, execute:
git push origin --delete Test_Branch
After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
You can change it to difference between hours also.
Enjoy!
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date];
&& NSTimeInterval distance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease]];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
currentdate = [dateFormatter dateFromString:stringDate];
Here is a function that generates Python code from a decision tree by converting the output of export_text
:
import string
from sklearn.tree import export_text
def export_py_code(tree, feature_names, max_depth=100, spacing=4):
if spacing < 2:
raise ValueError('spacing must be > 1')
# Clean up feature names (for correctness)
nums = string.digits
alnums = string.ascii_letters + nums
clean = lambda s: ''.join(c if c in alnums else '_' for c in s)
features = [clean(x) for x in feature_names]
features = ['_'+x if x[0] in nums else x for x in features if x]
if len(set(features)) != len(feature_names):
raise ValueError('invalid feature names')
# First: export tree to text
res = export_text(tree, feature_names=features,
max_depth=max_depth,
decimals=6,
spacing=spacing-1)
# Second: generate Python code from the text
skip, dash = ' '*spacing, '-'*(spacing-1)
code = 'def decision_tree({}):\n'.format(', '.join(features))
for line in repr(tree).split('\n'):
code += skip + "# " + line + '\n'
for line in res.split('\n'):
line = line.rstrip().replace('|',' ')
if '<' in line or '>' in line:
line, val = line.rsplit(maxsplit=1)
line = line.replace(' ' + dash, 'if')
line = '{} {:g}:'.format(line, float(val))
else:
line = line.replace(' {} class:'.format(dash), 'return')
code += skip + line + '\n'
return code
Sample usage:
res = export_py_code(tree, feature_names=names, spacing=4)
print (res)
Sample output:
def decision_tree(f1, f2, f3):
# DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,
# max_features=None, max_leaf_nodes=None,
# min_impurity_decrease=0.0, min_impurity_split=None,
# min_samples_leaf=1, min_samples_split=2,
# min_weight_fraction_leaf=0.0, presort=False,
# random_state=42, splitter='best')
if f1 <= 12.5:
if f2 <= 17.5:
if f1 <= 10.5:
return 2
if f1 > 10.5:
return 3
if f2 > 17.5:
if f2 <= 22.5:
return 1
if f2 > 22.5:
return 1
if f1 > 12.5:
if f1 <= 17.5:
if f3 <= 23.5:
return 2
if f3 > 23.5:
return 3
if f1 > 17.5:
if f1 <= 25:
return 1
if f1 > 25:
return 2
The above example is generated with names = ['f'+str(j+1) for j in range(NUM_FEATURES)]
.
One handy feature is that it can generate smaller file size with reduced spacing. Just set spacing=2
.
You can use the Mock.call_args_list
attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count
attribute should give you full control.
If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using intersection()
:
a = [1,2,3,4,5]
b = [1,3,5,6]
set(a).intersection(b)
I was having similar issue and adding
sessionFactory.setAnnotatedClasses(User.class);
this line helped but before that I was having
sessionFactory.setPackagesToScan(new String[] { "com.rg.spring.model" });
I am not sure why that one is not working.User class is under com.rg.spring.model Please let me know how to get it working via packagesToScan method.
Just like normal background-color: #f0f
You just need a way to target it, eg: <option id="myPinkOption">blah</option>
You can have multiple identical hash keys; but only if you have a range key that varies. Think of it like file formats; you can have 2 files with the same name in the same folder as long as their format is different. If their format is the same, their name must be different. The same concept applies to DynamoDB's hash/range keys; just think of the hash as the name and the range as the format.
Also, I don't recall if they had these at the time of the OP (I don't believe they did), but they now offer Local Secondary Indexes.
My understanding of these is that it should now allow you to perform the desired queries without having to do a full scan. The downside is that these indexes have to be specified at table creation, and also (I believe) cannot be blank when creating an item. In addition, they require additional throughput (though typically not as much as a scan) and storage, so it's not a perfect solution, but a viable alternative, for some.
I do still recommend Mike Brant's answer as the preferred method of using DynamoDB, though; and use that method myself. In my case, I just have a central table with only a hash key as my ID, then secondary tables that have a hash and range that can be queried, then the item points the code to the central table's "item of interest", directly.
Additional data regarding the secondary indexes can be found in Amazon's DynamoDB documentation here for those interested.
Anyway, hopefully this will help anyone else that happens upon this thread.
list.Where(m => m.application == "applicationName" &&
m.users.Any(u => u.surname=="surname"));
if you want to filter users as TimSchmelter commented, you can use
list.Where(m => m.application == "applicationName")
.Select(m => new Model
{
application = m.application,
users = m.users.Where(u => u.surname=="surname").ToList()
});
The solution of Kris is really nice, but I prefer a mix of factory and fluent style:
<?php
class Student
{
protected $firstName;
protected $lastName;
// etc.
/**
* Constructor
*/
public function __construct() {
// allocate your stuff
}
/**
* Static constructor / factory
*/
public static function create() {
return new self();
}
/**
* FirstName setter - fluent style
*/
public function setFirstName($firstName) {
$this->firstName = $firstName;
return $this;
}
/**
* LastName setter - fluent style
*/
public function setLastName($lastName) {
$this->lastName = $lastName;
return $this;
}
}
// create instance
$student= Student::create()->setFirstName("John")->setLastName("Doe");
// see result
var_dump($student);
?>
There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file
in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave
gem .
I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.
DA is right. In your own fiddle, the iframe is indeed responsive. You can verify that in firebug by checking iframe box-sizing. But some elements inside that iframe is not responsive, so they "stick out" when window size is small. For example, div#products-post-wrapper
's width is 8800px.
In my own work, I've realized that every time I've wanted something like variable-length automatic arrays or alloca(), I didn't really care that the memory was physically located on the cpu stack, just that it came from some stack allocator that didn't incur slow trips to the general heap. So I have a per-thread object that owns some memory from which it can push/pop variable sized buffers. On some platforms I allow this to grow via mmu. Other platforms have a fixed size (usually accompanied by a fixed size cpu stack as well because no mmu). One platform I work with (a handheld game console) has precious little cpu stack anyway because it resides in scarce, fast memory.
I'm not saying that pushing variable-sized buffers onto the cpu stack is never needed. Honestly I was surprised back when I discovered this wasn't standard, as it certainly seems like the concept fits into the language well enough. For me though, the requirements "variable size" and "must be physically located on the cpu stack" have never come up together. It's been about speed, so I made my own sort of "parallel stack for data buffers".
You can use the user-agent string to detect this.
var useragent = navigator.userAgent.toLowerCase();
if( useragent.search("iphone") )
; // iphone
else if( useragent.search("ipod") )
; // ipod
else if( useragent.search("android") )
; // android
etc
You can find a list of useragent strings here http://www.useragentstring.com/pages/useragentstring.php
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
Just clean and retry solved for me.
I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child
parameters will only make it more complicated. As for the background color I'd just set that to a variable.
Here goes what I came up with before I realized trying to be too clever might be a bad thing.
#romtest {
$bg: #e5e5e5;
.detailed {
th {
&:nth-child(-2n+6) {
background-color: $bg;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
background-color: $bg;
}
&.last {
&:nth-child(-2n+4){
background-color: $bg;
}
}
}
}
}
and here is a quick demo: http://codepen.io/anon/pen/BEImD
----EDIT----
Here's another approach to avoid retyping background-color
:
#romtest {
%highlight {
background-color: #e5e5e5;
}
.detailed {
th {
&:nth-child(-2n+6) {
@extend %highlight;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
@extend %highlight;
}
&.last {
&:nth-child(-2n+4){
@extend %highlight;
}
}
}
}
}
Updated June 2020
It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.
Before December 2019:
It is now "possible":
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887
This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime
$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
return filemtime($b) - filemtime($a);
});
The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do
usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));
If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort
instead.
With the resulting array, you would then iterate over the files like this:
foreach($files as $file){
printf('<tr><td><input type="checkbox" name="box[]"></td>
<td><a href="%1$s" target="_blank">%1$s</a></td>
<td>%2$s</td></tr>',
$file, // or basename($file) for just the filename w\out path
date('F d Y, H:i:s', filemtime($file)));
}
Note that because you already called filemtime
when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.
in django.utils.module_loading.module_has_submodule
import sys
import os
import imp
def module_has_submodule(package, module_name):
"""
check module in package
django.utils.module_loading.module_has_submodule
"""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
try:
package_path = package.__path__ # No __path__, then not a package.
except AttributeError:
# Since the remainder of this function assumes that we're dealing with
# a package (module with a __path__), so if it's not, then bail here.
return False
for finder in sys.meta_path:
if finder.find_module(name, package_path):
return True
for entry in package_path:
try:
# Try the cached finder.
finder = sys.path_importer_cache[entry]
if finder is None:
# Implicit import machinery should be used.
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
continue
# Else see if the finder knows of a loader.
elif finder.find_module(name):
return True
else:
continue
except KeyError:
# No cached finder, so try and make one.
for hook in sys.path_hooks:
try:
finder = hook(entry)
# XXX Could cache in sys.path_importer_cache
if finder.find_module(name):
return True
else:
# Once a finder is found, stop the search.
break
except ImportError:
# Continue the search for a finder.
continue
else:
# No finder found.
# Try the implicit import machinery if searching a directory.
if os.path.isdir(entry):
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
pass
# XXX Could insert None or NullImporter
else:
# Exhausted the search, so the module cannot be found.
return False
You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog
class.
Adding using WinForms = System.Windows.Forms;
will be helpful.
if it's not working for you then replace android:background with android:src
android:src will play the major trick
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/bg_hc" />
it's working fine like a charm
I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:
num1 = 20 if someBoolValue else num1
If you exclude else num1
, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.
As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:
if someBoolValue: num1=20
I'm not a big fan of the num1 = someBoolValue and 20 or num1
for the exact same reason. I have to actually think twice on what that line is doing.
The best way to actually achieve what you want to do is the original version:
if someBoolValue:
num1 = 20
The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.
Also, as a side note, num1 = 20 if someBoolValue
is valid Ruby code, because Ruby works a bit differently.
You can try this:
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: close");
Hopefully it will help prevent Cache, if any!
Basically you need to download the IEDriverServer.exe from Selenium HQ website without executing anything just remmeber the location where you want it and then put the code on Eclipse like this
System.setProperty("webdriver.ie.driver", "C:\\Users\\juan.torres\\Desktop\\QA stuff\\IEDriverServer_Win32_2.32.3\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver();
driver.navigate().to("http://www.youtube.com/");
for the path use double slash //
ok have fun !!
This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ...
as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.
$lastCell = 11
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7
$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row
$phoneData = for ($i=1; $i -le $endRow; $i++)
{
$pModel = $sh.Cells.Item($startRow,$model).Value2
$pMAC = $sh.Cells.Item($startRow,$mac).Value2
$nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
$extension = $sh.Cells.Item($startRow,$ext).Value2
New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
$startRow++
}
I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.
Also you can keep clients refferences. But this makes your memmory busy.
Create an empty object and set your clients into it.
const myClientList = {};
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
myClientList[socket.id] = socket;
});
socket.on("disconnect", (socket) => {
delete myClientList[socket.id];
});
then call your specific client by id from the object
myClientList[specificId].emit("blabla","somedata");
You need make your Contact classes implement Comparable, and then implement the compareTo(Contact)
method. That way, the Collections.sort will be able to sort them for you. Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'
For example, if you wanted to sort by name (A to Z), your class would look like this:
public class Contact implements Comparable<Contact> {
private String name;
// all the other attributes and methods
public compareTo(Contact other) {
return this.name.compareTo(other.name);
}
}
If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.
For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:
.row {
zoom: 1;
margin-left: -20px;
}
.row > [class*="span"] {
display: inline;
float: left;
margin-left: 20px;
}
.span4 {
width: 220px;
}
To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).
For example, to allow for the left border on the sidebar, they added this CSS in the <head>
after the the main <link href="../bootstrap.css" rel="stylesheet">
.
.content .span4 {
margin-left: 0;
padding-left: 19px;
border-left: 1px solid #eee;
}
You'll see they've reduced padding-left
by 1px
to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.
I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.
Just thought I'd share my hacky solution with anyone who's discovering this problem now with embedded links within a string. It attempts to inline the links by rendering it dynamically with what ever string is fed into it.
Please feel free to tweak it to your needs. It's working for our purposes as such:
This is an example of how https://google.com would appear.
View it on Gist:
https://gist.github.com/Friendly-Robot/b4fa8501238b1118caaa908b08eb49e2
import React from 'react';
import { Linking, Text } from 'react-native';
export default function renderHyperlinkedText(string, baseStyles = {}, linkStyles = {}, openLink) {
if (typeof string !== 'string') return null;
const httpRegex = /http/g;
const wwwRegex = /www/g;
const comRegex = /.com/g;
const httpType = httpRegex.test(string);
const wwwType = wwwRegex.test(string);
const comIndices = getMatchedIndices(comRegex, string);
if ((httpType || wwwType) && comIndices.length) {
// Reset these regex indices because `comRegex` throws it off at its completion.
httpRegex.lastIndex = 0;
wwwRegex.lastIndex = 0;
const httpIndices = httpType ?
getMatchedIndices(httpRegex, string) : getMatchedIndices(wwwRegex, string);
if (httpIndices.length === comIndices.length) {
const result = [];
let noLinkString = string.substring(0, httpIndices[0] || string.length);
result.push(<Text key={noLinkString} style={baseStyles}>{ noLinkString }</Text>);
for (let i = 0; i < httpIndices.length; i += 1) {
const linkString = string.substring(httpIndices[i], comIndices[i] + 4);
result.push(
<Text
key={linkString}
style={[baseStyles, linkStyles]}
onPress={openLink ? () => openLink(linkString) : () => Linking.openURL(linkString)}
>
{ linkString }
</Text>
);
noLinkString = string.substring(comIndices[i] + 4, httpIndices[i + 1] || string.length);
if (noLinkString) {
result.push(
<Text key={noLinkString} style={baseStyles}>
{ noLinkString }
</Text>
);
}
}
// Make sure the parent `<View>` container has a style of `flexWrap: 'wrap'`
return result;
}
}
return <Text style={baseStyles}>{ string }</Text>;
}
function getMatchedIndices(regex, text) {
const result = [];
let match;
do {
match = regex.exec(text);
if (match) result.push(match.index);
} while (match);
return result;
}
To sum it up,in object oriented programming, everything is modeled into classes and objects. Classes contain properties and methods. Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.
In addition to all the other correct answers, since Rails.root
is a Pathname
object, this won't work:
Rails.root + '/app/assets/...'
You could use something like join
Rails.root.join('app', 'assets')
If you want a string use this:
Rails.root.join('app', 'assets').to_s
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
At least for the GitHub Flavoured Markdown, you can give the illusion by making all the non-header row entries bold with the regular __
or **
formatting:
|Regular | text | in header | turns bold |
|-|-|-|-|
| __So__ | __bold__ | __all__ | __table entries__ |
| __and__ | __it looks__ | __like a__ | __"headerless table"__ |
Hosting a nodejs site through apache can be organized with apache proxy module.
It's better to start nodejs server on localhost with default port 1337
Enable proxy with a command:
sudo a2enmod proxy proxy_http
Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.
Configure /etc/apche2/sites-availables with
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName site.com
ServerAlias www.site.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass http://localhost:1337/
ProxyPassReverse http://localhost:1337/
</Location>
</VirtualHost>
and restart apache2 service.
if you have a certain output type then do something like this
cat /path/to/files/*.txt >> finalout.txt
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
Solution: In order to increase your buffer history on iterm bash terminal you've got two options:
Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)
Option 1. select the checkbox Unlimited scrollback
Option 2. type the selected Scrollback lines
numbers you'd like your terminal buffer to cache (See image below)
In order to not have the Cannot recover key
exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.
Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy
. Setting that to unlimited
with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty()
or via the java.security
file. The java.security
file could also be appended to by adding -Djava.security.properties=my_security.properties
to the command to start the program as detailed here.
Since JDK 8u161 unlimited cryptography is enabled by default.
You can use the base64
CLI tool to generate the base64 encoded version of your username + password like this:
$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz
-or-
$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==
Base64 is reversible so you can also decode it to confirm like this:
$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass
-or-
$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass
NOTE: username = joeuser, password = secretpass
You can put this together into curl
like this:
$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com
Most will likely agree that if you're going to bother doing this, then you might as well just use curl
's -u
option.
$ curl --help |grep -- "--user " -u, --user USER[:PASSWORD] Server user and password
For example:
$ curl -u someuser:secretpass http://example.com
But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.
For example, here I'm using the LastPass' CLI tool, lpass
, to retrieve my credentials:
$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
http://example.com
There's an even safer way to hand your credentials off to curl
though. This method makes use of the -K
switch.
$ curl -X GET -K \
<(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
http://example.com
When used, your details remain hidden, since they're passed to curl
via a temporary file descriptor, for example:
+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%
NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.
This method is dynamically creating a file with the contents user = "<username>:<password>"
and giving that to curl
.
The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.
When the user agent wants to send authentication credentials to the server, it may use the Authorization field.
The Authorization field is constructed as follows:
- The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
- The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
- The resulting string is encoded using a variant of Base64.
- The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.
For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
Source: Basic access authentication
You have two options here, you can make it open in a new window/tab with JS:
<td onClick={()=> window.open("someLink", "_blank")}>text</td>
But a better option is to use a regular link but style it as a table cell:
<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
Here is a long (easy to understand) version but takes care of leap years.
cheers, JK
def last_day_month(year, month):
leap_year_flag = 0
end_dates = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
# Checking for regular leap year
if year % 4 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
# Checking for century leap year
if year % 100 == 0:
if year % 400 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
else:
pass
# return end date of the year-month
if leap_year_flag == 1 and month == 2:
return 29
elif leap_year_flag == 1 and month != 2:
return end_dates[month]
else:
return end_dates[month]
zip
will transpose the list, after that you can concatenate the outputs.
In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]
I saw an interesting post from Ikraider here that solved my issue : https://github.com/docker/docker/issues/22599
Website instructions are wrong, here is what works in 16.04:
curl -s https://yum.dockerproject.org/gpg | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-engine=1.13.0-0~ubuntu-xenial
This is a proposal which uses the key if given, or all properties of the object for searching a value.
function filter(array, value, key) {_x000D_
return array.filter(key_x000D_
? a => a[key] === value_x000D_
: a => Object.keys(a).some(k => a[k] === value)_x000D_
);_x000D_
}_x000D_
_x000D_
var a = [{ name: 'xyz', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];_x000D_
_x000D_
_x000D_
console.log(filter(a, 'x'));_x000D_
console.log(filter(a, 'x', 'name'));
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
You can specify also imagePullPolicy: Never
in the container's spec:
containers:
- name: nginx
imagePullPolicy: Never
image: custom-nginx
ports:
- containerPort: 80
var svg; // if you have variable declared and not assigned value.
// then you make a mistake by appending elements to that before creating element
svg.appendChild(document.createElement("g"));
// at some point you assign to svg
svg = document.createElementNS('http://www.w3.org/2000/svg', "svg")
// then you put it in DOM
document.getElementById("myDiv").appendChild(svg)
// it wont render unless you manually change myDiv DOM with DevTools
// to fix assign before you append
var svg = createElement("svg", [
["version", "1.2"],
["xmlns:xlink", "http://www.w3.org/1999/xlink"],
["aria-labelledby", "title"],
["role", "img"],
["class", "graph"]
]);
function createElement(tag, attributeArr) {
// .createElementNS NS is must! Does not draw without
let elem = document.createElementNS('http://www.w3.org/2000/svg', tag);
attributeArr.forEach(element => elem.setAttribute(element[0], element[1]));
return elem;
}
// extra: <circle> for example requires attributes to render. Check if missing.
Add your multiple columns with comma separations:
UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'
However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?
Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.
this is most easy way for doing that
//substr(string,start,length)
substr("Hello Word", 0, 5);
substr($text, 0, 5);
substr($row['style-info'], 0, 5);
for more detail
h2.text-left{
position:relative;
top:50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}
Explanation:
The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.
Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.
A possible fix for multiple lines would be to use a percentage slightly less than 50%.
Great Article... worked like a breeze on Amazon Linux AMI.
Two more useful commands:
To change the default FTP upload folder
Step 1:
edit /etc/vsftpd/vsftpd.conf
Step 2: Create a new entry at the bottom of the page:
local_root=/var/www/html
To apply read, write, delete permission to the files under folder so that you can manage using a FTP device
find /var/www/html -type d -exec chmod 777 {} \;
In case you're using pure razor, i.e. no MVC controller:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
@if (IsPost)
{
<p>@Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton
or p:commandLink
, chances are that you have forgotten to explicitly add process="@this"
to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process
and update
are both @form
, which pretty much opposes the defaults you might expect from plain JSF f:ajax
or RichFaces, which are execute="@this"
and render="@none"
respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
echo "text to echo" > file.txt
(variable1, @variable2, ..) SET variable2 = nullif(@variable2, '' or ' ') >> you can put any condition
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
This will work regardless of what column inside your one code line for cell thats located in row X, in column Y:
Mid(Cells(X,Y).Address, 2, instr(2,Cells(X,Y).Address,"$")-2)
If you have a cell with unique defined name "Cellname":
Mid(Cells(1,val(range("Cellname").Column)).Address, 2, instr(2,Cells(1,val(range("Cellname").Column)).Address,"$")-2)
You can try with textContent.
var productId = val[key].textContent;
I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web
while inside the first web folder.
The built in Java URLEncoder is doing what it's supposed to, and you should use it.
A "+" or "%20" are both valid replacements for a space character in a URL. Either one will work.
A ":" should be encoded, as it's a separator character. i.e. http://foo or ftp://bar. The fact that a particular browser can handle it when it's not encoded doesn't make it correct. You should encode them.
As a matter of good practice, be sure to use the method that takes a character encoding parameter. UTF-8 is generally used there, but you should supply it explicitly.
URLEncoder.encode(yourUrl, "UTF-8");
[data-value] {
/* Attribute exists */
}
[data-value="foo"] {
/* Attribute has this exact value */
}
[data-value*="foo"] {
/* Attribute value contains this value somewhere in it */
}
[data-value~="foo"] {
/* Attribute has this value in a space-separated list somewhere */
}
[data-value^="foo"] {
/* Attribute value starts with this */
}
[data-value|="foo"] {
/* Attribute value starts with this in a dash-separated list */
}
[data-value$="foo"] {
/* Attribute value ends with this */
}
Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:
SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);
I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,
~/ytdl_lv.sh <URL> <output file name>
e.g.
~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4
script is as simple as below,
#!/bin/bash
# ytdl_lv.sh
# Author Prashant
#
URL=$1
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best
here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)
In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.
'01/01/2010 14:30:00
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.
You can use static variables fairly easily as long as they are thread-local.
The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:
extern mod sqlite;
use std::cell::RefCell;
thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));
fn main() {
ODB.with(|odb_cell| {
let odb = odb_cell.borrow_mut();
// code that uses odb goes here
});
}
Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell
the value itself will be mutable.
Unlike regular static
, in thread-local!(static ...)
you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec
, HashMap
and others.
If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option
in there, in which case accessing it gets a bit unwieldy:
extern mod sqlite;
use std::cell::RefCell;
thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));
fn main() {
ODB.with(|odb_cell| {
// assumes the value has already been initialized, panics otherwise
let odb = odb_cell.borrow_mut().as_mut().unwrap();
// code that uses odb goes here
});
}
A key feature of dynamic programming is the presence of overlapping subproblems. That is, the problem that you are trying to solve can be broken into subproblems, and many of those subproblems share subsubproblems. It is like "Divide and conquer", but you end up doing the same thing many, many times. An example that I have used since 2003 when teaching or explaining these matters: you can compute Fibonacci numbers recursively.
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
Use your favorite language and try running it for fib(50)
. It will take a very, very long time. Roughly as much time as fib(50)
itself! However, a lot of unnecessary work is being done. fib(50)
will call fib(49)
and fib(48)
, but then both of those will end up calling fib(47)
, even though the value is the same. In fact, fib(47)
will be computed three times: by a direct call from fib(49)
, by a direct call from fib(48)
, and also by a direct call from another fib(48)
, the one that was spawned by the computation of fib(49)
... So you see, we have overlapping subproblems.
Great news: there is no need to compute the same value many times. Once you compute it once, cache the result, and the next time use the cached value! This is the essence of dynamic programming. You can call it "top-down", "memoization", or whatever else you want. This approach is very intuitive and very easy to implement. Just write a recursive solution first, test it on small tests, add memoization (caching of already computed values), and --- bingo! --- you are done.
Usually you can also write an equivalent iterative program that works from the bottom up, without recursion. In this case this would be the more natural approach: loop from 1 to 50 computing all the Fibonacci numbers as you go.
fib[0] = 0
fib[1] = 1
for i in range(48):
fib[i+2] = fib[i] + fib[i+1]
In any interesting scenario the bottom-up solution is usually more difficult to understand. However, once you do understand it, usually you'd get a much clearer big picture of how the algorithm works. In practice, when solving nontrivial problems, I recommend first writing the top-down approach and testing it on small examples. Then write the bottom-up solution and compare the two to make sure you are getting the same thing. Ideally, compare the two solutions automatically. Write a small routine that would generate lots of tests, ideally -- all small tests up to certain size --- and validate that both solutions give the same result. After that use the bottom-up solution in production, but keep the top-bottom code, commented out. This will make it easier for other developers to understand what it is that you are doing: bottom-up code can be quite incomprehensible, even you wrote it and even if you know exactly what you are doing.
In many applications the bottom-up approach is slightly faster because of the overhead of recursive calls. Stack overflow can also be an issue in certain problems, and note that this can very much depend on the input data. In some cases you may not be able to write a test causing a stack overflow if you don't understand dynamic programming well enough, but some day this may still happen.
Now, there are problems where the top-down approach is the only feasible solution because the problem space is so big that it is not possible to solve all subproblems. However, the "caching" still works in reasonable time because your input only needs a fraction of the subproblems to be solved --- but it is too tricky to explicitly define, which subproblems you need to solve, and hence to write a bottom-up solution. On the other hand, there are situations when you know you will need to solve all subproblems. In this case go on and use bottom-up.
I would personally use top-bottom for Paragraph optimization a.k.a the Word wrap optimization problem (look up the Knuth-Plass line-breaking algorithms; at least TeX uses it, and some software by Adobe Systems uses a similar approach). I would use bottom-up for the Fast Fourier Transform.
Any model which don't identify resource and the action associated with is restless. restless is not any term but a slang term to represent all other services that doesn't abide with the above definition. In restful model resource is identified by URL (NOUN) and the actions(VERBS) by the predefined methods in HTTP protocols i.e. GET, POST, PUT, DELETE etc.
import com.google.common.base
if(!Strings.isNullOrEmpty(String str)) {
// Do your stuff here
}
I think all explanations above are a bit too technical for the people who are new to Object Oriented Programming (OOP). Years ago, it took me a while to wrap my head around this (as Jr Java Developer) and I really did no understand why we use a parent class or an interface to hide the actual class we are actually calling under the covers.
The immediate reason why is to hide complexity, so that the caller does not need to change often (be hacked and jacked in laymen's terms). This makes a lot of sense, especially if you goals is to avoid creating bugs. And the more you modify code, the more likely it is that you will have some of them creep up on you. On the other hand, if you just extend code, it is way less likely that you will have bugs because you concentrate on one thing at a time and your old code does not change or changes just a bit. Imagine that you have simple application that allows the employees in the medical profession to create profiles. For simplicity, let's assume that we have only GeneralPractitioners, Surgeons, and Nurses (in reality there are many more specific professions, of course). For each profession, you want to store some general information and some specific to that professional alone. For example, a Surgeon may have general fields like firstName, lastName, yearsOfExperience as general fields but also specific fields, e.g. specializations stored in an list instance variable, like List with contents simiar to "Bone Surgery", "Eye Surgery", etc. A Nurse would not have any of that but may have list procedures they are familiar with, GeneralPractioners would have their own specifics. As a result, how you save a profile of a specifics. However, you don't want your ProfileManager class to know about these differences, as they will inevitably change and increase over time as your application expands its functionality to cover more medical professions, e.g. Physio Therapist, Cardiologist, Oncologist, etc. All you want your ProfileManger to do is just say save(), no matter whose profile it is saving. Thus, it is common practice to hide this behind and Interface, and Abstract Class, or a Parent Class (if you plan to allow creating a general medical employee). In this case, let's choose a Parent class and call it MedicalEmployee. Under the covers, it can reference any of the above specific classes that extend it. When the ProfileManager calls myMedicalEmployee.save() the save() method will be polymorphically (many-structurally) be resolved to the correct class type that was used to create the profile originally, for example Nurse and call the save() method in that class.
In many cases, you don't really know what implementation you will need at runtime. From the example above, you have no idea if a GeneralPractitioner, a Surgeon, or a Nurse would create a profile. Yet, you know that you need to save that profile once completed, no matter what. MedicalEmployee.profile() does exactly that. It is replicated (overridden) by each specific type of MedicalEmployee - GeneralPractitioner, Surgeon, Nurse,
The result of (1) and (2) above is that you now can add new medical professions, implement save() in each new class, thereby overriding the save() method in MedicalEmployee, and you don't have to modify ProfileManager at all.
I'm having the same warnings. I'm not sure it's a matter of 32 vs 64 bits. Just loaded the new symbols and some problems were solved, but the ones regarding OpenCV still persist. This is an extract of the output with solved vs unsolved issue:
'OpenCV_helloworld.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220d.dll', Cannot find or open the PDB file
'OpenCV_helloworld.exe': Loaded 'C:\WINDOWS\system32\imm32.dll', Symbols loaded (source information stripped).
The code is exiting 0 in case someone will ask.
The program '[4424] OpenCV_helloworld.exe: Native' has exited with code 0 (0x0).
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
# ...
if line.startswith(prefix):
return line[len(prefix):]
str.partition()
def findvar(filename, varname="Path", sep="=") :
for line in open(filename):
if line.startswith(varname + sep):
head, sep_, tail = line.partition(sep) # instead of `str.split()`
assert head == varname
assert sep_ == sep
return tail
from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present
path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation
This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try Sieve of Eratosthenes.
import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n % divisor == 0:
return False
return True
As far as I can see you have the JRE
in your PATH
, but not the JDK
.
From a command prompt try this:
set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin
Then try javac
again - if this works you'll need to permanently modify your environment variables to have PATH
include the JDK
too.
Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().
var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();
This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.
Following SierraX and Peter's suggestion about text manipulation, curly brackets {}
are used to pass a variable to a command, for instance:
Let's say you have a sposi.txt file containing the first line of a well-known Italian novel:
> sposi="somewhere/myfolder/sposi.txt"
> cat $sposi
Ouput: quel ramo del lago di como che volge a mezzogiorno
Now create two variables:
# Search the 2nd word found in the file that "sposi" variable points to
> word=$(cat $sposi | cut -d " " -f 2)
# This variable will replace the word
> new_word="filone"
Now substitute the word variable content with the one of new_word, inside sposi.txt file
> sed -i "s/${word}/${new_word}/g" $sposi
> cat $sposi
Ouput: quel filone del lago di como che volge a mezzogiorno
The word "ramo" has been replaced.
try this angular.isUndefined(value);
https://docs.angularjs.org/api/ng/function/angular.isUndefined
Most of the answers do not indicate that the container must run before docker cp
will work:
docker build -t IMAGE_TAG .
docker run -d IMAGE_TAG
CONTAINER_ID=$(docker ps -alq)
# If you do not know the exact file name, you'll need to run "ls"
# FILE=$(docker exec CONTAINER_ID sh -c "ls /path/*.zip")
docker cp $CONTAINER_ID:/path/to/file .
docker stop $CONTAINER_ID
I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:
mySID, mySID.whereever.com =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = mySID.whereever.com)
(SID = mySID)
(SERVER = DEDICATED)
)
)
I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.
Same as accepted answer, But note that it works even with .crt
file and not just .pem
file, just in case if you are not able to find .pem
file location.
openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt
Result:
notAfter=Mar 29 06:15:00 2020 GMT
With marquee
tag.
HTML
<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
<i>
<font color="blue">
Today's date is :
<strong>
<span id="time"></span>
</strong>
</font>
</i>
</marquee>
JS
var today = new Date();
document.getElementById('time').innerHTML=today;
Without marquee
tag and with CSS
.
HTML
<p class="marquee">
<span id="dtText"></span>
</p>
CSS
.marquee {
width: 350px;
margin: 0 auto;
background:yellow;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
color:blue;
font-size:18px;
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee 15s linear infinite;
}
.marquee span:hover {
animation-play-state: paused
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}
JS
var today = new Date();
document.getElementById('dtText').innerHTML=today;
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
Compatibility with older browsers can be a drag, so be adviced.
If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.
Change left and right values to meet your requirement.
Thank you.
Hope this helps.
#container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
flex: 1;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
background: orange;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="column left">this is left</div>_x000D_
<div class="column center">this is center</div>_x000D_
<div class="column right">this is right</div>_x000D_
</div>
_x000D_
I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
I had this problem with a fork from some online course. I cloned my fork and ran into a permissions error. I couldn't understand why it was insisting I was my user from my other company. But as the previous commenter mentioned I had the Clone git repositories using ssh
setting checked and I had forgotten to add an ssh key to my new account. So I did and then still couldn't push because I got THIS error. The way I solved it was to push using the Github Desktop client.
Takeaways:
Regex is overkill here.
You could use string.Split
with the overload that takes a string[]
for the delimiters but that would also be overkill.
Look at Substring
and IndexOf
- the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.
You need to make sure all of your assemblies are compiling for the correct architecture. Try changing the architecture for x86 if reinstalling the COM component doesn't work.
There is no button type="cancel"
in html. You can try like this
<a href="http://www.url.com/yourpage.php">Cancel</a>
You can make it look like a button by using CSS style properties.
style="cursor: pointer;"
I got this bug when I renamed the class. Then I solved it just by following the below steps
Product
-> Clean
Restart
the XcodeUnfortunately, what you ask for is directly frowned upon in the JavaDoc of Stream:
A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream.
You can work around this using peek
or other methods should you truly desire that type of behaviour. In this case, what you should do is instead of trying to back two streams from the same original Stream source with a forking filter, you would duplicate your stream and filter each of the duplicates appropriately.
However, you may wish to reconsider if a Stream
is the appropriate structure for your use case.
This is how I fixed it. in Visual Studio Code
's terminal, First cache clean
npm cache clean --force
Then updated cli
ng update @angular/cli
If any module missing after this, use below command
npm install
One way (2k8);
select 'abc_1_2_3_4.gif ' as img into #T
insert #T values ('zzz_12_3_3_45.gif')
;with T as (
select 0 as row, charindex('_', img) pos, img from #T
union all
select pos + 1, charindex('_', img, pos + 1), img
from T
where pos > 0
)
select
img, pos
from T
where pos > 0
order by img, pos
>>>>
img pos
abc_1_2_3_4.gif 4
abc_1_2_3_4.gif 6
abc_1_2_3_4.gif 8
abc_1_2_3_4.gif 10
zzz_12_3_3_45.gif 4
zzz_12_3_3_45.gif 7
zzz_12_3_3_45.gif 9
zzz_12_3_3_45.gif 11
Update
;with T(img, starts, pos) as (
select img, 1, charindex('_', img) from #t
union all
select img, pos + 1, charindex('_', img, pos + 1)
from t
where pos > 0
)
select
*, substring(img, starts, case when pos > 0 then pos - starts else len(img) end) token
from T
order by img, starts
>>>
img starts pos token
abc_1_2_3_4.gif 1 4 abc
abc_1_2_3_4.gif 5 6 1
abc_1_2_3_4.gif 7 8 2
abc_1_2_3_4.gif 9 10 3
abc_1_2_3_4.gif 11 0 4.gif
zzz_12_3_3_45.gif 1 4 zzz
zzz_12_3_3_45.gif 5 7 12
zzz_12_3_3_45.gif 8 9 3
zzz_12_3_3_45.gif 10 11 3
zzz_12_3_3_45.gif 12 0 45.gif
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
There are other solutions you can look into http://ngmodules.org/modules/ngUpload as discussed here file uploader integration for angularjs
Hope you dont mind Xml.Linq and .net3.5+
XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);
Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects
The shortest answer is
Please try this.
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
Even if both work, I would use the latter.
location
is an object, and assigning a string to an object doesn't bode well for readability or maintenance.
Open the Eclipse Installation Folder on Windows Machine
Find the eclipse.ini
Open the eclipse.ini File and add the below two lines before -vmargs
-vm
C:\Users\IshaqKhan\jdk1.8.0_173\bin\javaw.exe
Hmm. By default, <label>
is display: inline;
and <input>
is (roughly, at least) display: inline-block;
, so they should both be on the same line. See http://jsfiddle.net/BJU4f/
Perhaps a stylesheet is setting label
or input
to display: block
?
Revisiting this page and I have more information to share with others.
Debugging environment (using Visual Studio)
1a) Stephen Walter's link to set the startup page on MVC using the project properties is only applicable when you are debugging your MVC application.
1b) Right mouse click on the .aspx page in Solution Explorer and select the "Set As Start Page" behaves the same.
Note: in both the above cases, the startup page setting is only recognised by your Visual Studio Development Server. It is not recognised by your deployed server.
Deployed environment
2a) To set the startup page, assuming that you have not change any of the default routings, change the content of /Views/Home/Index.aspx to do a "Server.Transfer" or a "Response.Redirect" to your desired page.
2b) Change your default routing in your global.asax.cs to your desired page.
Are there any other options that the readers are aware of? Which of the above (including your own option) would be your preferred solution (and please share with us why)?
Check out SproutCore.
http://www.appleinsider.com/articles/10/04/19/sproutcore_debuts_new_html5_web_development_tools.html
Explanation of Serialize and Deserialize using Python
In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.
Serialization using pickle
import pickle
#the object to serialize
example_dic={1:"6",2:"2",3:"f"}
#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()
The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):
€}q (KX 6qKX 2qKX fqu.
Deserialization using pickle
import pickle
pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)
print(get_deserialized_data_back)
Output:
{1: '6', 2: '2', 3: 'f'}
insert into OPT (email, campaign_id)
select '[email protected]',100
from dual
where not exists(select *
from OPT
where (email ='[email protected]' and campaign_id =100));
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
I use Git Bash for my Windows.
$ eval $(ssh-agent -s) //activates the connection
$ ssh-add ~/.ssh/id_rsa //adds the identity
$ clip < ~/.ssh/id_rsa.pub //THIS IS THE IMPORTANT ONE. This adds your key to your clipboard. Go back to GitHub and just paste it in, and voilá! You should be good to go.
just use -
if(!a) // if a is negative,undefined,null,empty value then...
{
// do whatever
}
else {
// do whatever
}
this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.
Case sensitive: document.getElementById
(notice the capital B
).
When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.
In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).
This approach works for me in Node.js, Is there any problem with this one?
File 'include.js':
fs = require('fs');
File 'main.js':
require('./include.js');
fs.readFile('./file.json', function (err, data) {
if (err) {
console.log('ERROR: file.json not found...')
} else {
contents = JSON.parse(data)
};
})
Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.
As of Hive 0.14, the CSV SerDe is a standard part of the Hive install
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)
You must have .bash_profile file and define flutter path in .bash_profile file.
First of all, if you do not have or do not know .bash_profile, please look my answer: How do I edit $PATH (.bash_profile) on OSX?
You should add below line(.../flutter_SDK_path/flutter/bin) in your .bash_profile
export PATH=$PATH:/home/username/Documents/flutter_SDK_path/flutter/bin
After these steps, you can write flutter codes such as, flutter doctor
, flutter build ios
, flutter clean
or etc. in terminal of Macbook.
@canerkaseler
I've come up with a new solution, which has a tiny bit of overhead, but seems to be working so far as a prototype. One assumption is that you're in an honour system environment for logging in, although this could be adapted by rerequesting a password whenever you switch tabs.
Use localStorage (or equivalent) and the HTML5 storage event to detect when a new browser tab has switched which user is active. When that happens, create a ghost overlay with a message saying you can't use the current window (or otherwise disable the window temporarily, you might not want it to be this conspicuous.) When the window regains focus, send an AJAX request logging the user back in.
One caveat to this approach: you can't have any normal AJAX calls (i.e., ones that depend on your session) happen in a window that doesn't have the focus (e.g. if you had a call happening after a delay), unless you manually make an AJAX re-login call before that. So really all you need do is have your AJAX function check first to make sure localStorage.currently_logged_in_user_id === window.yourAppNameSpace.user_id, and if not, log in first via AJAX.
Another is race conditions: if you can switch windows fast enough to confuse it, you may end up with a relogin1->relogin2->ajax1->ajax2 sequence, with ajax1 being made under the wrong session. Work around this by pushing login AJAX requests onto an array, and then onstorage and before issuing a new login request, abort all current requests.
The last gotcha to look out for is window refreshes. If someone refreshes the window while you've got an AJAX login request active but not completed, it'll be refreshed in the name of the wrong person. In this case you can use the nonstandard beforeunload event to warn the user about the potential mixup and ask them to click Cancel, meanwhile reissuing an AJAX login request. Then the only way they can botch it is by clicking OK before the request completes (or by accidentally hitting enter/spacebar, because OK is--unfortunately for this case--the default.) There are other ways to handle this case, like detecting F5 and Ctrl+R/Alt+R presses, which will work in most cases but could be thwarted by user keyboard shortcut reconfiguration or alternative OS use. However, this is a bit of an edge case in reality, and the worst case scenarios are never that bad: in an honour system configuration, you'd be logged in as the wrong person (but you can make it obvious that this is the case by personalizing pages with colours, styles, prominently displayed names, etc.); in a password configuration, the onus is on the last person who entered their password to have logged out or shared their session, or if this person is actually the current user, then there's no breach.
But in the end you have a one-user-per-tab application that (hopefully) just acts as it should, without having to necessarily set up profiles, use IE, or rewrite URLs. Make sure you make it obvious in each tab who is logged into that particular tab, though...
Problem is when you already have an outline. Chrome still changes something and it's a real pain. I cannot find what to change :
.search input {
outline: .5em solid black;
width:41%;
background-color:white;
border:none;
font-size:1.4em;
padding: 0 0.5em 0 0.5em;
border-radius:3px;
margin:0;
height:2em;
}
.search input:focus, .search input:hover {
outline: .5em solid black !important;
box-shadow:none;
border-color:transparent;;
}
.search button {
border:none;
outline: .5em solid black;
color:white;
font-size:1.4em;
padding: 0 0.9em 0 0.9em;
border-radius: 3px;
margin:0;
height:2em;
background: -webkit-gradient(linear, left top, left bottom, from(#4EB4F8), to(#4198DE));
background: -webkit-linear-gradient(#4EB4F8, #4198DE);
background: -moz-linear-gradient(top, #4EB4F8, #4198DE);
background: -ms-linear-gradient(#4EB4F8, #4198DE);
background: -o-linear-gradient(#4EB4F8, #4198DE);
background: linear-gradient(#4EB4F8, #4198DE);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#4EB4F8', endColorstr='#4198DE');
zoom: 1;
}
In case you need to parse it from a file, I find the best solution to use a HashMap<String, String>
to use it inside your java code for better manipultion.
Try out this code:
public HashMap<String, String> myMethodName() throws FileNotFoundException
{
String path = "absolute path to your file";
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
Gson gson = new Gson();
HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
return json;
}
This worked for me but only after forcing the specific verbs to be handled by the default handler.
<system.web>
...
<httpHandlers>
...
<add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>
You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx
An easy way to test is just to deny GET and see if your site loads.
First open a console then cd to where you've downloaded your file like some-package.whl and use
pip install some-package.whl
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.
If pip is not installed, and you are using Windows: How to install pip on Windows?
Here is a very light and easy way:
var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
if (codes.indexOf(codes[i]) != i) {
codes.splice(i,1);
}
}
svn log --verbose -r 42
Its simple javascript. Done using toggling the type
attribute of the input. Check this http://jsfiddle.net/RZm5y/16/
try a this one:
...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);
It's a bad idea to change the behavior of the home key. This is why Google doesn't allow you to override the home key. I wouldn't mess with the home key generally speaking. You need to give the user a way to get out of your app if it goes off into the weeds for whatever reason.
I'd image any work around will have unwanted side effects.
I found another solution to get the data. according to the documentation Please check documentation link
In service file add following.
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class MoviesService {
constructor(private db: AngularFireDatabase) {}
getMovies() {
this.db.list('/movies').valueChanges();
}
}
In Component add following.
import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';
@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
movies$;
constructor(private moviesDb: MoviesService) {
this.movies$ = moviesDb.getMovies();
}
In your html file add following.
<li *ngFor="let m of movies$ | async">{{ m.name }} </li>
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
I use Privoxy and cURL to scrape Tor pages:
<?php
$ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_exec($ch);
curl_close($ch);
?>
After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config
). Note the space and '.' a the end of line.
forward-socks4a / localhost:9050 .
Then restart Privoxy.
/etc/init.d/privoxy restart
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
Your code scope (this
) will be your window
object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000)
will crash this way.
That comes from javascript not React, it is js closure
So, in order to bind your current react component scope, do this:
setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);
Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:
setTimeout(()=>this.setState({position: 1}), 3000);
You need to unlock handlers. This can be done using following cmd command:
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers
Maybe another info for people that are getting this error on IIS 8, in my case was on Microsoft Server 2012 platform. I had spend couple of hours battling with other errors that bubbled up after executing appcmd. In the end I was able to fix it by removing Web Server Role and installing it again.
Just unset the node:
$str = <<<STR
<a>
<b>
<c>
</c>
</b>
</a>
STR;
$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c
This code was taken from How to delete / remove nodes in SimpleXML.
Does the -verbose
flag to your java
command yield any useful info? If not, maybe java -X
reveals something specific to your version that might help?
To list only the containers SHA1:
docker ps -aq --no-trunc
That way, you can use the list of all containers for other commands (which accept multiple container ids as parameters).
For example, to list only the name of all containers (since docker ps
list only their names with other information):
docker inspect --format='{{.Name}}' $(sudo docker ps -aq --no-trunc)
Note that this may also work:
SELECT * FROM table WHERE s=ANY(array)
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
It is a unicode char \u003C = <
In FreeBSD 11:
pkg install openldap-client # for lber.h
pkg install cyrus-sasl # if you need sasl.h
pip install python-ldap
I also face this issue but it is resolved in different way. Steps that I follow may be helpful for others.
This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):
The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".
Note that the type(numpy.ndarray)
is a type
itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.
See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy
>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True
Fun with booleans:
>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool # python equivalent
True
More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in
>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True # generic integer
>>> isinstance(x[0], int)
False # but not a python int in this case
# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind
'b'
>>> np.dtype('int64').kind
'i'
>>> np.dtype('float').kind
'f'
>>> np.dtype('half').kind
'f'
# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False
# Down these paths there be dragons:
# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False # again, confusing the .dtype with a specific dtype
# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:
>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False # oh boy
>>> x[0].dtype == np.int
False # ya, no luck here either
>>> x[0].dtype == np.int_
False # or here
>>> x[0].dtype == np.uint64
True # have to end on a good note!
Does your images have exactly a 460px width as the span6 ? In my case, with different image sizes, I put a height attribute on my images to be sure they are all the same height and the carousel don't resize between images.
In your case, try to set a height so the ratio between this height and the width of your carousel-inner div is the same as the aspectRatio of your images
var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve()
, dgesv spits this kind of error when the matrix you passed as a parameter is singular.
As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)
I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.
I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.
SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.
This article explains a bit:
"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."
Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.
$('#table tr').slice(1).remove();
I remember coming across that 'slice' is faster than all other approaches, so just putting it here.
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
You can use the UpdateProgress control:
When you use VARIABLE = value
, if value
is actually a reference to another variable, then the value is only determined when VARIABLE
is used. This is best illustrated with an example:
VAL = foo
VARIABLE = $(VAL)
VAL = bar
# VARIABLE and VAL will both evaluate to "bar"
When you use VARIABLE := value
, you get the value of value
as it is now. For example:
VAL = foo
VARIABLE := $(VAL)
VAL = bar
# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"
Using VARIABLE ?= val
means that you only set the value of VARIABLE
if VARIABLE
is not set already. If it's not set already, the setting of the value is deferred until VARIABLE
is used (as in example 1).
VARIABLE += value
just appends value
to VARIABLE
. The actual value of value
is determined as it was when it was initially set, using either =
or :=
.
I have just discovered a way to append text and its working fine at least.
var text = 'Put any text here';
$('#text').append(text);
You can change text according to your need.
Hope this helps.
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
David's answer is correct. I'd like to add that you might be getting a sign from God that your design is messed up, and that "Son" ought not to be a subclass of "Super", but that, instead, Super has some implementation detail best expressed by having the functionality that Son provides, as a strategy of sorts.
EDIT: Jon Skeet's answer is awesomest.
in the university it was necessary to count prime numbers up to 10,000 did so, the teacher was a little surprised, but I passed the test. Lang c#
void Main()
{
int number=1;
for(long i=2;i<10000;i++)
{
if(PrimeTest(i))
{
Console.WriteLine(number+++" " +i);
}
}
}
List<long> KnownPrime = new List<long>();
private bool PrimeTest(long i)
{
if (i == 1) return false;
if (i == 2)
{
KnownPrime.Add(i);
return true;
}
foreach(int k in KnownPrime)
{
if(i%k==0)
return false;
}
KnownPrime.Add(i);
return true;
}
"No suitable driver" usually means that the JDBC
URL you've supplied to connect has incorrect syntax or when the driver isn't loaded at all.
When the method getConnection is called, the DriverManager
will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.(using Class.forName()
)
For Example
import oracle.jdbc.driver.OracleDriver;
Class.forName("oracle.jdbc.driver.OracleDriver");
Also check that you have ojdbc6.jar
in your classpath. I would suggest to place .jar
at physical location to JBoss "$JBOSS_HOME/server/default/lib/"
directory of your project.
EDIT:
You have mentioned hibernate
lately.
Check that your hibernate.cfg.xml
file has connection properties something like this:
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
tv.setText(Integer.toString(intValue))
In this case, your test.js
will not run, because you're loading it before jQuery. put it after jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="test.js"></script>
I was searching for the iOS PCH file having the same problem, if you got here like me too, the solution that I've found is by clearing derived data; Close Simulator(s), go to xCode prefs -> locations -> go to the derived data file path, close xCode, delete the files in the derived data folder, re launch and cheers :)
If you're using Entity Framework, you can extend the default timeout (to give a long-running query more time to complete) by doing:
myDbContext.Database.CommandTimeout = 300;
Where myDbContext
is your DbContext instance, and 300
is the timeout value in seconds.
(Syntax current as of Entity Framework 6.)
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
in windows: if you have mysql workbench. Go to server status. find the location of running server file in my case it was:
C:\ProgramData\MySQL\MySQL Server 5.7
open my.ini file and find the buffer_pool_size. Set the value high. default value is 8M. This is how i fixed this problem
simply "CUT" project folder and move it out of workspace directory and do the following
file=>import=>(select new directory)=> mark (copy to my workspace) checkbox
and you done !
I am assuming that you need the JDK itself. If so you can accomplish this with:
sudo add-apt-repository ppa:sun-java-community-team/sun-java6
sudo apt-get update
sudo apt-get install sun-java6-jdk
You don't really need to go around editing sources or anything along those lines.
if you want to find datadir in linux or windows you can do following command
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'
if you are interested to find datadir you can use grep & awk command
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"' | grep 'datadir' | awk '{print $2}'
Let's say you have these lines of code:
test line one
test line two
test line three
test line four
Using Search and Replace Ctrl+H with Regex let's find this: ^
and replace it with "
, we'll have this:
"test line one
"test line two
"test line three
"test line four
Now let's search this: $
and replace it with "
, now we'll have this:
"test line one"
"test line two"
"test line three"
"test line four"
ArrayAdapter<String>
should work.
i.e.:
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,
spinnerArray); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.
Here a temporary workaround, If you are using room just upgrade to 1.1.0 or higher
implementation "android.arch.persistence.room:runtime:1.1.0"
it removes this warning for me.
I'm not allowed to write any comments yet, so I'll write an answer, if somebody will read all of them and reach this one.
If the index of the dataset is a datetime and you want to filter that just by (for example) months, you can do following:
df.loc[df.index.month == 3]
That will filter the dataset for you by March.
In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.
<video controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>
We can add an external HLS js script in web application.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Your title</title>
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
<script src="https://unpkg.com/video.js/dist/video.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
data-setup='{}'>
<source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
</video>
<script>
var player = videojs('my_video_1');
player.play();
</script>
</body>
</html>
The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.
Just document it here
on Windows you need to escape the \
character:
"e:\\directory\\-"
Here's a very short solution, that only works for 1 or 2 long strings. It's a oneliner, and it's blazing fast, using ES6 and not depending on jQuery. Enjoy:
var p = l => l.length<2 ? [l] : l.length==2 ? [l[0]+l[1],l[1]+l[0]] : Function('throw Error("unimplemented")')();
public
: it is a access specifier that means it will be accessed by publically.static
: it is access modifier that means when the java program is load then it will create the space in memory automatically.void
: it is a return type i.e it does not return any value.main()
: it is a method or a function name.string args[]
: its a command line argument it is a collection of variables in the string format.This is not like Collections.sort()
where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:
List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
compareTo(o2.getItem().getValue())).
collect(Collectors.toList());
You've just missed to assign the result
First of all you should verify that you have no excess virtual hosts in your httpd-vhosts file. I mean following simple rule: 1 project = 1 virtual host in config file. Otherwise you'll face with error even if you'll change ports etc.
Easier Yet, you can operate directly on $@
;)
Here is how to do pass a a list of args directly from the prompt:
function echoarg { for stuff in "$@" ; do echo $stuff ; done ; }
echoarg Hey Ho Lets Go
Hey
Ho
Lets
Go
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.