Use like this:
if( $('#foo').is(':visible') ) {
// it's visible, do something
}
else {
// it's not visible so do something else
}
Hope it helps!
SELECT DAY(SUBDATE(ADDDATE(CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-1'), INTERVAL 1 MONTH), INTERVAL 1 DAY))
Nice 'n' Simple and does not require creating any functions
After reading this post some time ago I was wondering if it was safe to use domains for exception handling on an api / function level. I wanted to use them to simplify exception handling code in each async function I wrote. My concern was that using a new domain for each function would introduce significant overhead. My homework seems to indicate that there is minimal overhead and that performance is actually better with domains than with try catch in some situations.
http://www.lighthouselogic.com/#/using-a-new-domain-for-each-async-function-in-node/
Use Controls
object
For i = 1 To X
Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
Using dlpyr::mutate
and forcats::fct_recode
:
library(dplyr)
library(forcats)
iris <- iris %>%
mutate(Species = fct_recode(Species,
"Virginica" = "virginica",
"Versicolor" = "versicolor"
))
iris %>%
count(Species)
# A tibble: 3 x 2
Species n
<fctr> <int>
1 setosa 50
2 Versicolor 50
3 Virginica 50
The answer is due to the fact that Google Chrome uses an SQLite file to save cookies. It resides under:
C:\Users\<your_username>\AppData\Local\Google\Chrome\User Data\Default\
inside Cookies
file. (which is an SQLite database file)
So it's not a file stored on hard drive but a row in an SQLite database file which can be read by a third party program such as: SQLite Database Browser
EDIT: Thanks to @Chexpir, it is also good to know that the values are stored encrypted.
Here is a .NET solution that worked for me:
Download PhantomJS at http://phantomjs.org/download.html.
Copy the .exe file from the bin folder in the download folder and paste it to the bin debug/release folder of your Visual Studio project.
Add this using
using OpenQA.Selenium.PhantomJS;
In your code, open the driver like this:
PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
// Your code here
}
You could find disk intensive full table scans with something like this:
SELECT Disk_Reads DiskReads, Executions, SQL_ID, SQL_Text SQLText,
SQL_FullText SQLFullText
FROM
(
SELECT Disk_Reads, Executions, SQL_ID, LTRIM(SQL_Text) SQL_Text,
SQL_FullText, Operation, Options,
Row_Number() OVER
(Partition By sql_text ORDER BY Disk_Reads * Executions DESC)
KeepHighSQL
FROM
(
SELECT Avg(Disk_Reads) OVER (Partition By sql_text) Disk_Reads,
Max(Executions) OVER (Partition By sql_text) Executions,
t.SQL_ID, sql_text, sql_fulltext, p.operation,p.options
FROM v$sql t, v$sql_plan p
WHERE t.hash_value=p.hash_value AND p.operation='TABLE ACCESS'
AND p.options='FULL' AND p.object_owner NOT IN ('SYS','SYSTEM')
AND t.Executions > 1
)
ORDER BY DISK_READS * EXECUTIONS DESC
)
WHERE KeepHighSQL = 1
AND rownum <=5;
You can do it this way inside a program:
#include <sys/resource.h>
// core dumps may be disallowed by parent of this process; change that
struct rlimit core_limits;
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limits);
Unpack it where ever you like. In Android Studio under Settings is category Gradle where you can specify external gradle location if you want. It probably makes sense to put gradle bin folder into your path.
As addition to other answers, @JsonProperty
annotation is really important if you use the @JsonCreator
annotation in classes which do not have a no-arg constructor.
public class ClassToSerialize {
public enum MyEnum {
FIRST,SECOND,THIRD
}
public String stringValue = "ABCD";
public MyEnum myEnum;
@JsonCreator
public ClassToSerialize(MyEnum myEnum) {
this.myEnum = myEnum;
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ClassToSerialize classToSerialize = new ClassToSerialize(MyEnum.FIRST);
String jsonString = mapper.writeValueAsString(classToSerialize);
System.out.println(jsonString);
ClassToSerialize deserialized = mapper.readValue(jsonString, ClassToSerialize.class);
System.out.println("StringValue: " + deserialized.stringValue);
System.out.println("MyEnum: " + deserialized.myEnum);
}
}
In this example the only constructor is marked as @JsonCreator
, therefore Jackson will use this constructor to create the instance. But the output is like:
Serialized: {"stringValue":"ABCD","myEnum":"FIRST"}
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of ClassToSerialize$MyEnum from String value 'stringValue': value not one of declared Enum instance names: [FIRST, SECOND, THIRD]
But after the addition of the @JsonProperty
annotation in the constructor:
@JsonCreator
public ClassToSerialize(@JsonProperty("myEnum") MyEnum myEnum) {
this.myEnum = myEnum;
}
The deserialization is successful:
Serialized: {"myEnum":"FIRST","stringValue":"ABCD"}
StringValue: ABCD
MyEnum: FIRST
Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...
I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.
It's pretty quick, in Notepad++:
You should easily find the wrong character(s)
function sort_unique(arr) {
return arr.sort().filter(function(el,i,a) {
return (i==a.indexOf(el));
});
}
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
You can simply use decimal.ToString()
For two decimals
myDecimal.ToString("0.00");
For four decimals
myDecimal.ToString("0.0000");
This gives dot as decimal separator, and no thousand separator regardless of culture.
when using the class in constraints it's mean you can only use Reference type, another thing to add is when to use the constraint new(), it's must be the last thing you write in the Constraints terms.
Of course the method numbers()
returns an array, it's just that you're doing nothing with it. Try this in main()
:
int[] array = numbers(); // obtain the array
System.out.println(Arrays.toString(array)); // now print it
That will show the array in the console.
This is how I do it:
with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
stripped = (line.strip() for line in infile)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(outfile)
writer.writerows(lines)
Hope it helps!
I like very simple solutions, here is the one more
<p>hello <span>How are you</span></p>
and css
p {
display: flex;
flex-direction: column;
}
If one want to make executable hello.py
first find the path where python is in your os with : which python
it usually resides under "/usr/bin/python" folder.
at the very first line of hello.py
one should add : #!/usr/bin/python
then through linux command chmod
one should just make it executable like : chmod +x hello.py
and execute with ./hello.py
I got it work by setting size to freeform
My guess is the best you can come up with is
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
: planRec.approved_by.ToString();
Of course since you're hinting at the fact that approved_by
is an object
(which cannot equal ""), this would be rewritten as
this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.
$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"
Note: No need to delete the user from Keychain .
Google now allows to hide the Badge, from the FAQ :
I'd like to hide the reCAPTCHA v3 badge. What is allowed?
You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text: This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.
For example:
So you can simply hide it using the following CSS :
.grecaptcha-badge {
visibility: hidden;
}
Do not use display: none;
as it appears to disable the spam checking (thanks @Zade)
As mentioned in other answers, all of the following will work for the standard string-based syntax.
WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds
There is also an alternative method of passing it a DATETIME
value. You might think I'm confusing this with WAITFOR TIME
, but it also works for WAITFOR DELAY
.
Considerations for passing DATETIME
:
'1900-01-01'
).DATETIME
than to properly format a VARCHAR
.How to wait for 2 seconds:
--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1
--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2
A note on waiting for TIME
vs DELAY
:
Have you ever noticed that if you accidentally pass WAITFOR TIME
a date that already passed, even by just a second, it will never return? Check it out:
--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER
Unfortunately, WAITFOR DELAY
will do the same thing if you pass it a negative DATETIME
value (yes, that's a thing).
--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER
However, I would still recommend using WAITFOR DELAY
over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR
statement.
Using the fileProvider is the way to go. But you can use this simple workaround:
WARNING: It will be fixed in next Android release - https://issuetracker.google.com/issues/37122890#comment4
replace:
startActivity(intent);
by
startActivity(Intent.createChooser(intent, "Your title"));
You should be able to put them in your ~/matlab on unix.
I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath
from the matlab command line.
Anything program with tree or graph data structures will likely have some recursion.
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
There is no way to do this with CSS, you could use PHP or Javascript for this.
PHP example:
$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps
jQuery example (it's a plugin now!):
// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
return this.each(function(){
var val = $(this).text(), newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
}
$(this).text(newVal);
});
}
$('a.link').ucwords();?
your fadeIn()
function calls the fadeOut()
function, which calls the fadeIn()
function again. the recursion is in the JS.
git push --all
is the canonical way to push everything to a new bare repository.
Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with
git clone --bare
then use
git remote add origin <new-remote-repo>
in the original (non-bare) repository.
The below worked for me
From access help:
Stop Disabled Mode from blocking a query If you try to run an append query and it seems like nothing happens, check the Access status bar for the following message:
This action or event has been blocked by Disabled Mode.
To stop Disabled Mode from blocking the query, you must enable the database content. You use the Options button in the Message Bar to enable the query.
Enable the append query In the Message Bar, click Options. In the Microsoft Office Security Options dialog box, click Enable this content, and then click OK. If you don't see the Message Bar, it may be hidden. You can show it, unless it has also been disabled. If the Message Bar has been disabled, you can enable it.
Show the Message Bar If the Message Bar is already visible, you can skip this step.
On the Database Tools tab, in the Show/Hide group, select the Message Bar check box. If the Message Bar check box is disabled, you will have to enable it.
Enable the Message Bar If the Message Bar check box is enabled, you can skip this step.
Click the Microsoft Office Button , and then click Access Options. In the left pane of the Access Options dialog box, click Trust Center. In the right pane, under Microsoft Office Access Trust Center, click Trust Center Settings. In the left pane of the Trust Center dialog box, click Message Bar. In the right pane, click Show the Message Bar in all applications when content has been blocked, and then click OK. Close and reopen the database to apply the changed setting. Note When you enable the append query, you also enable all other database content.
For more information about Access security, see the article Help secure an Access 2007 database.
Note: this doen't sanitize arrays:
import { isPlainObject } from 'lodash';
export const sanitize = (obj: {}) => {
if (isPlainObject(obj)) {
const sanitizedObj = {};
for (const key in obj) {
if (obj[key]) {
sanitizedObj[key] = sanitize(obj[key]);
}
}
return sanitizedObj;
} else {
return obj;
}
};
Test:
describe('sanitize', () => {
it('should keep an object if there are no empty fields', () => {
expect(sanitize({})).toEqual({});
expect(sanitize({ foo: 'bar' })).toEqual({ foo: 'bar' });
expect(sanitize({ content: { foo: 'bar' } })).toEqual({
content: { foo: 'bar' },
});
});
it('should remove empty fields from top level', () => {
expect(sanitize({ foo: '', bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: null, bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: undefined, bar: 'baz' })).toEqual({ bar: 'baz' });
});
it('should remove nested empty fields', () => {
expect(sanitize({ content: { foo: '', bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: null, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: undefined, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
});
});
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
Try the following commands to search the string inside all previous tracked files:
git log --patch | less +/searching_string
or
git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'
which needs to be run from the parent directory where you'd like to do the searching.
As the other answers have indicated, you need to use an anonymous type.
As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
.Select(x => new { x.EMAIL, x.ID });
AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.
UPDATE
If you want the entire object, then you just have to omit the call to Select()
, i.e.
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);
// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'" name="invite['.$userid.']" type="checkbox">
// you can access the value directly like this:
$invite = $_POST['invite'][$userid];
Following is the most performant way to find the next AUTO_INCREMENT
value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large information_schema
database.
mysql> SHOW TABLE STATUS LIKE 'table_name';
// Look for the Auto_increment column
However, if you must retrieve this value in a query, then to the information_schema
database you must go.
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
In RxJS 5+ you can do it like this
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
In RxJS 6+
import { of } from "rxjs";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
If you want to delay each emitted value try
from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
I had this same problem, read this post, but ended building this solution that selects the divs dynamically by fetching the ID from a custom class on the href
using JQuery's attr()
function.
Here's the JQuery:
$('a.custom_class').click(function(e) {
var div = $(this).attr('href');
$(div).toggle('fast');
e.preventDefault();
}
And you just have to create a link like this then in the HTML:
<a href="#" class="#1">Link Text</a>
<div id="1">Div Content</div>
Also be sure that your file is actually a CSV file. For example, if you had an .xls file, and simply changed the file extension to .csv, the file won't import and will give the error above. To check to see if this is your problem open the file in excel and it will likely say:
"The file format and extension of 'Filename.csv' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"
To fix the file: open the file in Excel, click "Save As", Choose the file format to save as (use .cvs), then replace the existing file.
This was my problem, and fixed the error for me.
for (x in restaurants) {
if (restaurants[x].restaurant.food == 'chicken') {
return restaurants[x].restaurant.name;
}
}
you can try this :
div#panel {_x000D_
border:solid;_x000D_
width:500px;_x000D_
height:300px;_x000D_
}_x000D_
div#content {_x000D_
height:90%;_x000D_
background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
width:100%;_x000D_
height:10%;_x000D_
/*make input doesnt overflow inside div*/_x000D_
-webkit-box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
box-sizing: border-box;_x000D_
/*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
<div id="content"></div>_x000D_
<input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
I think that you'll find interesting stuff in the following answer of mine that I did for a previous similar question:
https://stackoverflow.com/q/5929469/551449
In this answer, I proposed a pattern that allows a regex to catch any kind of number and since I have nothing else to add to it, I think it is fairly complete
Since you are open to jQuery, this plugin seems to do the trick.
Do not use $scope.$apply()
angular already uses it and it can result in this error
$rootScope:inprog Action Already In Progress
if you use twice, use $timeout
or interval
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
From "node_modules" in Git:
To recap.
- Only checkin node_modules for applications you deploy, not reusable packages you maintain.
- Any compiled dependencies should have their source checked in, not the compile targets, and should $ npm rebuild on deploy.
My favorite part:
All you people who added node_modules to your gitignore, remove that shit, today, it’s an artifact of an era we’re all too happy to leave behind. The era of global modules is dead.
(The original link was this one, but it is now dead. Thanks @Flavio for pointing it out.)*
if anyone gets in here again this worked for me...
"aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]
For confused old me a range
.Address(False, False, , True)
seems to give in format TheSheet!B4:K9
If it does not why the criteria .. avoid Str functons
will probably only take less a millisecond and use 153 already used electrons
about 0.3 Microsec
RaAdd=mid(RaAdd,instr(raadd,"]") +1)
or
'about 1.7 microsec
RaAdd= split(radd,"]")(1)
It's caused by n % x
, when x
is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.
General notes:
q
to be global.I wrote a small CLI in Python and added GFM support. It's called Grip (Github Readme Instant Preview).
Install it with:
$ pip install grip
And to use it, simply:
$ grip
Then visit localhost:5000
to view the readme.md
file at that location.
You can also specify your own file:
$ grip CHANGES.md
And change port:
$ grip 8080
And of course, specifically render GitHub-Flavored Markdown, optionally with repository context:
$ grip --gfm --context=username/repo issue.md
Notable features:
stdin
and export to stdout
added in 3.0Hope this helps someone here. Check it out.
Firewalld
blocks the IP address. so to give access, use these commands:
firewall-cmd --permanent --zone=trusted --add-source=YOUR_IP/32
firewall-cmd --permanent --zone=trusted --add-port=3306/tcp
firewall-cmd --reload
Support for the extended ternary operator was added in Twig 1.12.0.
If foo
echo yes
else echo no
:
{{ foo ? 'yes' : 'no' }}
If foo
echo it, else echo no
:
{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
If foo
echo yes
else echo nothing:
{{ foo ? 'yes' }}
or
{{ foo ? 'yes' : '' }}
Returns the value of foo
if it is defined and not null, no
otherwise:
{{ foo ?? 'no' }}
Returns the value of foo
if it is defined (empty values also count), no
otherwise:
{{ foo|default('no') }}
As an additional info to Joey's answer, which isn't described in the help of set /?
nor for /?
.
%~0
expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as
%~0 - mYbAtCh
%~n0 - mybatch
%~nx0 - mybatch.bat
But there is one exception, expanding in a subroutine could fail
echo main- %~0
call :myFunction
exit /b
:myFunction
echo func - %~0
echo func - %~n0
exit /b
This results to
main - myBatch
Func - :myFunction
func - mybatch
In a function %~0
expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!
I use variations of this all the time to process files...
for files in *.log; do echo "Do stuff with: $files"; echo "Do more stuff with: $files"; done;
If processing lists of files is what you're interested in, look into the -execdir option for files.
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).
Here is the another solution as well, the bind method.
$(document).bind('click', ".intro", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
Cheers :)
If you are using an array of objects. Then the below code should do the magic, where an object property will be the criteria to remove duplicate items.
In the below example, duplicates have been removed comparing name of each item.
Try this example. http://jsfiddle.net/deepak7641/zLj133rh/
var myArray = [_x000D_
{name: 'deepak', place: 'bangalore'}, _x000D_
{name: 'chirag', place: 'bangalore'}, _x000D_
{name: 'alok', place: 'berhampur'}, _x000D_
{name: 'chandan', place: 'mumbai'}_x000D_
];_x000D_
var toRemove = [_x000D_
{name: 'deepak', place: 'bangalore'},_x000D_
{name: 'alok', place: 'berhampur'}_x000D_
];_x000D_
_x000D_
for( var i=myArray.length - 1; i>=0; i--){_x000D_
for( var j=0; j<toRemove.length; j++){_x000D_
if(myArray[i] && (myArray[i].name === toRemove[j].name)){_x000D_
myArray.splice(i, 1);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
alert(JSON.stringify(myArray));
_x000D_
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:
module.directive('myDirectiveContainer', function () {
return {
controller: function ($scope) {
this.scope = $scope;
}
};
});
module.directive('myDirective', function () {
return {
require: '^myDirectiveContainer',
link: function (scope, element, attrs, containerController) {
// use containerController.scope here...
}
};
});
and then
<div my-directive-container="">
<div my-directive="">
</div>
</div>
Maybe not the most graceful solution, but it got the job done.
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
private void DeleteProductButton_Click(object sender, EventArgs e)
{
string ProductID = deleteProductButton.Text;
if (string.IsNullOrEmpty(ProductID))
{
MessageBox.Show("Please enter valid ProductID");
deleteProductButton.Focus();
}
try
{
string SelectDelete = "Delete from Products where ProductID=" + deleteProductButton.Text;
SqlCommand command = new SqlCommand(SelectDelete, Conn);
command.CommandType = CommandType.Text;
command.CommandTimeout = 15;
DialogResult comfirmDelete = MessageBox.Show("Are you sure you want to delete this record?");
if (comfirmDelete == DialogResult.No)
{
return;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
The pattern yyyy-MM-dd
isn't an officially supported format for Date
constructor. Firefox seems to support it, but don't count on other browsers doing the same.
Here are some supported strings:
DateJS seems like a good library for parsing non standard date formats.
Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:
Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:
- YYYY is the decimal digits of the year in the Gregorian calendar.
- "-" (hyphon) appears literally twice in the string.
- MM is the month of the year from 01 (January) to 12 (December).
- DD is the day of the month from 01 to 31.
- "T" appears literally in the string, to indicate the beginning of the time element.
- HH is the number of complete hours that have passed since midnight as two decimal digits.
- ":" (colon) appears literally twice in the string.
- mm is the number of complete minutes since the start of the hour as two decimal digits.
- ss is the number of complete seconds since the start of the minute as two decimal digits.
- "." (dot) appears literally in the string.
- sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.
- Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm
This format includes date-only forms:
- YYYY
- YYYY-MM
- YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
- THH:mm
- THH:mm:ss
- THH:mm:ss.sss
Also included are "date-times" which may be any combination of the above.
So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.
Update: after looking at datejs documentation, using it, your problem should be solved using code like this:
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Alternatively:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016
) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
Replace Your JS with
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Source link
We can define the so-called foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: ['bio101', 'bio102'] // <= ids of the courses
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
The courses
field contains _id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane
, we need to perform another operation to retrieve the course
document via _id
.
If the course bio101
is removed, we need to perform another operation to update the courses
field in the student
document.
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Example:
student
{
name: 'Kate Monster',
addresses : [
{ street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
{ street: '123 Avenue Q', city: 'New York', cc: 'USA' }
]
}
Like the student
/course
example above.
Suitable for one-to-squillions, such as log messages.
host
{
_id : ObjectID('AAAB'),
name : 'goofy.example.com',
ipaddr : '127.66.66.66'
}
logmsg
{
time : ISODate("2014-03-28T09:42:41.382Z"),
message : 'cpu is on fire!',
host: ObjectID('AAAB') // Reference to the Host document
}
Virtually, a host
is the parent of a logmsg
. Referencing to the host
id saves much space given that the log messages are squillions.
References:
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions
variable
or
foreach($questions as &$question){
Adding the &
will keep the $questions
updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach
documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Using spacy:
import spacy
nlp = spacy.load('en_core_web_sm')
text = "How are you today? I hope you have a great day"
tokens = nlp(text)
for sent in tokens.sents:
print(sent.string.strip())
The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.
Yes. Thanks
Ctrl + F11 for Portrait
and
Ctrl + F12 for Landscape
Update
Please follow Commonsware MapV2 code snippets to get better understanding.
(It is present in Omnibus edition)
Following snippet is working fine at my end.I choose to use SupportMapFragment
.
Dont forget to add google-play-services.jar
into your project.
MainActivity.java
package com.example.newmapview;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment fragment = new SupportMapFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newmapview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="com.example.newmapview.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.newmapview.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.newmapview.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="XXXXX" />
</application>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
</manifest>
Here is the result
Hope this will help.
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
Or you can do
docker run -v /var/volume1 -v /var/volume2 DATA busybox true
Yes you can go to File -> Settings -> Editor -> Auto Import -> Java and make the following changes:
1.change Insert imports on paste value to All in drop down option.
2.markAdd unambigious imports on the fly option as checked.(For Window or linux user)
On a Mac, do the same thing in Android Studio -> Preferences
3.You can also use Eclipse shortcut key in Android Studio just go to in Android Studio
File -> Settings -> KeyMap -> Keymaps dropdown Option. Select from them
Thankyou
EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.
I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.
To set these:
Jenkins
-> Manage Jenkins
-> Configure System
Home directory
, click the Advanced...
button:
This value may include the following variables:
${JENKINS_HOME}
— Absolute path of the Jenkins home directory${ITEM_ROOTDIR}
— Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job${ITEM_FULL_NAME}
— The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo
The value should normally include${ITEM_ROOTDIR}
or${ITEM_FULL_NAME}
, otherwise different jobs will end up sharing the same workspace.
What you missed here is timezones.
Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.
You need to read the top of the datetime
docs, which explain about timezones and "naive" and "aware" objects.
If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp
instead of fromtimestamp
.
On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0)
instead.
Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.
If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp
method instead of trying to figure out how to do it yourself. And even if you don't, you may want to consider borrowing its source code.
(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)
Almost 2hrs on this issue! And finally I solved it by replacing the
iPhone Developer
to
iPhone Developer: My Dev Account Name
for Debug's CODE_SIGN_IDENTITY
:
I've no idea why it works, but it does! At least for me!
Environment: Xcode 5.0 (5A1412).
You are triggering the event before the event is even bound.
Just move the triggering
of the event to after attaching the event.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Also possible with vanilla JS
new Date().toISOString() // "2017-08-26T16:31:02.349Z"
foreach ($_POST["select2"] as $selectedOption)
{
echo $selectedOption."\n";
}
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Use crontab to add job
crontab -e
And job should be in this format:
00 19 * * 1,3,5 /home/user/somejob.sh
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
There's no built-in functionality to remove duplicates from arrays. Raj's answer seems elegant, but I prefer to use dictionaries.
Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
'Set d = New Scripting.Dictionary
Dim i As Long
For i = LBound(myArray) To UBound(myArray)
d(myArray(i)) = 1
Next i
Dim v As Variant
For Each v In d.Keys()
'd.Keys() is a Variant array of the unique values in myArray.
'v will iterate through each of them.
Next v
EDIT: I changed the loop to use LBound
and UBound
as per Tomalak's suggested answer.
EDIT: d.Keys()
is a Variant array, not a Collection.
simply use a 'script' tag with a dot after.
script.
var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}
https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug
Set the classpath in a way suitable multiple jars and current directory's class files.
CLASSPATH=${ORACLE_HOME}/jdbc/lib/ojdbc6.jar:${ORACLE_HOME}/jdbc/lib/ojdbc14.jar:${ORACLE_HOME}/jdbc/lib/nls_charset12.jar;
CLASSPATH=$CLASSPATH:/export/home/gs806e/tops/jconn2.jar:.;
export CLASSPATH
bash-4.2$ printf '%x\n' 4294967295
ffffffff
bash-4.2$ printf -v hex '%x' 4294967295
bash-4.2$ echo $hex
ffffffff
I had to check the box for the debugger on the phone "always allow on this phone". I then did a adb devices and then entered the adb command to clear the adds. It worked fine. Before that, it did not recognize the pm and other commands
One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"
For example, if your not careful you may be tempted to try something like:
Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
Will give "foo" a value of 0!
I think the '?' operator equivalent in C# would instead fail compilation
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
This one makes sure you have no more than three valid pairs:
(([a-fA-F]|[0-9]){2}){3}
Any more or less than three pairs of valid characters fail to match.
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
I work for Urban Outfitters. We have an open source pod, URBNAlert
, that we used in all of our apps. It's based off of UIAlertController
, but is highly customizable.
Source is here: https://github.com/urbn/URBNAlert
Or simply install by the pod by placing URBNAlert
in your Podfile
Heres some sample code:
URBNAlertViewController *uac = [[URBNAlertViewController alloc] initWithTitle:@"The Title of my message can be up to 2 lines long. It wraps and centers." message:@"And the message that is a bunch of text. And the message that is a bunch of text. And the message that is a bunch of text."];
// You can customize style elements per alert as well. These will override the global style just for this alert.
uac.alertStyler.blurTintColor = [[UIColor orangeColor] colorWithAlphaComponent:0.4];
uac.alertStyler.backgroundColor = [UIColor orangeColor];
uac.alertStyler.textFieldEdgeInsets = UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0);
uac.alertStyler.titleColor = [UIColor purpleColor];
uac.alertStyler.titleFont = [UIFont fontWithName:@"Chalkduster" size:30];
uac.alertStyler.messageColor = [UIColor blackColor];
uac.alertStyler.alertMinWidth = @150;
uac.alertStyler.alertMaxWidth = @200;
// many more styling options available
[uac addAction:[URBNAlertAction actionWithTitle:@"Ok" actionType:URBNAlertActionTypeNormal actionCompleted:^(URBNAlertAction *action) {
// Do something
}]];
[uac addAction:[URBNAlertAction actionWithTitle:@"Cancel" actionType:URBNAlertActionTypeCancel actionCompleted:^(URBNAlertAction *action) {
// Do something
}]];
[uac show];
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
Use this method to check the network state:
private void checkInternetConnection() {
if (br == null) {
br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("TEST Internet", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver((BroadcastReceiver) br, intentFilter);
}
}
remember to unregister service in onDestroy.
Cheers!!
UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/
function swapOutSource(url, newSource) {
params = url.split('&');
var src = params[0].split('=');
params.shift();
src[1] = newSource;
var newUrl = ( src.join('=') + params.join('&'));
return newUrl;
}
Then go at it!
var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");
console.log(newUrl);
Use DateDiff with MINUTE difference:
SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff
Query that may help you:
SELECT StartTime, EndTime, DATEDIFF(MINUTE, StartTime , EndTime) AS MinuteDiff
FROM TableName
I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.
You may use trick in unix/linux environment:
in gnuplot program: plot "/dev/stdin" ...
In command line: gnuplot program.plot < data.dat
If it is maven project please check the java file is created under src/main/java
If you are not getting please change the JRE path and create the java files in above folder structure
The previous answers all state that you can do the following:
var d = eval(net_datetime.slice(1, -1));
However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:
// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);
The correct way to do this is:
var d = eval("new " + net_datetime.slice(1, -1)); // which parses to
var d = new Date([epoch timestamp]);
There is no need to import/Inject your controller in JS. You can just inject your controller/nested controller through your HTML.It's worked for me. Like :
<div ng-controller="TestCtrl1">
<div ng-controller="TestCtrl2">
<!-- your code-->
</div>
</div>
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
Be careful where you set WORKDIR
because it can affect the continuous integration flow. For example, setting it to /home/circleci/project
will cause error something like .ssh
or whatever is the remote circleci is doing at setup time.
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE @rAgent_ID INT = 0
-- Looping variable.
DECLARE @i INT = 0
-- Count of rows affected for looping over
DECLARE @count INT
-- These are your old variables.
DECLARE @rAgent_Name NVARCHAR(50)
DECLARE @rAgent_Email NVARCHAR(50)
DECLARE @rAgent_IP NVARCHAR(50)
DECLARE @hotelID INT
DECLARE @retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT @Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE @i < @count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
@rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > @rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT @rAgent_Name = rAgent_Name,
@rAgent_Email = rAgent_Email,
@rAgent_IP = rAgent_IP,
@hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = @rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
@rAgent_IP, @hotelID, 'RA', @retval
-- Set up next iteration
SET @i = @i + 1
END
END
GO
I sure hope this helps you out. Cheers!
I found a way to pass a JSON message using only a HTML form.
This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.
GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.
{
allUsers
{
userId
}
}
I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.
<html>
<body>
<form method="post" action="http://localhost:8080/graphql">
<input type="text" name="operations" value="{"query": "{ allUsers { userId } }", "variables": {}}"/>
<input type="submit" />
</form>
</body>
</html>
In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.
just change the codec to "DIVX"
. This codec works with all formats.
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
i hope this works for you!
I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.
The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.
SHOW TABLES only lists the non-TEMPORARY tables in a given database.
Let's say you want to substitute something in an array of string and you don't want to perform the copy-paste on your entire sheet.
Let's take this as an example:
To apply this formula on the entire column (array) in a clean an elegant way, you can do:
=ARRAYFORMULA(SUBSTITUE(A:A, "a", "x"))
It works for 2D-arrays as well, let's say:
=ARRAYFORMULA(SUBSTITUE(A2:D83, "a", "x"))
The most straightforward method is to use plt.tight_layout
transformation which is actually more preferable as it doesn't do unnecessary cropping when using plt.savefig
import matplotlib as plt
plt.plot([1,2,3], [1,2,3])
plt.tight_layout(pad=0)
plt.savefig('plot.png')
However, this may not be preferable for complex plots that modifies the figure. Refer to Johannes S's answer that uses plt.subplots_adjust
if that's the case.
This work for me in Angular 9:
import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
@ViewChild('Map') Map: GoogleMap; /* Element Map */
locations = [
{ lat: 7.423568, lng: 80.462287 },
{ lat: 7.532321, lng: 81.021187 },
{ lat: 6.117010, lng: 80.126269 }
];
constructor() {
var bounds = new google.maps.LatLngBounds();
setTimeout(() => {
for (let u in this.locations) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(this.locations[u].lat,
this.locations[u].lng),
});
bounds.extend(marker.getPosition());
}
this.Map.fitBounds(bounds)
}, 200)
}
And it automatically centers the map according to the indicated positions.
Result:
git stash
did the job,
It restored the files that I had deleted using rm
instead of git rm
.
I did first a checkout of the last hash, but I do not believe it is required.
If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.
A simple example of processing would be:
import sys
from wavefile import WaveReader, WaveWriter
with WaveReader(sys.argv[1]) as r :
with WaveWriter(
'output.wav',
channels=r.channels,
samplerate=r.samplerate,
) as w :
# Just to set the metadata
w.metadata.title = r.metadata.title + " II"
w.metadata.artist = r.metadata.artist
# This is the prodessing loop
for data in r.read_iter(size=512) :
data[1] *= .8 # lower volume on the second channel
w.write(data)
The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.
If you don't want to bother with the keystore file, then just remove the package altogether for all users.
Connect your device with Mac/PC and run adb uninstall <package>
Worked for me.
I had just this problem and I found a similar answer here.
The method is to set top
the way you want it and then press W
(capital W).
This saves top
's current layout to a configuration file in $HOME/.toprc
Although this might not work if you want to run multiple top
's with different configurations.
So via what I consider a work around you can write to different config files / use different config files by doing one of the following...
1) Rename the binary
ln -s /usr/bin/top top2
./top2
Now .top2rc
is going to be written to your $HOME
2) Set $HOME to some alternative path, since it will write its config file to the $HOME/.binary-name.rc file
HOME=./
top
Now .toprc
is going to be written to the current folder.
Via use of other peoples comments to add the various usage accounting in top you can create a batch output for that information and latter coalesces the information via a script. Maybe not quite as simple as you script but I found top to provide me ALL processes so that later I can recap and capture a state during a long run that I might have missed otherwise (unexplained sudden CPU usage due to stray processes)
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
As a general rule (i.e. in vanilla kernels), fork
/clone
failures with ENOMEM
occur specifically because of either an honest to God out-of-memory condition (dup_mm
, dup_task_struct
, alloc_pid
, mpol_dup
, mm_init
etc. croak), or because security_vm_enough_memory_mm
failed you while enforcing the overcommit policy.
Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)
In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)
Now, in order to actually move forward I'd say you're left with two options:
NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.
Memory-wise, we already know that subprocess.Popen
uses fork
/clone
under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec
a puny 10kB executable such as free
or ps
. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM
.
Alternatives to fork
that do not have this parent page tables etc. copy problem are vfork
and posix_spawn
. But if you do not feel like rewriting chunks of subprocess.Popen
in terms of vfork
/posix_spawn
, consider using suprocess.Popen
only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free
/ps
/sleep
and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.
HOWEVER, in your particular case you can skip invoking ps
and free
altogether; that information is readily available to you in Python directly from procfs
, whether you choose to access it yourself or via existing libraries and/or packages. If ps
and free
were the only utilities you were running, then you can do away with subprocess.Popen
completely.
Finally, whatever you do as far as subprocess.Popen
is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.
I tried all the possible answers posted above none of them worked,
I resolved it by simply restarting my IDE i.e., Visual Studio Code
May it helps someone.
You append a newline to both the username and the password, i.e. the output would be something like
Sebastian
password
John
hfsjaijn
use fwrite($fh,$user." ".$password."\n");
instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv()
to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';
...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)
git rebase -i HEAD~<quantity of your commits>
(i.e. git rebase -i HEAD~5
)txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc
then save by entering wq!
and press enter.Done
The answer that worked with me is what @Anthony had written, but you have to add another line which is
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
so you can use this:
HttpContextFactory.Current.Request.Headers.Add(key, value);
The shortest expression is
curl 'http://…' | jq length
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
I wrote a regex to help find and replace "&" within an INSERT, I hope that this helps someone.
The trick was to make sure that the "&" was with other text.
Find “(\'[^\']*(?=\&))(\&)([^\']*\')”
Replace “$1' || chr(38) || '$3”
Code for clearing up the text field when clicked
<EditText android:onClick="TextFieldClicked"/>
public void TextFieldClicked(View view){
if(view.getId()==R.id.editText1);
text.setText("");
}
you will need to do it like this...
<a type="button" href="http://www.facebook.com/" value="facebook" target="_blank" class="button"></a>
and add the basic css if you want it to look like a btn.. like this
.button {
width:100px;
height:50px;
-moz-box-shadow:inset 0 1px 0 0 #fff;
-webkit-box-shadow:inset 0 1px 0 0 #fff;
box-shadow:inset 0 1px 0 0 #fff;
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #d1d1d1) );
background:-moz-linear-gradient( center top, #ffffff 5%, #d1d1d1 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d1d1d1');
background-color:#fff;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
color:#777;
font-family:Helvetica;
font-size:15px;
font-weight:700;
padding:6px 24px;
text-decoration:none;
text-shadow:1px 1px 0 #fff
}
.button:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #d1d1d1), color-stop(1, #ffffff) );
background:-moz-linear-gradient( center top, #d1d1d1 5%, #ffffff 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d1d1d1', endColorstr='#ffffff');
background-color:#d1d1d1
}
.button:active {
position:relative;
top:1px
}
target works only with href tags..
These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate
.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if (section == 0)
{
// to hide footer for section 0
return 0.0;
}
else
{
// show footer for every section except section 0
return HEIGHT_YOU_WANT;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *footerView = [[UIView alloc] init];
footerView.backgroundColor = [UIColor blackColor];
return footerView;
}
Swift
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = UIColor.black
return footerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
// to hide footer for section 0
return 0.0
} else {
// show footer for every section except section 0
return HEIGHT_YOU_WANT
}
}
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
Mockito also provides the option of stubbing methods, matching arguments (like anyInt() and anyString()), verifying the number of invocations (times(3), atLeastOnce(), never()), and more.
I've also found that Mockito is simple and clean.
One thing I don't like about Mockito is that you can't stub static methods.
UPDATE user_account
SET (student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = teacher_id
AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'
Above are the sample update query...
You can write sub query with update SQL statement, you don't need to give alias name for that table. give alias name to sub query table. I tried and it's working fine for me....
Big-O is to little-o as =
is to <
. Big-O is an inclusive upper bound, while little-o is a strict upper bound.
For example, the function f(n) = 3n
is:
O(n²)
, o(n²)
, and O(n)
O(lg n)
, o(lg n)
, or o(n)
Analogously, the number 1
is:
= 2
, < 2
, and = 1
= 0
, < 0
, or < 1
Here's a table, showing the general idea:
(Note: the table is a good guide but its limit definition should be in terms of the superior limit instead of the normal limit. For example, 3 + (n mod 2)
oscillates between 3 and 4 forever. It's in O(1)
despite not having a normal limit, because it still has a lim sup
: 4.)
I recommend memorizing how the Big-O notation converts to asymptotic comparisons. The comparisons are easier to remember, but less flexible because you can't say things like nO(1) = P.
In my case, after the recent (Mac OS High Sierra) upgrade and the subsequent brew upgrade, I started to see the above error. I followed the above instructions but still got the same error message. Then I realised that I had to use python2 which points to the brew installed python rather than the os x installed one.
@Josh: You can expand your solution with translated Message from your resource bundle
<script type="text/javascript">
$.validator.messages.number = '@Html.Raw(@Resources.General.ErrorMessageNotANumber)';
</script>
If you put this code part into your _Layout.cshtml (MVC) it's available for all your views
download putty connection manager from here http://www.thegeekstuff.com/scripts/puttycm.zip
Thanks
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
In addition to Michael Enriquez's answer, I can think of one other reason why this may be a good way to protect yourself from an undetermined state:
Say ViewControllerA presents ViewControllerB modally. But, since you may not have written the code for ViewControllerA you aren't aware of the lifecycle of ViewControllerA. It may dismiss 5 seconds (say) after presenting your view controller, ViewControllerB.
In this case, if you were simply using dismissViewController
from ViewControllerB to dismiss itself, you would end up in an undefined state--perhaps not a crash or a black screen but an undefined state from your point of view.
If, instead, you were using the delegate pattern, you would be aware of the state of ViewControllerB and you can program for a case like the one I described.
If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function
then:
data = [7, 7, 7, 7]
print(*data, sep='')
Otherwise, you'll need to convert to string and print:
print ''.join(map(str, data))
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
try this within your if statements:
Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True
Using @joran's sample data,
ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")
note that the default position of geom_histogram
is "stack."
see "position adjustment" of this page:
You can use readonly
attribute, if you want your input only to be read. And you can use disabled
attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).
Try passing columns of the DataFrame
directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
In [5]: df
Out[5]:
col1 col2 col3
0 -1.000075 -0.759910 100
1 0.510382 0.972615 200
2 1.872067 -0.731010 500
3 0.131612 1.075142 1000
4 1.497820 0.237024 1700
plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)
colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)
However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter
once for each point type.
cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300')
plt.legend()
From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull
method: df[df.col3.isnull()]
To split a list of points into many types, take a look at numpy select
, which is a vectorized if-then-else implementation and accepts an optional default value. For example:
df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
[0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
subset = df[df.subset == label]
plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()
print ''.join(file('example.txt'))
I think there is no need to specify
'http://localhost:8080`"
in the URI part.. because. if you specify it, You'll have to change it manually for every environment.
Only
"/restws/json/product/get" also works
Here is a Perl script that prints out Git diff commands for a given file as found in a Git log command.
E.g.
git log pom.xml | perl gldiff.pl 3 pom.xml
Yields:
git diff 5cc287:pom.xml e8e420:pom.xml
git diff 3aa914:pom.xml 7476e1:pom.xml
git diff 422bfd:pom.xml f92ad8:pom.xml
which could then be cut and pasted in a shell window session or piped to /bin/sh
.
Notes:
Code:
# gldiff.pl
use strict;
my $max = shift;
my $file = shift;
die "not a number" unless $max =~ m/\d+/;
die "not a file" unless -f $file;
my $count;
my @lines;
while (<>) {
chomp;
next unless s/^commit\s+(.*)//;
my $commit = $1;
push @lines, sprintf "%s:%s", substr($commit,0,6),$file;
if (@lines == 2) {
printf "git diff %s %s\n", @lines;
@lines = ();
}
last if ++$count >= $max *2;
}
In short:
You might want to read what Mozilla is doing regarding memory leaks. One tool in their toolbox is the Hans Boehm garbage collector used as memory leak detector.
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
You can use a padding for the button and you can play with drawablePadding
<Button
style="@style/botonesMenu"
android:padding="15dp"
android:drawablePadding="-15dp"
android:text="@string/actualizarBD"
android:textAlignment="gravity"
android:gravity="center"
android:layout_row="1"
android:layout_column="0"
android:drawableTop="@drawable/actualizar"
android:id="@+id/btnActualizar"
android:onClick="actualizarBD" />
you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"
Pass data from child to parent Component using Callback
You need to pass from parent to child callback function, and then call it in the child.
Parent Component:-TimeModal
handleTimeValue = (timeValue) => {
this.setState({pouringDiff: timeValue});
}
<TimeSelection
prePourPreHours={prePourPreHours}
setPourTime={this.setPourTime}
isPrePour={isPrePour}
isResident={isResident}
isMilitaryFormatTime={isMilitaryFormatTime}
communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
onSelectPouringTimeDiff={this.handleTimeValue}
/>
Note:- onSelectPouringTimeDiff={this.handleTimeValue}
In the Child Component call props when required
componentDidMount():void{
// Todo use this as per your scenrio
this.props.onSelectPouringTimeDiff(pouringDiff);
}
These are positional arguments of the script.
Executing
./script.sh Hello World
Will make
$0 = ./script.sh
$1 = Hello
$2 = World
Note
If you execute ./script.sh
, $0
will give output ./script.sh
but if you execute it with bash script.sh
it will give output script.sh
.
Please consider the use of CSS for adding style class and then add this class by JavaScript classList & simply add() function.
style.css
.nice-style {
fontsize : 12px;
left: 200px;
top: 100px;
}
script JavaScript
const addStyle = document.getElementById("myElement");
addStyle.classList.add('nice-style');
The above answer did not work for me -
The following worked
$('input[type=checkbox]').each(function()
{
this.checked = false;
});
This makes sure all the checkboxes are unchecked.
Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:
If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"
How about HKEY_CLASSES_ROOT\Word.Application\CurVer?
Another sort of workaround might be...
Use the HTML:
<input type="text" id="myselect"/>
<datalist id="myselect">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
</datalist>
In Firefox at least a focus followed by a click drops down the list of known valid values as the <datalist>
elements IFF the field happens to be empty. Otherwise, one must clear the field to see valid choices as one types in data. A new value is accepted as typed. One must handle new values in JS or other to persist them.
This is not perfect, but it suffices for my minimalist needs, so I thought I would share.
If ComboBox1.SelectedIndex = -1 Then
ComboBox1.SelectedIndex = 0
End If
Here's an example where all the imports are at the very top (this is the only time I've needed to do this). I want to be able to terminate a subprocess on both Un*x and Windows.
import os
# ...
try:
kill = os.kill # will raise AttributeError on Windows
from signal import SIGTERM
def terminate(process):
kill(process.pid, SIGTERM)
except (AttributeError, ImportError):
try:
from win32api import TerminateProcess # use win32api if available
def terminate(process):
TerminateProcess(int(process._handle), -1)
except ImportError:
def terminate(process):
raise NotImplementedError # define a dummy function
(On review: what John Millikin said.)
Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.
You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.
Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.
I had the same issue. Changing
$.ajax(...)
to
jQuery.ajax(...)
did not work. But then I found that jQuery was included twice and removing one of them fixed the problem.
If you application is using setting such as Asp.net ConnectionString you need to add the attribute HostType to your method, else they wont load even if you have an App.Config file.
[TestMethod]
[HostType("ASP.NET")] // will load the ConnectionString from the App.Config file
public void Test() {
}
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
This is the best solution I can think of that will work with pure JavaScript. You will also be able to style the element as it can be targeted in CSS. Just add in place of the year and it will automatically be updated.
//Wait for everything to load first
window.addEventListener('load', () => {
//Wrap code in IIFE
(function() {
//If your page has an element with ID of auto-year-update the element will be populated with the current year.
var date = new Date();
if (document.querySelector("#auto-year-update") !== null) {
document.querySelector("#auto-year-update").innerText = date.getFullYear();
}
})();
});
$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", $array) . "'";
From the error it seems that you are trying to import something which is not a class.
If your MyFunctions
is a class, you should import it like this:
<%@page import="com.TransportPortal.MyFunctions"%>
If it is a package and you want to import everything in the package you should do like this:
<%@page import="com.TransportPortal.MyFunctions.* "%>
Edit:
There are two cases which will give you this error, edited to cover both.
This answer is for upgrading Python 2.7.10 to Python 2.7.11 on Mac OS X El Capitan . On Terminal type:
brew unlink python
After that type on Terminal
brew install python
There is a wonderful print_r
implementation for JavaScript in php.js library.
Note, you should also add echo
support in the code.
All I'm getting from that is
_internal
I get the route name from inside a controller with $this->getRequest()->get('_route').
Even the code tuxedo25 suggested returns _internal
This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.
The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();
It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function
is a list of tf.Variable
objects, then the line session.run(init)
will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters
to use initial_parameters_of_hypothesis_function[i].initialized_value()
, which adds the necessary dependency:
parameters = []
for i in range(0, number_of_attributes, 1):
parameters.append(tf.Variable(
initial_parameters_of_hypothesis_function[i].initialized_value()))
As suggested by A Star, I always use something along the lines of:
DATE(NOW()) - INTERVAL 1 MONTH
Similarly you can do:
NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY
and so on. Much easier than typing DATE_ADD
or DATE_SUB
all the time :)!
I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..
To redirect http://example.com
or http://www.example.com
to https://www.example.com
in a simple way, you can use the following Rule in htaccess :
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond www.%{HTTP_HOST} ^(?:www\.)?(www\..+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
[Tested]
%{REQUEST_SCHEME} variable is available since apache 2.4 , this variable contains the value of requested scheme (http or https), on apache 2.4 you can use the following rule :
RewriteEngine on
RewriteCond %{REQUEST_SCHEME} ^http$
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
This may seem like a shot in the dark but make sure PHP has been complied with OpenSSL if SMTP requires SSL.
To check use phpinfo()
Hope it helps!
You can do
onchange='showHideOther.call(this);'
instead of
onchange='showHideOther(this);'
But then you also need to replace obj
with this
in the function.
Yet another way:
:'<,'>g/^/norm I//
/^/
is just a dummy pattern to match every line. norm
lets you run the normal-mode commands that follow. I//
says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).
:g
is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.
Expanding on @Ryan G mentioned usage of the pandas.DataFrame.astype(<type>)
method, one can use the errors=ignore
argument to only convert those columns that do not produce an error, which notably simplifies the syntax. Obviously, caution should be applied when ignoring errors, but for this task it comes very handy.
>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
... A B C D
... 0 2.16861 8.34139 1.83434 6.91706
... 1 5.85938 9.71712 5.53371 4.26542
... 2 0.50112 4.06725 1.99795 4.75698
>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
... A B C D E
... 0 2 8 1 6 X
... 1 5 9 5 4 Y
... 2 0 4 1 4 Z
From pandas.DataFrame.astype docs:
errors : {‘raise’, ‘ignore’}, default ‘raise’
Control raising of exceptions on invalid data for provided dtype.
- raise : allow exceptions to be raised
- ignore : suppress exceptions. On error return original object
New in version 0.20.0.
I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:
Nothing worked until I read Rohitdev's comment and realized that I had, in fact added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up.
In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.
The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.
You can call generic methods with types only known at execution time, but you have to use reflection:
// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
.MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });
Ick.
Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?
If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.
Following syntax may help for adding a main page and related subpages for doxygen:
/*! \mainpage Drawing Shapes
*
* This project helps user to draw shapes.
* Currently two types of shapes can be drawn:
* - \subpage drawingRectanglePage "How to draw rectangle?"
*
* - \subpage drawingCirclePage "How to draw circle?"
*
*/
/*! \page drawingRectanglePage How to draw rectangle?
*
* Lorem ipsum dolor sit amet
*
*/
/*! \page drawingCirclePage How to draw circle?
*
* This page is about how to draw a circle.
* Following sections describe circle:
* - \ref groupCircleDefinition "Definition of Circle"
* - \ref groupCircleClass "Circle Class"
*/
Creating groups as following also help for designing pages:
/** \defgroup groupCircleDefinition Circle Definition
* A circle is a simple shape in Euclidean geometry.
* It is the set of all points in a plane that are at a given distance from a given point, the centre;
* equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
* The distance between any of the points and the centre is called the radius.
*/
NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.
Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.
Here's a simple example that only allows files that end in ".gif" to be uploaded:
<script type="text/javascript">
function checkFile() {
var fileElement = document.getElementById("uploadFile");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension.toLowerCase() == "gif") {
return true;
}
else {
alert("You must select a GIF file for upload");
return false;
}
}
</script>
<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" />
</form>
However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).
However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.
Use Properties.loadFromXML(InputStream)
. There's no need for external libs.
Better than a messy code (since maintainability and design are your concern), it is preferable not to use long strings.
Start by reading xml properties:
InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
Properties prop = new Properies();
prop.loadFromXML(fileIS);
then you can use your multiline string in a more maintainable way...
static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n MEGA\n LONG\n..."
MultiLine.xml` gets located in the same folder YourClass:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="Super Duper UNIQUE Key">
MEGA
LONG
MULTILINE
</entry>
</properties>
PS.: You can use <![CDATA["
... "]]>
for xml-like string.
"SP25 work on Visual Studio 2019" is an exaggeration. It is extremely unreliable and should be avoided at all costs. I currently have to maintain a second development environment with V2015 for report development.
To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}