I've used answer of @afrodev as reference. In my case I take parameter to my function as string that have to be posted in request. So, here is the code:
func defineOriginalLanguage(ofText: String) {
let text = ofText
let stringURL = basicURL + "identify?version=2018-05-01"
let url = URL(string: stringURL)
var request = URLRequest(url: url!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = text.data(using: .utf8)
Alamofire.request(request)
.responseJSON { response in
print(response)
}
}
Mime header and from, to address also can be included in the html file it self.
Command
cat cpu_alert.html | /usr/lib/sendmail -t
cpu_alert.html file sample.
From: [email protected]
To: [email protected]
Subject: CPU utilization heigh
Mime-Version: 1.0
Content-Type: text/html
<h1>Mail body will be here</h1>
The mail body should start after one blank line from the header.
Sample code available here: http://sugunan.net/git/slides/shell/cpu.php
[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar
[host_group:vars]
custom_var=asdasdasd
You can access host group vars using:
{{ hostvars['host_group'].custom_var }}
If you need a specific value from specific host, you can use:
{{ hostvars[groups['host_group'][0]].node_name }}
You can use a Spring-EL expression, for eg on JDK 1.7:
@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")
In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.
If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.
From your snippet Your class AliceUniversity
seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate
and UniversityGraduate
.
Pure virtual functions are the ones with = 0;
at the end of declaration.
Example: virtual void doSomething() = 0;
For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.
You need a database that contains IP address and location mapping. Or you can use a lot of online tools to achieve this, for example: http://www.ipligence.com/geolocation
Google returs lots of result under keywords: "IP location"
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Give your ul
an id
,
<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">
then do
var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';
IF you're using jQuery, this becomes:
var $yourUl = $("#yourUlId");
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');
Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery
$("#yourUlId").toggle();
will alternate between showing or hiding this element.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
Well, there really is a lot to this. I'm assuming you have an account on http://github.com/. If not, go get one.
After that, you really can just follow their guide, its very simple and easy and the explanation is much more clear than mine: http://help.github.com/ >> http://help.github.com/mac-set-up-git/
To answer your specific question: You upload files to github through the git push
command after you have added your files you needed through git add 'files'
and commmited them git commit -m "my commit messsage"
I broke my head to understand why your answers for WPA/WPA2 don't work...after hours of tries I found what you are missing:
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
is REQUIRED for WPA networks!!!!
Now, it works :)
Suppose you have one stored procedure like this
First stored procedure:
Create PROCEDURE LoginId
@UserName nvarchar(200),
@Password nvarchar(200)
AS
BEGIN
DECLARE @loginID int
SELECT @loginID = LoginId
FROM UserLogin
WHERE UserName = @UserName AND Password = @Password
return @loginID
END
Now you want to call this procedure from another stored procedure like as below
Second stored procedure
Create PROCEDURE Emprecord
@UserName nvarchar(200),
@Password nvarchar(200),
@Email nvarchar(200),
@IsAdmin bit,
@EmpName nvarchar(200),
@EmpLastName nvarchar(200),
@EmpAddress nvarchar(200),
@EmpContactNo nvarchar(150),
@EmpCompanyName nvarchar(200)
AS
BEGIN
INSERT INTO UserLogin VALUES(@UserName,@Password,@Email,@IsAdmin)
DECLARE @EmpLoginid int
**exec @EmpLoginid= LoginId @UserName,@Password**
INSERT INTO tblEmployee VALUES(@EmpName,@EmpLastName,@EmpAddress,@EmpContactNo,@EmpCompanyName,@EmpLoginid)
END
As you seen above, we can call one stored procedure from another
This article thoroughly explains the difference between different implementations of Python. Like the article puts it:
The first thing to realize is that ‘Python’ is an interface. There’s a specification of what Python should do and how it should behave (as with any interface). And there are multiple implementations (as with any interface).
The second thing to realize is that ‘interpreted’ and ‘compiled’ are properties of an implementation, not an interface.
Another way - inspired by this this answer - to "inject" variables is the following (fcron example):
%daily 00 12 \
set -a; \
. /path/to/file/containing/vars; \
set +a; \
/path/to/script/using/vars
From help set
:
-a Mark variables which are modified or created for export.
Using + rather than - causes these flags to be turned off.
So everything in between set -
and set +
gets exported to env
and is then available for other scripts, etc. Without using set
the variables get sourced but live in set
only.
Aside from that it's also useful to pass variables when a program requires a non-root account to run but you'd need some variables inside that other user's environment. Below is an example passing in nullmailer vars to format the e-mail header:
su -s /bin/bash -c "set -a; \
. /path/to/nullmailer-vars; \
set +a; \
/usr/sbin/logcheck" logcheck
You need to escape the backslash \
:
println yourString.replace("\\", "/")
You can use free tool called Advanced SQL Server Dependencies http://advancedsqlserverdependencies.codeplex.com/
It supports all database objects (tables, views, etc.) and can find dependencies across multiple databases (in case of synonyms).
The accepted answer suggests to modify the raw data for presentation purposes, something you generally do not want. Imagine you need to make further analyses with these columns and you need the precision you lost with rounding.
You can modify the formatting of individual columns in data frames, in your case:
output = df.to_string(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
print(output)
For your information '{:,.2%}'.format(0.214)
yields 21.40%
, so no need for multiplying by 100.
You don't have a nice HTML table anymore but a text representation. If you need to stay with HTML use the to_html
function instead.
from IPython.core.display import display, HTML
output = df.to_html(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
display(HTML(output))
Update
As of pandas 0.17.1, life got easier and we can get a beautiful html table right away:
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
may be in your case you could reach this with the following:
mv excluded_dir ..\
ls -R
mv ..\excluded_dir .
# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password
encrypted and test with the current Password not encrypted to verify
if it's the same User.
For example :
public function updateUser(Request $req)
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(User::class);
$user = $repository->find($req->get(id)); /// get User from your DB
if($user == null){
throw $this->createNotFoundException('User don't exist!!', $user);
}
$password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
$passwordToUpdate = $req->get('password'); // not encrypted yet from request.
$passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);
////////////VERIFY IF IT'S THE SAME PASSWORD
$isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );
if($isPass === false){ // failure
throw $this->createNotFoundException('Your password it's not verify', null);
}
return $isPass; //// true!! it's the same password !!!
}
This thread is perhaps very very old now. But want to share these results for someone who see this thread. Ran a comparison betn. Flotr2, ChartJS, highcharts asynchronously. Flotr2 seems to be the quickest. Tested this by passing a new data point every 50ms upto 1000 data points totally. Flotr2 was the quickest for me though it appears to be redrawing charts regularly.
Try just this without the span tag:
<option selected="selected" class="grey_color">select one option</option>
For bigger flexibility you can use any JS widget.
If you want to return the original string untouched if it does not contain the search character then you can use an anonymous function (a closure):
var streetaddress=(function(s){var i=s.indexOf(',');
return i==-1 ? s : s.substr(0,i);})(addy);
This can be made more generic:
var streetaddress=(function(s,c){var i=s.indexOf(c);
return i==-1 ? s : s.substr(0,i);})(addy,',');
Actually, ECMAScript says on page 15: That an identifier may start with a $, an underscore or a UnicodeLetter, and then it goes on (just below that) to specify that a UnicodeLetter can be any character from the unicode catagories, Lo, Ll, Lu, Lt, Lm and Nl. And when you look up those catagories you will see that this opens up a lot more possibilities than just latin letters. Just search for "unicode catagories" in google and you can find them.
You can use this way to fulfill this requirement. I use the below method to validate the Password and Confirm Password.
To use this method you have to import FormGroup
from @angular/forms
library.
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
FormBuilder Group:
this.myForm= this.formBuilder.group({
password : ['', Validators.compose([Validators.required])],
confirmPassword : ['', Validators.compose([Validators.required])],
},
{validator: this.checkPassword('password', 'confirmPassword') }
);
Method to Validate two fields:
checkPassword(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
} else {
matchingControl.setErrors(null);
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
}
}
}
HTML: Here I am use personalized isPasswordSame variable you can use the inbuilt hasError or any other.
<form [formGroup]="myForm">
<ion-item>
<ion-label position="floating">Password</ion-label>
<ion-input required type="text" formControlName="password" placeholder="Enter Password"></ion-input>
</ion-item>
<ion-label *ngIf="myForm.controls.password.valid">
<p class="error">Please enter password!!</p>
</ion-label>
<ion-item>
<ion-label position="floating">Confirm Password</ion-label>
<ion-input required type="text" formControlName="confirmPassword" placeholder="Enter Confirm Password"></ion-input>
</ion-item>
<ion-label *ngIf="isPasswordSame">
<p class="error">Password and Confrim Password must be same!!</p>
</ion-label>
</form>
So it seems that there is no way to reattach a stale detached entity in JPA.
merge()
will push the stale state to the DB,
and overwrite any intervening updates.
refresh()
cannot be called on a detached entity.
lock()
cannot be called on a detached entity,
and even if it could, and it did reattach the entity,
calling 'lock' with argument 'LockMode.NONE'
implying that you are locking, but not locking,
is the most counterintuitive piece of API design I've ever seen.
So you are stuck.
There's an detach()
method, but no attach()
or reattach()
.
An obvious step in the object lifecycle is not available to you.
Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.
It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.
Mik
As of February 2020, for Android Studio 3.5.3, the simplest answer I found is this video.
Note 1: At 01.24 "Find" tab appears below. Click "Do Refactor" and continue as in the video.
Note 2: If you have any Java/Kotlin files "Marked as Plain Text" you need to modify the package name at the top manually, i.e. package com.example.thisplaceneedstobemanuallyupdated
Note 3: Be careful about letter cases while renaming, just as in the video.
Note 4: If you want to update the project name on title bar of project window, modify rootProject.name = 'YourProjectName'
inside "settings.gradle" file under "Gradle Scripts" directory.
select distinct owner
from dba_segments
where owner in (select username from dba_users where default_tablespace not in ('SYSTEM','SYSAUX'));
Based on some answers I found here, I made myself a small helper file to source for my projects:
#!/bin/bash
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
here is an example how it looks like in use:
#!/bin/bash
export AnException=100
export AnotherException=101
# start with a try
try
( # open a subshell !!!
echo "do something"
[ someErrorCondition ] && throw $AnException
echo "do something more"
executeCommandThatMightFail || throw $AnotherException
throwErrors # automaticatly end the try block, if command-result is non-null
echo "now on to something completely different"
executeCommandThatMightFail
echo "it's a wonder we came so far"
executeCommandThatFailsForSure || true # ignore a single failing command
ignoreErrors # ignore failures of commands until further notice
executeCommand1ThatFailsForSure
local result = $(executeCommand2ThatFailsForSure)
[ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
executeCommand3ThatFailsForSure
echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
# now you can handle
case $ex_code in
$AnException)
echo "AnException was thrown"
;;
$AnotherException)
echo "AnotherException was thrown"
;;
*)
echo "An unexpected exception was thrown"
throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
;;
esac
}
NOTE:
pd.convert_objects
has now been deprecated. You should usepd.Series.astype(float)
orpd.to_numeric
as described in other answers.
This is available in 0.11. Forces conversion (or set's to nan)
This will work even when astype
will fail; its also series by series
so it won't convert say a complete string column
In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))
In [11]: df
Out[11]:
A B
0 1.0 1.0
1 1 foo
In [12]: df.dtypes
Out[12]:
A object
B object
dtype: object
In [13]: df.convert_objects(convert_numeric=True)
Out[13]:
A B
0 1 1
1 1 NaN
In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]:
A float64
B float64
dtype: object
FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.
Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).
Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.
IMO some of the previous answers are incorrect! (It's possible to sort the answers to start from oldest to newest).
array_merge()
actually merges the arrays, meaning, if the arrays have a common item one of the copies will be omitted. Same goes for +
(union).
I didn't find a "work-around" for this issue, but to do it manually...
Here it goes:
<?php
$part1 = array(1,2,3);
echo "array 1 = \n";
print_r($part1);
$part2 = array(4,5,6);
echo "array 2 = \n";
print_r($part2);
$ans = NULL;
for ($i = 0; $i < count($part1); $i++) {
$ans[] = $part1[$i];
}
for ($i = 0; $i < count($part2); $i++) {
$ans[] = $part2[$i];
}
echo "after arrays concatenation:\n";
print_r($ans);
?>
You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.
To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.
UPDATE: JUST USE JSON.stringify to print objects on screen!
All you need is this line:
document.body.innerHTML = '<pre>' + JSON.stringify(ObjectWithSubObjects, null, "\t") + '</pre>';
This is my older version of printing objects recursively on screen:
var previousStack = '';
var output = '';
function objToString(obj, stack) {
for (var property in obj) {
var tab = ' ';
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === 'object' && typeof stack === 'undefined') {
config = objToString(obj[property], property);
} else {
if (typeof stack !== 'undefined' && stack !== null && stack === previousStack) {
output = output.substring(0, output.length - 1); // remove last }
output += tab + '<span>' + property + ': ' + obj[property] + '</span><br />'; // insert property
output += '}'; // add last } again
} else {
if (typeof stack !== 'undefined') {
output += stack + ': { <br />' + tab;
}
output += '<span>' + property + ': ' + obj[property] + '</span><br />';
if (typeof stack !== 'undefined') {
output += '}';
}
}
previousStack = stack;
}
}
}
return output;
}
Usage:
document.body.innerHTML = objToString(ObjectWithSubObjects);
Example output:
cache: false
position: fixed
effect: {
fade: false
fall: true
}
Obviously this can be improved by adding comma's when needed and quotes from string values. But this was good enough for my case.
It's not a HTTP response code, but it is documented by WhatWG as a valid value for the status attribute of an XMLHttpRequest
or a Fetch response.
Broadly speaking, it is a default value used when there is no real HTTP status code to report and/or an error occurred sending the request or receiving the response. Possible scenarios where this is the case include, but are not limited to:
First, to reiterate: 0 is not a HTTP status code. There's a complete list of them in RFC 7231 Section 6.1, that doesn't include 0, and the intro to section 6 states clearly that
The status-code element is a three-digit integer code
which 0 is not.
However, 0 as a value of the .status
attribute of an XMLHttpRequest object is documented, although it's a little tricky to track down all the relevant details. We begin at https://xhr.spec.whatwg.org/#the-status-attribute, documenting the .status
attribute, which simply states:
That may sound vacuous and tautological, but in reality there is information here! Remember that this documentation is talking here about the .response
attribute of an XMLHttpRequest
, not a response, so this tells us that the definition of the status on an XHR object is deferred to the definition of a response's status in the Fetch spec.
But what response object? What if we haven't actually received a response yet? The inline link on the word "response" takes us to https://xhr.spec.whatwg.org/#response, which explains:
An
XMLHttpRequest
has an associated response. Unless stated otherwise it is a network error.
So the response whose status we're getting is by default a network error. And by searching for everywhere the phrase "set response to" is used in the XHR spec, we can see that it's set in five places:
To a network error, when:
open()
method is called, orsend()
method)abort()
method is called, causing the request error steps to runTo the response produced by sending the request using Fetch, by way of either the Fetch process response task (if the XHR request is asychronous) or the Fetch process response end-of-body task (if the XHR request is synchronous).
Looking in the Fetch standard, we can see that:
A network error is a response whose status is always
0
so we can immediately tell that we'll see a status of 0 on an XHR object in any of the cases where the XHR spec says the response should be set to a network error. (Interestingly, this includes the case where the body's stream gets "errored", which the Fetch spec tells us can happen during parsing the body after having received the status - so in theory I suppose it is possible for an XHR object to have its status set to 200, then encounter an out-of-memory error or something while receiving the body and so change its status back to 0.)
We also note in the Fetch standard that a couple of other response types exist whose status is defined to be 0, whose existence relates to cross-origin requests and the same-origin policy:
An opaque filtered response is a filtered response whose ... status is
0
...An opaque-redirect filtered response is a filtered response whose ... status is
0
...
(various other details about these two response types omitted).
But beyond these, there are also many cases where the Fetch algorithm (rather than the XHR spec, which we've already looked at) calls for the browser to return a network error! Indeed, the phrase "return a network error" appears 40 times in the Fetch standard. I will not try to list all 40 here, but I note that they include:
In other words: whenever something goes wrong other than getting a real HTTP error status code like a 500 or 400 from the server, you end up with a status attribute of 0 on your XHR object or Fetch response object in the browser. The number of possible specific causes enumerated in spec is vast.
Finally: if you're interested in the history of the spec for some reason, note that this answer was completely rewritten in 2020, and that you may be interested in the previous revision of this answer, which parsed essentially the same conclusions out of the older (and much simpler) W3 spec for XHR, before these were replaced by the more modern and more complicated WhatWG specs this answers refers to.
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
This worked for me in Oracle:
SELECT a.*
FROM tbl1 a
MINUS
SELECT b.*
FROM tbl2 b;
TLDR; Uninstall and re-install using admin account.
I encountered this error after installing Oracle Express 11g 64 bit using a standard account. After looking for a fix on various sites I realized that the issue was most likely caused by an incorrect setting. Different people suggested editing various files which I was not interested in doing. I found one person who claimed that the issue was a registry setting. Since I used a standard account to install I thought that maybe the registry setting could not be altered using a standard account. So I uninstalled and re-installed using an admin account and it just worked.
For this purpose and if i dont have boolean variable i use the following:
<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">
I messed with this for several hours and tried many different suggestions.
I finally got it to work by doing the following:
Action: Start a program
Program/Script: C:\scriptdir\script.bat
Add arguments (optional) script.bat
Start in (optional): c:\scriptdir
run only when user logged in
run with highest privileges
configure for: Windows Vista, Windows Server 2008
I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
selector: 'my-component',_x000D_
templateUrl: './my-component.component.html',_x000D_
styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
public backgroundImg: SafeStyle;_x000D_
@Input() myObject: any;_x000D_
_x000D_
constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
ngOnInit() {_x000D_
this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
}_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.
Example:
var testObject = {
"1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround
Though $toInt
is really useful, it was added on mongoDB 4.0, I've run into this same situation in a database running 3.2 which upgrading to use $toInt
was not an option due to some other application incompatibilities, so i had to come up with something else, and actually was surprisingly simple.
If you $project
and $add
zero to your string, it will turn into a number
{
$project : {
'convertedField' : { $add : ["$stringField",0] },
//more fields here...
}
}
You can set your hash directly to URL too.
window.location.hash = "YourHash";
The result : http://url#YourHash
The timeouts()
methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):
Thread t = new Thread(new Runnable() {
public void run() {
driver.get(Thread.currentThread().getName());
}
}, url);
t.start();
try {
t.join(YOUR_TIMEOUT_HERE_IN_MS);
} catch (InterruptedException e) { // ignore
}
if (t.isAlive()) { // Thread still alive, we need to abort
logger.warning("Timeout on loading page " + url);
t.interrupt();
}
This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
Annotating with @XmlTransient
resolves that issue
@XmlTransient
public void setTimeSeries(List<TimeSeries> timeSeries) {
this.timeSeries = timeSeries;
}
Look at http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlTransient.html for more details
The best practice is definitely to avoid loops or recursions in Matlab.
Between sum(A(:))
and sum(sum(A))
.
In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum()
. (One can test reshape()
and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)
As such, there is no reason sum(sum(A))
should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A))
is very wide-spread amongst users. It is likely that they hard-code sum(sum(A))
to be a single loop, the same to sum(A(:))
.
Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.
First is using tic toc.
Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.
Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.
Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.
Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27 (line 70)
A=rand(100000000,1);
Below is using cputime
Size 100x100
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x1
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000x1000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27_2 (line 70)
A=rand(100000000,1);
In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:))
and sum(sum(A))
.
I tried the largest size allowed on my computer a few more times.
Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.2808
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
They seem equivalent.
Either one is good. But sum(sum(A))
requires that you know the dimension of your array is 2.
inline fun <reified T : Enum<T>> Intent.putExtra(enumVal: T, key: String? = T::class.qualifiedName): Intent =
putExtra(key, enumVal.ordinal)
inline fun <reified T: Enum<T>> Intent.getEnumExtra(key: String? = T::class.qualifiedName): T? =
getIntExtra(key, -1)
.takeUnless { it == -1 }
?.let { T::class.java.enumConstants[it] }
This gives you the flexibility to pass multiple of the same enum type, or default to using the class name.
// Add to gradle
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
// Import the extension functions
import path.to.my.kotlin.script.putExtra
import path.to.my.kotlin.script.getEnumExtra
// To Send
intent.putExtra(MyEnumClass.VALUE)
// To Receive
val result = intent.getEnumExtra<MyEnumClass>()
Div of style, position:absolute;bottom:5px;width:100%;
is working,
But it required more scrollup situation.
window.onscroll = function() {
var v = document.getElementById("copyright");
v.style.position = "fixed";
v.style.bottom = "5px";
}
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
console.log(objArray.sort(function(a, b) { return a.name > b.name}));
This solved my problem with google.protobuf import in Tensorflow and Python 3.7.5 that i had yesterday.
Check where is protobuf
pip show protobuf
If it is installed you will get something like this
Name: protobuf
Version: 3.6.1
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /usr/lib/python3/dist-packages
Requires:
Required-by: tensorflow, tensorboard
(If not, run pip install protobuf
)
Now move into the location folder.
cd /usr/lib/python3/dist-packages
Now run
touch google/__init__.py
Use default parameters
template <typename T>
void func(T a, T b = T()) {
std::cout << a << b;
}
int main()
{
func(1,4); // a = 1, b = 4
func(1); // a = 1, b = 0
std::string x = "Hello";
std::string y = "World";
func(x,y); // a = "Hello", b ="World"
func(x); // a = "Hello", b = ""
}
Note : The following are ill-formed
template <typename T>
void func(T a = T(), T b )
template <typename T>
void func(T a, T b = a )
Please add the keyword public to your class definition. Your test class is currently not visible outside its own assembly.
namespace tests {
[TestClass]
public class SimpleTest {
[TestMethod]
public void Test() {
Assert.AreEqual("a","a", "same");
}
}
}
You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:
Find (in regular expression mode):
(.+)
Replace with:
"\1"
This adds the quotes:
"AliceBlue"
"AntiqueWhite"
"Aqua"
"Aquamarine"
"Azure"
"Beige"
"Bisque"
"Black"
"BlanchedAlmond"
Find (in extended mode):
\r\n
Replace with (with a space after the comma, not shown):
,
This converts the lines into a comma-separated list:
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
Add the var myArray =
assignment and braces manually:
var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
I was trying to find the meaning of GRANT USAGE on *.* TO
and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password
will be granted when you create the user with the following command (CREATE
):
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
When you grant privilege with GRANT
, new privilege s will be added on top of it.
For example, for developing interactive, realtime HTML5 web applications. See Elm, the compiler of which is implemented in Haskell and the syntax of which borrows a lot from Haskell's.
It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.
It just reminds you the differences between the current branch and the branch which does the current track. Please provide more info, including what branch is printed in the message and where do you push/pull the current branch.
But, sometimes, even with user-select
and touch-callout
turned off, cursor: pointer;
may cause this effect, so, just set cursor: default;
and it'll work.
The Python 2 syntax works in Python 3 as well:
>>> class MyClass:
... def __init__(self):
... self.title = 'Title'
...
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>>
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file
This will have some overhead, but technically it does answer your question:
echo abc `#Put your comment here` \
def `#Another chance for a comment` \
xyz, etc.
And for pipelines specifically, there is a clean solution with no overhead:
echo abc | # Normal comment OK here
tr a-z A-Z | # Another normal comment OK here
sort | # The pipelines are automatically continued
uniq # Final comment
See Stack Overflow question How to Put Line Comment for a Multi-line Command.
To expand a bit on Hossein Narimani Rad's answer, you can rename both a table and columns using System.ComponentModel.DataAnnotations.Schema.TableAttribute and System.ComponentModel.DataAnnotations.Schema.ColumnAttribute respectively.
This has a couple benefits:
For example, adding [Table("Staffs")]
:
[Table("Staffs")]
public class AccountUser
{
public long Id { get; set; }
public long AccountId { get; set; }
public string ApplicationUserId { get; set; }
public virtual Account Account { get; set; }
public virtual ApplicationUser User { get; set; }
}
Will generate the migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AccountUsers_Accounts_AccountId",
table: "AccountUsers");
migrationBuilder.DropForeignKey(
name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
table: "AccountUsers");
migrationBuilder.DropPrimaryKey(
name: "PK_AccountUsers",
table: "AccountUsers");
migrationBuilder.RenameTable(
name: "AccountUsers",
newName: "Staffs");
migrationBuilder.RenameIndex(
name: "IX_AccountUsers_ApplicationUserId",
table: "Staffs",
newName: "IX_Staffs_ApplicationUserId");
migrationBuilder.RenameIndex(
name: "IX_AccountUsers_AccountId",
table: "Staffs",
newName: "IX_Staffs_AccountId");
migrationBuilder.AddPrimaryKey(
name: "PK_Staffs",
table: "Staffs",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Staffs_Accounts_AccountId",
table: "Staffs",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Staffs_AspNetUsers_ApplicationUserId",
table: "Staffs",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Staffs_Accounts_AccountId",
table: "Staffs");
migrationBuilder.DropForeignKey(
name: "FK_Staffs_AspNetUsers_ApplicationUserId",
table: "Staffs");
migrationBuilder.DropPrimaryKey(
name: "PK_Staffs",
table: "Staffs");
migrationBuilder.RenameTable(
name: "Staffs",
newName: "AccountUsers");
migrationBuilder.RenameIndex(
name: "IX_Staffs_ApplicationUserId",
table: "AccountUsers",
newName: "IX_AccountUsers_ApplicationUserId");
migrationBuilder.RenameIndex(
name: "IX_Staffs_AccountId",
table: "AccountUsers",
newName: "IX_AccountUsers_AccountId");
migrationBuilder.AddPrimaryKey(
name: "PK_AccountUsers",
table: "AccountUsers",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_AccountUsers_Accounts_AccountId",
table: "AccountUsers",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
table: "AccountUsers",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
You can also do this
public class Example extends Activity {
final Context context = this;
final Dialog dialog = new Dialog(context);
}
This worked for me !!
The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.
You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.
The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.
In your planner component, you must be missing import HeaderAreaComponent like this-
import { HeaderAreaComponent } from '../header-area.component';
//change path according your project
Also, make sure - All the components and pipes must be declared via an NgModule.
See if this helps.
I'm a bit new to Bibtex (and to Latex in general) and I'd like to revive this old post since I found it came up in many of my Google search inquiries about the ordering of a bibliography in Latex.
I'm providing a more verbose answer to this question in the hope that it might help some novices out there facing the same difficulties as me.
Here is an example of the main .tex file in which the bibliography is called:
\documentclass{article}
\begin{document}
So basically this is where the body of your document goes.
``FreeBSD is easy to install,'' said no one ever \cite{drugtrafficker88}.
``Yeah well at least I've got chicken,'' said Leeroy Jenkins \cite{goodenough04}.
\newpage
\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited
\bibliography{references} % Or whatever your .bib file is called
\end{document}
...and an example of the .bib file itself:
@ARTICLE{ goodenough04,
AUTHOR = "G. D. Goodenough and others",
TITLE = "What it's like to have a sick-nasty last name",
JOURNAL = "IEEE Trans. Geosci. Rem. Sens.",
YEAR = "xxxx",
volume = "xx",
number = "xx",
pages = "xx--xx"
}
@BOOK{ drugtrafficker88,
AUTHOR = "G. Drugtrafficker",
TITLE = "What it's Like to Have a Misleading Last Name",
YEAR = "xxxx",
PUBLISHER = "Harcourt Brace Jovanovich, Inc."
ADDRESS = "The Florida Alps, FL, USA"
}
Note the references in the .bib file are listed in reverse order but the references are listed in the order they are cited in the paper.
More information on the formatting of your .bib file can be found here: http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management
You could simply use target="_blank"
on the form.
<form action="action.php" method="post" target="_blank">
<input type="hidden" name="something" value="some value">
</form>
Add hidden inputs in the way you prefer, and then simply submit the form with JS.
For some reason I was not able to use my scalar function until I referenced it using brackets, like so:
select [dbo].[fun_functional_score]('01091400003')
Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
In php 7.2+ you can't use count
on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:
$model->relation()->exists()
generic solution working on all the relation types (pre php 7.2):
if (count($model->relation))
{
// exists
}
This will work for every relation since dynamic properties return Model
or Collection
. Both implement ArrayAccess
.
So it goes like this:
single relations: hasOne
/ belongsTo
/ morphTo
/ morphOne
// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false
// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true
to-many relations: hasMany
/ belongsToMany
/ morphMany
/ morphToMany
/ morphedByMany
// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false
// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true
Try setting your ScriptManager to this.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
if you could set the height of the wrapping div of the content (#header-content as shown in other's reply), instead of the entire #header, maybe you can also try this approach:
HTML
<div id="header">
<h1>some title</h1>
<div id="header-content">
<span>
first line of header text<br>
second line of header text<br>
third, last line of header text
</span>
</div>
</div>
CSS
#header-content{
height:100px;
}
#header-content::before{
display:inline-block;
content:'';
height:100%;
vertical-align:bottom;
}
#header-content span{
display:inline-block;
}
Use the textarea
<textarea name="textarea" style="width:250px;height:150px;"></textarea>
don't leave any space between the opening and closing tags Or Else This will leave some empty lines or spaces.
Just use var = var1 var2
and it will automatically concatenate the vars var1
and var2
:
awk '{new_var=$1$2; print new_var}' file
You can put an space in between with:
awk '{new_var=$1" "$2; print new_var}' file
Which in fact is the same as using FS
, because it defaults to the space:
awk '{new_var=$1 FS $2; print new_var}' file
$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am
You can play around with it in ideone: http://ideone.com/4u2Aip
prefer struct, and it's what std::greater do
struct Compare {
bool operator()(Node const&, Node &) {}
}
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
this is the source code about wraps:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
This is probably due to your target server not having a valid SSL certificate.
You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:
You can use System.arraycopy
for either of these. Both of these are O(n), since they copy all but 1 element.
If you will be removing the first element often, consider using LinkedList
instead. You can use LinkedList.remove
, which is from the Queue
interface, for convenience. With LinkedList
, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator
to that position. However, accessing an arbitrary element by index is O(n).
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
if(jTextField1.getText().length()>=5)
{
jTextField1.setText(jTextField1.getText().substring(0, 4));
}
}
I have taken a jtextfield whose name is jTextField1, the code is in its key pressed event. I Have tested it and it works. And I am using the NetBeans IDE.
You can return multiple arrays and scalars from a function
function x()
{
$a=array("a","b","c");
$b=array("e","f");
return array('x',$a,$b);
}
list ($m,$n,$o)=x();
echo $m."\n";
print_r($n);
print_r($o);
The find
method returns a Cursor
instance, which allows you to iterate over all matching documents.
To get the first document that matches the given criteria you need to use find_one
. The result of find_one
is a dictionary.
You can always use the list
constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.
You should do that if you need to reuse the cursor and have a good reason not to use rewind()
Demo using find
:
>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
... print(doc) # or do something with the document
...
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}
Demo using find_one
:
>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
$("input[type=checkbox]").on("change", function() {
if (this.checked) {
//do your stuff
}
});
There are two easy and safe rules which work not only in sh
but also bash
.
This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.
'I'\''m a s@fe $tring which ends in newline
'
sed command: sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"
This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""
\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"
sed command: sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'
.
There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-]
, which can be left unescaped to keep it more readable
I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"
sed command: LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'
.
Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.
Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.
(You can easily validate the rules by reading the POSIX spec for sh
. For bash, check the reference manual linked by @AustinPhillips)
This is an old question but I thought i'd share my take on it as I feel it is somewhat simpler that other answers (good for bases from 2 to 36):
def intStr(n,base=10):
if n < 0 : return "-" + intStr(-n,base) # handle negatives
if n < base: return chr([48,55][n>9] + n) # 48 => "0"..., 65 => "A"...
return intStr(n//base,base) + intStr(n%base,base) # recurse for multiple digits
if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
return true;
}
You can do a reverse DNS lookup with host
, too. Just give it the IP address as an argument:
$ host 192.168.0.10
server10 has address 192.168.0.10
Here is what worked for me to solve part 1 of this question:
location / {
rewrite ^([^.]*[^/])$ $1/ permanent;
try_files $uri $uri/ /index.php =404;
include fastcgi_params;
fastcgi_pass php5-fpm-sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
}
rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.
try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.
fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.
HTML
<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>
Another way to do it:
testSpace.Style.Add("display", "none");
or
testSpace.Style["background-image"] = "url(images/foo.png)";
in vb.net you can do it this way:
testSpace.Style.Item("display") = "none"
An example where things could go wrong with Shell=True is shown here
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
Check the doc here: subprocess.call()
A difference not yet mentioned: size limit
void *malloc(size_t size)
can only allocate up to SIZE_MAX
.
void *calloc(size_t nmemb, size_t size);
can allocate up about SIZE_MAX*SIZE_MAX
.
This ability is not often used in many platforms with linear addressing. Such systems limit calloc()
with nmemb * size <= SIZE_MAX
.
Consider a type of 512 bytes called disk_sector
and code wants to use lots of sectors. Here, code can only use up to SIZE_MAX/sizeof disk_sector
sectors.
size_t count = SIZE_MAX/sizeof disk_sector;
disk_sector *p = malloc(count * sizeof *p);
Consider the following which allows an even larger allocation.
size_t count = something_in_the_range(SIZE_MAX/sizeof disk_sector + 1, SIZE_MAX)
disk_sector *p = calloc(count, sizeof *p);
Now if such a system can supply such a large allocation is another matter. Most today will not. Yet it has occurred for many years when SIZE_MAX
was 65535. Given Moore's law, suspect this will be occurring about 2030 with certain memory models with SIZE_MAX == 4294967295
and memory pools in the 100 of GBytes.
First i will give you Dangerous Permission List in Android M and Later version
Then give you example of how to request for permission in Android M and later version.
I ask user to WRITE_EXTERNAL_STORAGE permission.
First add permission in your android menifest file
Step 1 Declare requestcode
private static String TAG = "PermissionDemo";
private static final int REQUEST_WRITE_STORAGE = 112;
Step 2 Add this code when you want ask user for permission
//ask for the permission in android M
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission to record denied");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Permission to access the SD-CARD is required for this app to Download PDF.")
.setTitle("Permission required");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i(TAG, "Clicked");
makeRequest();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
makeRequest();
}
}
protected void makeRequest() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Step 3 Add override method for Request
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_WRITE_STORAGE: {
if (grantResults.length == 0
|| grantResults[0] !=
PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission has been denied by user");
} else {
Log.i(TAG, "Permission has been granted by user");
}
return;
}
}
}
Note: Do not forget to add permission in menifest file
BEST EXAMPLE BELOW WITH MULTIPLE PERMISSION PLUS COVER ALL SCENARIO
I added comments so you can easily understand.
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.production.hometech.busycoder.R;
import java.util.ArrayList;
public class PermissionInActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_PERMISSION_SETTING = 99;
private Button bt_camera;
private static final String[] PARAMS_TAKE_PHOTO = {
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int RESULT_PARAMS_TAKE_PHOTO = 11;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_in);
bt_camera = (Button) findViewById(R.id.bt_camera);
bt_camera.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_camera:
takePhoto();
break;
}
}
/**
* shouldShowRequestPermissionRationale() = This will return true if the user had previously declined to grant you permission
* NOTE : that ActivityCompat also has a backwards-compatible implementation of
* shouldShowRequestPermissionRationale(), so you can avoid your own API level
* checks.
* <p>
* shouldShowRequestPermissionRationale() = returns false if the user declined the permission and checked the checkbox to ask you to stop pestering the
* user.
* <p>
* requestPermissions() = request for the permisssiion
*/
private void takePhoto() {
if (canTakePhoto()) {
Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "You should give permission", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);
} else {
ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);
}
}
// This method return permission denied String[] so we can request again
private String[] netPermisssion(String[] wantedPermissions) {
ArrayList<String> result = new ArrayList<>();
for (String permission : wantedPermissions) {
if (!hasPermission(permission)) {
result.add(permission);
}
}
return (result.toArray(new String[result.size()]));
}
private boolean canTakePhoto() {
return (hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE));
}
/**
* checkSelfPermission() = you can check if you have been granted a runtime permission or not
* ex = ContextCompat.checkSelfPermission(this,permissionString)== PackageManager.PERMISSION_GRANTED
* <p>
* ContextCompat offers a backwards-compatible implementation of checkSelfPermission(), ActivityCompat offers a backwards-compatible
* implementation of requestPermissions() that you can use.
*
* @param permissionString
* @return
*/
private boolean hasPermission(String permissionString) {
return (ContextCompat.checkSelfPermission(this, permissionString) == PackageManager.PERMISSION_GRANTED);
}
/**
* requestPermissions() action goes to onRequestPermissionsResult() whether user can GARNT or DENIED those permisssions
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RESULT_PARAMS_TAKE_PHOTO) {
if (canTakePhoto()) {
Toast.makeText(this, "You can take picture", Toast.LENGTH_SHORT).show();
} else if (!(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
final AlertDialog.Builder settingDialog = new AlertDialog.Builder(PermissionInActivity.this);
settingDialog.setTitle("Permissioin");
settingDialog.setMessage("Now you need to enable permisssion from the setting because without permission this app won't run properly \n\n goto -> setting -> appInfo");
settingDialog.setCancelable(false);
settingDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getBaseContext(), "Go to Permissions to Grant all permission ENABLE", Toast.LENGTH_LONG).show();
}
});
settingDialog.show();
Toast.makeText(this, "You need to grant permission from setting", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PERMISSION_SETTING) {
if (canTakePhoto()) {
Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();
}
}
}
}
Special Case for Configuration change
It is possible that the user will rotate the device or otherwise trigger a configuration change while our permission dialog is in the foreground. Since our activity is still visible behind that dialog, we get destroyed and recreated… but we do not want to re-raise the permission dialog again.
That is why we have a boolean, named isInPermission, that tracks whether or not
we are in the middle of requesting permissions. We hold onto that value in
onSaveInstanceState()
:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}
We restore it in onCreate()
. If we do not hold all of the desired permissions, but isInPermission is true, we skip requesting the permissions, since we are in the
middle of doing so already.
If the main task is just to use the string in a URL, why not to use slugyfier?
composer require cocur/slugify
then
use Cocur\Slugify\Slugify;
$slugify = new Slugify();
echo $slugify->slugify('Fóø Bår');
It also has many bridges for popular frameworks. E.g. you can use Doctrine Extensions Sluggable behaviour to generate automatically unique slug for each entity in DB and use it in URL.
If you want just to wipe out all accents you can play around with rulesets to satisfy the requirements.
I had this issue as well, and quite a nice way to do it if you are within the same controller is to use named parameters:
return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
If you really need to specify all the .jar files dynamically you could use shell scripts, or Apache Ant. There's a commons project called Commons Launcher which basically lets you specify your startup script as an ant build file (if you see what I mean).
Then, you can specify something like:
<path id="base.class.path">
<pathelement path="${resources.dir}"/>
<fileset dir="${extensions.dir}" includes="*.jar" />
<fileset dir="${lib.dir}" includes="*.jar"/>
</path>
In your launch build file, which will launch your application with the correct classpath.
If you're repeating single characters like the OP, and the maximum number of repeats is not too high, then you could use a simple substring operation like this:
int i = 3;
String someNum = "123";
someNum += "00000000000000000000".substring(0, i);
If it's a DNS problem, you could try:
If this doesn't fix it, you could try editing the hosts file located here:
C:\Windows\System32\drivers\etc\hosts
And ensure that this line (and no other line referencing localhost) is in there:
127.0.0.1 localhost
As stated in the documentation, flutter prefer composition over parameters. Most of the time what you're looking for is not a property, but instead a wrapper (and sometimes a few helpers/"builder")
For borders what you want is DecoratedBox
, which has a decoration
property that defines borders ; but also background images or shadows.
Alternatively like @Aziza said, you can use Container
. Which is the combination of DecoratedBox
, SizedBox
and a few other useful widgets.
One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.
SELECT
v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE
I.InvoiceID IN
(SELECT iL.InvoiceSequence
FROM InvoiceLineItems
WHERE iL.InvoiceSequence > 1)
ORDER BY
V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
This might work for you:
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!
here is the modifed getFacebookUrl:
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
boolean activated = packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
if(activated){
if ((versionCode >= 3002850)) {
return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
} else {
return "fb://page/" + FACEBOOK_PAGE_ID;
}
}else{
return FACEBOOK_URL;
}
} catch (PackageManager.NameNotFoundException e) {
return FACEBOOK_URL;
}
}
The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
Combining the advice from MartinP and user664833, I was also able to get it to work. Caveat is that entering psql from the pgAdmin GUI tool via choosing Plugins...PSQL Console sets the credentials and permission level for the psql session, so you must have Admin or CRUD permissions on the table and maybe also Admin on the DB (do not know for sure on that). The command then in the psql console would take this form:
postgres=# \i driveletter:/folder_path/backupfilename.backup
where postgres=# is the psql prompt, not part of the command.
The .backup file will include the commands used to create the table, so you may also get things like "ALTER TABLE ..." commands in the file that get executed but reported as errors. I suppose you can always delete these commands before running the restore but you're probably better safe than sorry to keep them in there, as these will not likely cause the restore of data to fail. But always check to be sure the data you wanted to resore actually got there. (Sorry if this seems like patronizing advice to anyone, but it's an oversight that can happen to anyone no matter how long they have been at this stuff -- a moment's distraction from a colleague, a phone call, etc., and it's easy to forget this step. I have done it myself using other databases earlier in my career and wondered "Gee, why am I not seeing any data back from this query?" Answer was the data never actually got restored, and I just wasted 2 hours trying to hunt down suspected possible bugs that didn't exist.)
//create a variable that contain your button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
startActivity(intent);
}
});
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
swift 3.0
for width
UIScreen.main.bounds.size.width
for height
UIScreen.main.bounds.size.height
Two main steps involved are
1- Creating a C++ dll
In visual studio
New->Project->Class Library in c++ template. Name of project here is first_dll in
visual studio 2010. Now declare your function as public in first_dll.h file and
write the code in first_dll.cpp file as shown below.
Header File code
// first_dll.h
using namespace System;
namespace first_dll
{
public ref class Class1
{
public:
static double sum(int ,int );
// TODO: Add your methods for this class here.
};
}
Cpp File
//first_dll.cpp
#include "stdafx.h"
#include "first_dll.h"
namespace first_dll
{
double Class1:: sum(int x,int y)
{
return x+y;
}
}
Check This
**Project-> Properties -> Configuration/General -> Configuration Type**
this option should be Dynamic Library(.dll) and build the solution/project now.
first_dll.dll file is created in Debug folder
2- Linking it in C# project
Open C# project
Rightclick on project name in solution explorer -> Add -> References -> Browse to path
where first_dll.dll is created and add the file.
Add this line at top in C# project
Using first_dll;
Now function from dll can be accessed using below statement in some function
double var = Class1.sum(4,5);
I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.
Try adding
word-break: break-all
to the CSS on your table element.
That will get the words in the table cells to break such that the table does not grow wider than its containing div, yet the table columns are still sized dynamically. jsfiddle demo.
window.open ("http://www.javascript-coder.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");
from
http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
:]
As mentioned above (a quick way to do this) :
pip install IDLEX
Then I create a shortcut on Desktop (Win10) like this:
C:\Python\Python37\pythonw.exe "C:\Python\Python37\Scripts\idlex.pyw"
The paths may be different and need to be changed:
C:\Python\Python37
(Thanks for the great answers above)
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.
You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).
Using .Equals is also a lot easier to read.
I realize this is a several years old question, but...
On Access 2010
, you can use InStrRev()
to do this. Hope this helps.
To untrack a single file that has already been added/initialized to your repository, i.e., stop tracking the file but not delete it from your system use: git rm --cached filename
To untrack every file that is now in your .gitignore
:
First commit any outstanding code changes, and then, run this command:
git rm -r --cached .
This removes any changed files from the index(staging area), then just run:
git add .
Commit it:
git commit -m ".gitignore is now working"
To undo git rm --cached filename
, use git add filename
.
Make sure to commit all your important changes before running
git add .
Otherwise, you will lose any changes to other files.
Max value for array index is Integer.MAX_INT - it's around 2Gb (2^31 / 2 147 483 647). Your input stream can be bigger than 2Gb, so you have to process data in chunks, sorry.
InputStream is;
final byte[] buffer = new byte[512 * 1024 * 1024]; // 512Mb
while(true) {
final int read = is.read(buffer);
if ( read < 0 ) {
break;
}
// do processing
}
This link works with me: video
The answer posted before didn't work for me until the second click
So what I did is Directly call:
new NewForm().setVisible(true);
this.dispose();//to close the current jframe
I've just had a particular problem where I had to count the number of true statements from a logical vector and this worked best for me...
length(grep(TRUE, (gene.rep.matrix[i,1:6] > 1))) > 5
So This takes a subset of the gene.rep.matrix object, and applies a logical test, returning a logical vector. This vector is put as an argument to grep, which returns the locations of any TRUE entries. Length then calculates how many entries grep finds, thus giving the number of TRUE entries.
One difference is that:
:map
does nvo
== normal + (visual + select) + operator pending:map!
does ic
== insert + command-line modeas stated on help map-modes
tables.
So: map
does not map to all modes.
To map to all modes you need both :map
and :map!
.
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
Use $.ajax
to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the action
POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
I believe that's a simple incarnation of the Command pattern.
Same from above, bit more detailed
Using .Net Core
Controller
public class TestController : Controller
{
private string connectionString;
public IDbConnection Connection
{
get { return new SqlConnection(connectionString); }
}
public TestController()
{
connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
}
public JsonResult GetEventCategory(string q)
{
using (IDbConnection dbConnection = Connection)
{
var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
commandType: CommandType.StoredProcedure).FirstOrDefault();
return Json(categories);
}
}
public class ResultTokenInput
{
public int ID { get; set; }
public string name { get; set; }
}
}
Stored Procedure ( parent child relation )
create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
BEGIN
WITH CTE(Id, Name, IdHierarchy,parentId) AS
(
SELECT
e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
FROM
EventCategory e where e.Title like '%'+@keyword+'%'
-- WHERE
-- parentid = @parentid
UNION ALL
SELECT
p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
FROM
EventCategory p
JOIN CTE c ON c.Id = p.parentid
where p.Title like '%'+@keyword+'%'
)
SELECT
*
FROM
CTE
ORDER BY
IdHierarchy
References in case
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;
Try string.TrimEnd()
:
Something = Something.TrimEnd(',');
You can do this in 2 steps:
1: Change the input type(In your EditText
field) in the layout file to android:inputType="number"
2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());
You can use strpos()
or stripos()
to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.
Use the operators ===
or `!== to differ FALSE from 0 in PHP.
If you specifically want methods, you should use inspect.ismethod.
For method names:
import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
For the methods themselves:
import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
Sometimes inspect.isroutine
can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).
That's the easiest I could think of (TESTED) and it works!!
char message[50];
fgets(message, 50, stdin);
for( i = 0, j = 0; i < strlen(message); i++){
message[i-j] = message[i];
if(message[i] == ' ')
j++;
}
message[i] = '\0';
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
While Nate's answer is pretty good already, I'm going to expand on it more specifically for Visual Studio 2010 as requested, and include information on compiling in the various optional components which requires external libraries.
If you are using headers only libraries, then all you need to do is to unarchive the boost download and set up the environment variables. The instruction below set the environment variables for Visual Studio only, and not across the system as a whole. Note you only have to do it once.
C:\boost_1_47_0
).Microsoft.Cpp.<Platform>.user
, and select Properties
to open the Property Page for edit.VC++ Directories
on the left.Include Directories
section to include the path to your boost source files.If you want to use the part of boost that require building, but none of the features that requires external dependencies, then building it is fairly simple.
C:\boost_1_47_0
).bootstrap.bat
to build b2.exe (previously named bjam).Run b2:
b2 --toolset=msvc-10.0 --build-type=complete stage
; b2 --toolset=msvc-10.0 --build-type=complete architecture=x86 address-model=64 stage
Go for a walk / watch a movie or 2 / ....
Library Directories
section to include the path to your boost libraries output. (The default for the example and instructions above would be C:\boost_1_47_0\stage\lib
. Rename and move the directory first if you want to have x86 & x64 side by side (such as to <BOOST_PATH>\lib\x86
& <BOOST_PATH>\lib\x64
).If you want the optional components, then you have more work to do. These are:
Boost.IOStreams Bzip2 filters:
C:\bzip2-1.0.6
).-sBZIP2_SOURCE="C:\bzip2-1.0.6"
when running b2 in step 5.Boost.IOStreams Zlib filters
C:\zlib-1.2.5
).-sZLIB_SOURCE="C:\zlib-1.2.5"
when running b2 in step 5.Boost.MPI
project-config.jam
in the directory <BOOST_PATH>
that resulted from running bootstrap. Add in a line that read using mpi ;
(note the space before the ';').Boost.Python
To completely built the 32-bits version of the library requires 32-bits Python, and similarly for the 64-bits version. If you have multiple versions installed for such reason, you'll need to tell b2 where to find specific version and when to use which one. One way to do that would be to edit the file project-config.jam
in the directory <BOOST_PATH>
that resulted from running bootstrap. Add in the following two lines adjusting as appropriate for your Python installation paths & versions (note the space before the ';').
using python : 2.6 : C:\\Python\\Python26\\python ;
using python : 2.6 : C:\\Python\\Python26-x64\\python : : : <address-model>64 ;
Do note that such explicit Python specification currently cause MPI build to fail. So you'll need to do some separate building with and without specification to build everything if you're building MPI as well.
Follow the second set of instructions above to build boost.
Boost.Regex ICU support
C:\icu4c-4_8
).<ICU_PATH>\source\allinone
.-sICU_PATH="C:\icu4c-4_8"
when running b2 in step 5.The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:
=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel
and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
See this Codepen link for faster and easy way of checking an element if it has a specific class using vanilla JavaScript~!
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
If you're in control of the string, you could also use a 'Raw' string type:
>>> string = r"abcd\n"
>>> print(string)
abcd\n
Using spring boot you will no need to build configuration. This will have done automatically when you create project.
If you use spring MVC you need to build configuration yourself. It is more complicated, but it is crucial.
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
##Configuring credential.helper
On OS X (now macOS), run this in Terminal:
git config --global credential.helper osxkeychain
It enables Git to use file Keychain.app to store username and password and to retrieve the passphrase to your private SSH key from the keychain.
For Windows use:
git config --global credential.helper wincred
For Linux use:
git config --global credential.helper cache // If you want to cache the credentials for some time (default 15 minutes)
OR
git config --global credential.helper store // if you want to store the credentials for ever (considered unsafe)
Note : The first method will cache the credentials in memory, whereas the second will store them in ~/.git-credentials
in plain text format.
Check here for more info about Linux method.
Check here for more info about all three.
##Troubleshooting
If the Git credential helper is configured correctly macOS saves the passphrase in the keychain. Sometimes the connection between SSH and the passphrases stored in the keychain can break. Run ssh-add -K
or ssh-add ~/.ssh/id_rsa
to add the key to keychain again.
For macOS v10.12 (Sierra), ssh-add -K
needs to be run after every reboot. To avoid this, create ~/.ssh/config
with this content.
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
From the ssh_config
man
page on 10.12.2:
UseKeychain
On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be 'yes' or 'no'. The default is 'no'.
Apple has added Technote 2449 which explains what happened.
Prior to macOS Sierra,
ssh
would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.
Here is an algorithm I just build, which will split a String
by any Character
from the array and if there is any desire to keep the substrings with splitted characters one could set the swallow
parameter to true
.
Xcode 7.3 - Swift 2.2:
extension String {
func splitBy(characters: [Character], swallow: Bool = false) -> [String] {
var substring = ""
var array = [String]()
var index = 0
for character in self.characters {
if let lastCharacter = substring.characters.last {
// swallow same characters
if lastCharacter == character {
substring.append(character)
} else {
var shouldSplit = false
// check if we need to split already
for splitCharacter in characters {
// slit if the last character is from split characters or the current one
if character == splitCharacter || lastCharacter == splitCharacter {
shouldSplit = true
break
}
}
if shouldSplit {
array.append(substring)
substring = String(character)
} else /* swallow characters that do not equal any of the split characters */ {
substring.append(character)
}
}
} else /* should be the first iteration */ {
substring.append(character)
}
index += 1
// add last substring to the array
if index == self.characters.count {
array.append(substring)
}
}
return array.filter {
if swallow {
return true
} else {
for splitCharacter in characters {
if $0.characters.contains(splitCharacter) {
return false
}
}
return true
}
}
}
}
Example:
"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]
Override the paintComponent method of your panel so you can custom draw. Like this:
@Override
public void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
//now do the drawing here
...
}
If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:
Both Jonathan and Charles are right... you've got to stop the service first, then uninstall/reinstall. Combining their two answers makes the perfect batch file or PowerShell script.
I will make mention of a caution learned the hard way -- Windows 2000 Server (possibly the client OS as well) will require a reboot before the reinstall no matter what. There must be a registry key that is not fully cleared until the box is rebooted. Windows Server 2003, Windows XP and later OS versions do not suffer that pain.
I prefer an old-school editing setup. I use command-line vim embedded in a GNU Screen "window" inside of iTerm.
This may not integrate well with XCode, but I think it works great for developing and using command-line programs. If you spend any significant time working in a terminal, GNU Screen is worth the 30 minutes it takes to master the basic terminal multiplexing concepts.
A temp table can be created in the caller and then populated from the called SP.
create table #GetValuesOutputTable(
...
);
exec GetValues; -- populates #GetValuesOutputTable
select * from #GetValuesOutputTable;
Some advantages of this approach over the "insert exec" is that it can be nested and that it can be used as input or output.
Some disadvantages are that the "argument" is not public, the table creation exists within each caller, and that the name of the table could collide with other temp objects. It helps when the temp table name closely matches the SP name and follows some convention.
Taking it a bit farther, for output only temp tables, the insert-exec approach and the temp table approach can be supported simultaneously by the called SP. This doesn't help too much for chaining SP's because the table still need to be defined in the caller but can help to simplify testing from the cmd line or when calling externally.
-- The "called" SP
declare
@returnAsSelect bit = 0;
if object_id('tempdb..#GetValuesOutputTable') is null
begin
set @returnAsSelect = 1;
create table #GetValuesOutputTable(
...
);
end
-- populate the table
if @returnAsSelect = 1
select * from #GetValuesOutputTable;
Just do this
props.history.push('/link')
this.props.history.push('/link')
Example:
<button onClick={()=>{props.history.push('/link')}} >Press</button>
react-router-dom: 5.2.0,
react: 16.12.0
My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.
$(function() {
callPlayer($('#iframe')[0], 'unMute');
});
function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}
Below is a slightly improved version of Dídac Pérez's answer, with both directions implemented, along with a demo of these functions' usages using unsigned char and unsigned long long values. Several notes:
cout << +value
trick for tersely outputting an unsigned char numerically that I found here: https://stackoverflow.com/a/28414758/1599699<put the type here>
syntax for clarity and safety.The result of a shift operation is undefined if additive-expression is negative or if additive-expression is greater than or equal to the number of bits in the (promoted) shift-expression.
Here's the code I'm using:
#include <iostream>
using namespace std;
template <typename T>
inline T rotateAndCarryLeft(T rotateMe, unsigned char shiftNum)
{
static const unsigned char TBitCount = sizeof(T) * 8U;
return (rotateMe << shiftNum) | (rotateMe >> (TBitCount - shiftNum));
}
template <typename T>
inline T rotateAndCarryRight(T rotateMe, unsigned char shiftNum)
{
static const unsigned char TBitCount = sizeof(T) * 8U;
return (rotateMe >> shiftNum) | (rotateMe << (TBitCount - shiftNum));
}
void main()
{
//00010100 == (unsigned char)20U
//00000101 == (unsigned char)5U == rotateAndCarryLeft(20U, 6U)
//01010000 == (unsigned char)80U == rotateAndCarryRight(20U, 6U)
cout << "unsigned char " << 20U << " rotated left by 6 bits == " << +rotateAndCarryLeft<unsigned char>(20U, 6U) << "\n";
cout << "unsigned char " << 20U << " rotated right by 6 bits == " << +rotateAndCarryRight<unsigned char>(20U, 6U) << "\n";
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned char) * 8U; ++shiftNum)
{
cout << "unsigned char " << 21U << " rotated left by " << +shiftNum << " bit(s) == " << +rotateAndCarryLeft<unsigned char>(21U, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned char) * 8U; ++shiftNum)
{
cout << "unsigned char " << 21U << " rotated right by " << +shiftNum << " bit(s) == " << +rotateAndCarryRight<unsigned char>(21U, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned long long) * 8U; ++shiftNum)
{
cout << "unsigned long long " << 3457347ULL << " rotated left by " << +shiftNum << " bit(s) == " << rotateAndCarryLeft<unsigned long long>(3457347ULL, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned long long) * 8U; ++shiftNum)
{
cout << "unsigned long long " << 3457347ULL << " rotated right by " << +shiftNum << " bit(s) == " << rotateAndCarryRight<unsigned long long>(3457347ULL, shiftNum) << "\n";
}
cout << "\n\n";
system("pause");
}
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: '[email protected]',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: '[email protected]',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
If you're using the command-line tools, running git --version
should give you the version number.
If you want to change the name of the current branch, run:
git branch -m [old_branch] [new_branch]
If you want to delete the old remote branch, run:
git push origin :[old_branch]
If you want to delete the old remote branch and create a new remote branch, run:
git push origin :old_branch new_branch
I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)
git reset --hard origin
This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.
git reset --hard origin/<branch>
I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.
function sessionexists(){
if(!empty($_SESSION)){
return true;
}else{
return false;
}
}
if (!sessionexists()){
redirect("https://www.yoursite.com/");
exit();
}else{call_user_func('check_the_page');
}
Also, there was just a typo in your original post.
'min:2|max5'
should have been 'min:2|max:5'
.
Notice the ":" for the "max" rule.
If you control the input data, you can use the mini version
package main
import (
"testing"
"strconv"
)
func Atoi (s string) int {
var (
n uint64
i int
v byte
)
for ; i < len(s); i++ {
d := s[i]
if '0' <= d && d <= '9' {
v = d - '0'
} else if 'a' <= d && d <= 'z' {
v = d - 'a' + 10
} else if 'A' <= d && d <= 'Z' {
v = d - 'A' + 10
} else {
n = 0; break
}
n *= uint64(10)
n += uint64(v)
}
return int(n)
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in := Atoi("9999")
_ = in
}
}
func BenchmarkStrconvAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in, _ := strconv.Atoi("9999")
_ = in
}
}
the fastest option (write your check if necessary). Result :
Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2 100000000 14.6 ns/op
BenchmarkStrconvAtoi-2 30000000 51.2 ns/op
PASS
ok path 3.293s
String localFormat = android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE MMMM d");
return new SimpleDateFormat(localFormat, Locale.getDefault()).format(localMidnight);
will return a format based on device's language. Note that getBestDateTimePattern() returns "the best possible localized form of the given skeleton for the given locale"
Delete this is legal as long as object is in heap. You would need to require object to be heap only. The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion
Instead use use appendTo
. append
or appendTo
returns a jQuery object so you don't have to wrap it inside $()
.
var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');
.appendTo()
reference: http://api.jquery.com/appendTo/
Alernatively you can try this also.
$('<div />', { id: 'holdy' }).appendTo('body');
^
(Here you can specify any attribute/value pair you want)
For such you must rely on VBA. You can't do it just with Excel functions.
For completeness' sake, here's the way to do it with arrow
(better dates and times for Python):
sometime = arrow.now()
abitlater = sometime.shift(seconds=3)
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
I used to do this a lot when I worked with Classic ASP. Usually I used it when server-side validation was needed of some sort for the input (before the days of AJAX). The main draw back I see is that it doesn't separate programming logic from the presentation, at the file level.
There is no need to install Poppler on your OS. This will work:
pip install Wand
from wand.image import Image
f = "somefile.pdf"
with(Image(filename=f, resolution=120)) as source:
for i, image in enumerate(source.sequence):
newfilename = f[:-4] + str(i + 1) + '.jpeg'
Image(image).save(filename=newfilename)
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
The array is being re-indexed when you do a .splice()
, which means you'll skip over an index when one is removed, and your cached .length
is obsolete.
To fix it, you'd either need to decrement i
after a .splice()
, or simply iterate in reverse...
var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}
This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.
To resolve this problem, you can try this.
first, you have found out your pg_hba.conf by:
cd /etc/postgresql/9.5/main from your root directory
and open file using
sudo nano pg_hba.conf
then add this line:
local all all md5
to your pg_hba.conf and then restart by using the command:
sudo service postgresql restart
I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:
<android:theme="@android:style/Theme.NoTitleBar">
Just add it to your application
tag to apply it app-wide.
I found that next time when you need to look up these information. Instead of opening a browser and google it, you could just type call /?
in your cmd and you'll get it:
...
%* in a batch script refers to all the arguments (e.g. %1 %2 %3
%4 %5 ...)
Substitution of batch parameters (%n) has been enhanced. You can
now use the following optional syntax:
%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file
%~$PATH:1 - searches the directories listed in the PATH
environment variable and expands %1 to the fully
qualified name of the first one found. If the
environment variable name is not defined or the
file is not found by the search, then this
modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dp1 - expands %1 to a drive letter and path only
%~nx1 - expands %1 to a file name and extension only
%~dp$PATH:1 - searches the directories listed in the PATH
environment variable for %1 and expands to the
drive letter and path of the first one found.
%~ftza1 - expands %1 to a DIR like output line
In the above examples %1 and PATH can be replaced by other
valid values. The %~ syntax is terminated by a valid argument
number. The %~ modifiers may not be used with %*
In SciPy >= 0.11
import numpy as np
from scipy.signal import argrelextrema
x = np.random.random(12)
# for local maxima
argrelextrema(x, np.greater)
# for local minima
argrelextrema(x, np.less)
Produces
>>> x
array([ 0.56660112, 0.76309473, 0.69597908, 0.38260156, 0.24346445,
0.56021785, 0.24109326, 0.41884061, 0.35461957, 0.54398472,
0.59572658, 0.92377974])
>>> argrelextrema(x, np.greater)
(array([1, 5, 7]),)
>>> argrelextrema(x, np.less)
(array([4, 6, 8]),)
Note, these are the indices of x that are local max/min. To get the values, try:
>>> x[argrelextrema(x, np.greater)[0]]
scipy.signal
also provides argrelmax
and argrelmin
for finding maxima and minima respectively.
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
In order to check the maximum allowed connections, you can run the following query:
SHOW VARIABLES LIKE "max_connections";
To check the number of active connections, you can run the following query:
SHOW VARIABLES LIKE "max_used_connections";
Hope it helps.
You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:
auto f()
{
struct S
{
int a;
double b;
} s;
s.a = 42;
s.b = 42.0;
return s;
}
auto x = f();
a = x.a;
b = x.b;
As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives
wrap the first searched character in a character class
ps -ef | grep '[t]omcat'
This searches for tomcat too, but misses the grep [t]omcat
entry, because it isn't matched by [t]omcat
.
use a custom output format with ps
ps -e -o pid,comm | grep tomcat
This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep
and not as grep tomcat
.
First try this in your Windows cmd window:
pip3 install pyqt5
If that is successful, it will look something like this:
C:\Windows\System32>pip3 install pyqt5
Collecting pyqt5
Downloading PyQt5-5.9-5.9.1-cp35.cp36.cp37-none-win_amd64.whl (77.2MB)
100% |################################| 77.2MB 13kB/s
Collecting sip<4.20,>=4.19.3 (from pyqt5)
Downloading sip-4.19.3-cp35-none-win_amd64.whl (49kB)
100% |################################| 51kB 984kB/s
Installing collected packages: sip, pyqt5
Successfully installed pyqt5-5.9 sip-4.19.3
If that did not work, you might try this link from SourceForge.
PyQt5 .exe installers for Windows
How to find the installer that's right for you?
First, determine what version of Python you have and whether you have 32-bit or 64-bit Python. Next, open one of the directories. I'm on Python 3.5 64-bit so I'm looking for a .exe with those specs. When you open a directory on SourceForge, you will see some directories with ONLY .zip or .tar.gz. That's not what you're looking for. A good indication of which directory you should click is given by the "Downloads/Week" column. I'll open the PyQt-5.6 directory in my case.
Here we notice some .exe files:
PyQt-5.6
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x32-2.exe
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
|_PyQt5_gpl-5.6.zip
|_PyQt5_gpl-5.6.tar.gz
I know these are Python 3.5 by Py3.5
in the file name. I am also looking for the 64-bit version so I'll download PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
. Final answer!
Note: if you try to install a version that's not compatible with your system, a dialog box will appear immediately after running the .exe. That's an indication that you've chosen the wrong one. I'm not trying to sound like a dbag... I did that several times!
To test a successful install, in your Python interpreter, try to import:
from PyQt5 import QtCore, QtGui, QtWidgets
After returning from a function, all identifiers are destroyed instead of kept values in a memory location and we can not locate the values without having an identifier.But that location still contains the value stored by previous function.
So, here function foo()
is returning the address of a
and a
is destroyed after returning its address. And you can access the modified value through that returned address.
Let me take a real world example:
Suppose a man hides money at a location and tells you the location. After some time, the man who had told you the money location dies. But still you have the access of that hidden money.
Ok, it seems that some versions of PHP have a limitation of length of GET params:
Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.
To add support for long parameters with suhosin, add
suhosin.get.max_value_length = <limit>
inphp.ini
Source: http://www.php.net/manual/en/reserved.variables.get.php#101469
As According to me while you are using setOnTouchListener om parent or child stop the scrolling of parent as you touch on child else stop scrolling of child as you touch on parent
General sibling combinator
The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.
The following should work for you:
[\n\r].*Object Name:\s*([^\n\r]*)
Your desired match will be in capture group 1.
[\n\r][ \t]*Object Name:[ \t]*([^\n\r]*)
Would be similar but not allow for things such as " blah Object Name: blah" and also make sure that not to capture the next line if there is no actual content after "Object Name:"
It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value is encountered. See this link.
Here is the relevant portion that pertains to the Warning notice you are getting:
New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.
I'm guessing either $item['quantity'] or $product['price'] does not contain a numeric value, so make sure that they do before trying to multiply them. Maybe use some sort of conditional before calculating the $sub_total, like so:
<?php
if (is_numeric($item['quantity']) && is_numeric($product['price'])) {
$sub_total += ($item['quantity'] * $product['price']);
} else {
// do some error handling...
}
Edit:
I benchmarked my original solution against other solutions suggests here and found that it is very inefficient.
The benchmark itself is very interesting (link) It compares 3 solutions (higher is better):
- @fregante (formerly called @bfred.it) solution, which adds values one by one (14,955 op/sec)
- @jameslk's solution, which uses a self invoking generator (5,089 op/sec)
- my own, which uses reduce & spread (3,434 op/sec)
As you can see, @fregante's solution is definitely the winner.
Performance + Immutability
With that in mind, here's a slightly modified version which doesn't mutates the original set and excepts a variable number of iterables to combine as arguments:
function union(...iterables) { const set = new Set(); for (const iterable of iterables) { for (const item of iterable) { set.add(item); } } return set; }
Usage:
const a = new Set([1, 2, 3]); const b = new Set([1, 3, 5]); const c = new Set([4, 5, 6]); union(a,b,c) // {1, 2, 3, 4, 5, 6}
I would like to suggest another approach, using reduce
and the spread
operator:
function union (sets) {
return sets.reduce((combined, list) => {
return new Set([...combined, ...list]);
}, new Set());
}
Usage:
const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);
union([a, b, c]) // {1, 2, 3, 4, 5, 6}
Tip:
We can also make use of the rest
operator to make the interface a bit nicer:
function union (...sets) {
return sets.reduce((combined, list) => {
return new Set([...combined, ...list]);
}, new Set());
}
Now, instead of passing an array of sets, we can pass an arbitrary number of arguments of sets:
union(a, b, c) // {1, 2, 3, 4, 5, 6}
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout
value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.
For example:
// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;
This value can also be configured in your web.config
file in the httpRuntime
configuration element:
<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300"
... other configuration attributes ...
/>
Please note according to the MSDN documentation:
"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."
If you've already done this but are finding that your session is expiring then increase the
ASP.NET HttpSessionState.Timeout
value:
For example:
// Increase session timeout to thirty minutes
Session.Timeout = 30;
This value can also be configured in your web.config
file in the sessionState
configuration element:
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.
The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.
I found this question looking for a way to do the same thing for my Javascript tests, using Protractor (a javascript frontend to Selenium.)
My solution with protractor 1.2.0 and webdriver 2.1:
browser.actions()
.mouseMove(
element(by.css('.material-dialog-container'))
)
.click()
.perform();
This also accepts an offset (i'm using it to click above and left of an element:)
browser.actions()
.mouseMove(
element(by.css('.material-dialog-container'))
, -20, -20 // pixel offset from top left
)
.click()
.perform();
You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking
In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))
In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]:
A B C D
12 0.491683 0.137766 0.859753 -1.041487
13 0.376200 0.575667 1.534179 1.247358
14 0.428739 1.539973 1.057848 -1.254489
In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]:
A 3
B 3
C 3
D 3
dtype: int64
In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3
None of these answers solved my problem, which was that the items weren't the same width in my makeshift flexbox table when it was shrunk to a width too small.
The solution for me was simply to put overflow: hidden;
on the flex-grow: 1;
cells.
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
The only viable solution in my opinion is to use
ID INT IDENTITY(1,1)
column to get SQL Server to handle the automatic increment of your numeric valueSo try this:
CREATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers
without specifying values for ID
or UserID
:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID
value, and UserID
will contain values like UID00000001
, UID00000002
,...... and so on - automatically, safely, reliably, no duplicates.
Update: the column UserID
is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:
In Internet Explorer, this solution does not work in ssl.
One can see the error in console as:
SEC7111: HTTPS security is compromised by this,
Workaround : As one of the user here suggested replace chart.apis.google.com to chart.googleapis.com for the URL path to avoid SSL error.
Specifically, to install the pdf.js plugin for firefox, you do not use the app store. Instead, go to addons.mozilla.org from inside mozilla and install it from there. Also, to see if it's installed properly, go to the menu Tools:Add-ons (not the "about:plugins" url as you might think from the desktop version).
(New account, otherwise I'd put this as a comment on the answer above)
It's not enough just to rotate the page content. Here is a right CSS which work in the most browsers (Chrome, Firefox, IE9+).
First set body margin
to 0, because otherwise page margins will be larger than those you set in the print dialog. Also set background
color to visualize pages.
body {
margin: 0;
background: #CCCCCC;
}
margin
, border
and background
are required to visualize pages.
padding
must be set to the required print margin. In the print dialog you must set the same margins (10mm in this example).
div.portrait, div.landscape {
margin: 10px auto;
padding: 10mm;
border: solid 1px black;
overflow: hidden;
page-break-after: always;
background: white;
}
The size of A4 page is 210mm x 297mm. You need to subtract print margins from the size. And set the size of page's content:
div.portrait {
width: 190mm;
height: 276mm;
}
div.landscape {
width: 276mm;
height: 190mm;
}
I use 276mm instead of 277mm, because different browsers scale pages a little bit differently. So some of them will print 277mm-height content on two pages. The second page will be empty. It's more safe to use 276mm.
We don't need any margin
, border
, padding
, background
on the printed page, so remove them:
@media print {
body {
background: none;
-ms-zoom: 1.665;
}
div.portrait, div.landscape {
margin: 0;
padding: 0;
border: none;
background: none;
}
div.landscape {
transform: rotate(270deg) translate(-276mm, 0);
transform-origin: 0 0;
}
}
Note that the origin of transformation is 0 0
! Also the content of landscape pages must be moved 276mm down!
Also if you have a mix of portrait and lanscape pages IE will zoom out the pages. We fix it by setting -ms-zoom
to 1.665. If you'll set it to 1.6666 or something like this the right border of the page content may be cropped sometimes.
If you need IE8- or other old browsers support you can use -webkit-transform
, -moz-transform
, filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3)
. But for modern enough browsers it's not required.
Here is a test page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
...Copy all styles here...
</style>
</head>
<body>
<div class="portrait">A portrait page</div>
<div class="landscape">A landscape page</div>
</body>
</html>
<input type="text" name="whatever" id="funkystyling" />
Here's the CSS for the image on the left:
#funkystyling {
background: white url(/path/to/icon.png) left no-repeat;
padding-left: 17px;
}
And here's the CSS for the image on the right:
#funkystyling {
background: white url(/path/to/icon.png) right no-repeat;
padding-right: 17px;
}
while installing python packages in a global environment is doable, it is a best practice to isolate the environment between projects (creating virtual environments). Otherwise, confusion between Python versions will arise, just like your problem.
The simplest method is to use venv
library in the project directory:
python3 -m venv venv
Where the first venv
is to call the venv
package, and the second venv
defines the virtual environment directory name.
Then activate the virtual environment:
source venv/bin/activate
Once the virtual environment has been activated, your pip install ...
commands would not be interfered with any other Python version or pip version anymore.
For installing requests
:
pip install requests
Another benefit of the virtual environment is to have a concise list of libraries needed for that specific project.
*note: commands only work on Linux and Mac OS