I don't know why, but closing my internet connection solved this problem for me.
HTML
<input type="date" id="theDate">
JS
$(document).ready(function() {
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
$("#theDate").attr("value", today);
});
If you don't want to use jQuery you can do something like this
HTML
<input type="date" id="theDate">
JS
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("theDate").value = today;
here, I'm passing the date object and converting it into UTC time.
$.fn.convertTimeToUTC = function (convertTime) {
if($(this).isObject(convertTime)) {
return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
}
};
// Returns if a value is an object
$.fn.isObject = function(value) {
return value && typeof value === 'object';
};
//you can call it as below
$(this).convertTimeToUTC(date);
To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.
To install OpenSSL development package on Debian, Ubuntu or their derivatives:
$ sudo apt-get install libssl-dev
To install OpenSSL development package on Fedora, CentOS or RHEL:
$ sudo yum install openssl-devel
Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :
dnf install openssl-devel
This is what I use to sort in memory - it can easily be expanded to sort an array.
Sub sortlist()
Dim xarr As Variant
Dim yarr As Variant
Dim zarr As Variant
xarr = Sheets("sheet").Range("sing col range")
ReDim yarr(1 To UBound(xarr), 1 To 1)
ReDim zarr(1 To UBound(xarr), 1 To 1)
For n = 1 To UBound(xarr)
zarr(n, 1) = 1
Next n
For n = 1 To UBound(xarr) - 1
y = zarr(n, 1)
For a = n + 1 To UBound(xarr)
If xarr(n, 1) > xarr(a, 1) Then
y = y + 1
Else
zarr(a, 1) = zarr(a, 1) + 1
End If
Next a
yarr(y, 1) = xarr(n, 1)
Next n
y = zarr(UBound(xarr), 1)
yarr(y, 1) = xarr(UBound(xarr), 1)
yrng = "A1:A" & UBound(yarr)
Sheets("sheet").Range(yrng) = yarr
End Sub
I think the given answers miss the point of the original question, which is how much space needs to be allocated to fit the base64 encoding for a given binary string of length n bytes.
The answer is (floor(n / 3) + 1) * 4 + 1
This includes padding and a terminating null character. You may not need the floor call if you are doing integer arithmetic.
Including padding, a base64 string requires four bytes for every three-byte chunk of the original string, including any partial chunks. One or two bytes extra at the end of the string will still get converted to four bytes in the base64 string when padding is added. Unless you have a very specific use, it is best to add the padding, usually an equals character. I added an extra byte for a null character in C, because ASCII strings without this are a little dangerous and you'd need to carry the string length separately.
Just use the float style. Put your google map iframe in a div class, and the paragraph in another div class, then apply the following CSS styles to those div classes(don't forget to clear the blocks after float effect, to not make the blocks trouble below them):
css
.google_map{
width:55%;
margin-right:2%;
float: left;
}
.google_map iframe{
width:100%;
}
.paragraph {
width:42%;
float: left;
}
.clearfix{
clear:both
}
html
<div class="google_map">
<iframe></iframe>
</div>
<div class="paragraph">
<p></p>
</div>
<div class="clearfix"></div>
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
<?php
echo "<script>window.opener.location.reload();</script>";
echo "<script>window.close();</script>";
?>
$ git rev-parse --abbrev-ref HEAD
master
This should work with Git 1.6.3 or newer.
The method you're looking for is charAt
. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
For more information, see the Java documentation on String.charAt
. If you want another simple tutorial, this one or this one.
If you don't want the result as a char
data type, but rather as a string, you would use the Character.toString
method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
If you want more information on the Character
class and the toString
method, I pulled my info from the documentation on Character.toString.
Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise
constructor (the Promise
executor) which receives the functions for resolving/rejecting the promise as arguments.
First, since async
now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later
as the name of the function to avoid confusion.
Using native promises (or a faithful polyfill) it would look like this:
function later(delay) {
return new Promise(function(resolve) {
setTimeout(resolve, delay);
});
}
Note that that assumes a version of setTimeout
that's compliant with the definition for browsers where setTimeout
doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).
If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout
after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):
function later(delay, value) {
return new Promise(function(resolve) {
setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
/* Or for outdated browsers that don't support doing that:
setTimeout(function() {
resolve(value);
}, delay);
Or alternately:
setTimeout(resolve.bind(null, value), delay);
*/
});
}
If you're using ES2015+ arrow functions, that can be more concise:
function later(delay, value) {
return new Promise(resolve => setTimeout(resolve, delay, value));
}
or even
const later = (delay, value) =>
new Promise(resolve => setTimeout(resolve, delay, value));
If you want to make it possible to cancel the timeout, you can't just return a promise from later
, because promises can't be cancelled.
But we can easily return an object with a cancel
method and an accessor for the promise, and reject the promise on cancel:
const later = (delay, value) => {
let timer = 0;
let reject = null;
const promise = new Promise((resolve, _reject) => {
reject = _reject;
timer = setTimeout(resolve, delay, value);
});
return {
get promise() { return promise; },
cancel() {
if (timer) {
clearTimeout(timer);
timer = 0;
reject();
reject = null;
}
}
};
};
Live Example:
const later = (delay, value) => {_x000D_
let timer = 0;_x000D_
let reject = null;_x000D_
const promise = new Promise((resolve, _reject) => {_x000D_
reject = _reject;_x000D_
timer = setTimeout(resolve, delay, value);_x000D_
});_x000D_
return {_x000D_
get promise() { return promise; },_x000D_
cancel() {_x000D_
if (timer) {_x000D_
clearTimeout(timer);_x000D_
timer = 0;_x000D_
reject();_x000D_
reject = null;_x000D_
}_x000D_
}_x000D_
};_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
l2.cancel();_x000D_
}, 150);
_x000D_
Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.
Then later
would tend to look something like this:
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
In a comment on the question, I asked:
Are you trying to create your own promise library?
and you said
I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it
To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
<script>
(function() {
// ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
var PromiseThingy = (function() {
// Internal - trigger a callback
function triggerCallback(callback, promise) {
try {
callback(promise.resolvedValue);
}
catch (e) {
}
}
// The internal promise constructor, we don't share this
function Promise() {
this.callbacks = [];
}
// Register a 'then' callback
Promise.prototype.then = function(callback) {
var thispromise = this;
if (!this.resolved) {
// Not resolved yet, remember the callback
this.callbacks.push(callback);
}
else {
// Resolved; trigger callback right away, but always async
setTimeout(function() {
triggerCallback(callback, thispromise);
}, 0);
}
return this;
};
// Our public constructor for PromiseThingys
function PromiseThingy() {
this.p = new Promise();
}
// Resolve our underlying promise
PromiseThingy.prototype.resolve = function(value) {
var n;
if (!this.p.resolved) {
this.p.resolved = true;
this.p.resolvedValue = value;
for (n = 0; n < this.p.callbacks.length; ++n) {
triggerCallback(this.p.callbacks[n], this.p);
}
}
};
// Get our underlying promise
PromiseThingy.prototype.promise = function() {
return this.p;
};
// Export public
return PromiseThingy;
})();
// ==== Using it
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
display("Start " + Date.now());
later().then(function() {
display("Done1 " + Date.now());
}).then(function() {
display("Done2 " + Date.now());
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
In my own case, i had to set backdrop
and set the top
and left
properties before i could apply draggable
function on the modal dialog. Maybe it might help someone ;)
if (!($('.modal.in').length)) {
$('.modal-dialog').css({
top: 0,
left: 0
});
}
$('#myModal').modal({
backdrop: false,
show: true
});
$('.modal-dialog').draggable({
handle: ".modal-header"
});
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
Conditions apply because you can use where condition for sub-select statements. You can perform complicated inserts using sub-selects.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';
By placing a "select" in the insert statement, you can perform multiples inserts quickly.
With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL statement before performing the insert.
SELECT count(*)
FROM customers
WHERE city = 'Newark';
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
See also How to insert with where clause
It seems that Safari 11 changes the behavior, and now local storage works in a private browser window. Hooray!
Our web app that used to fail in Safari private browsing now works flawlessly. It always worked fine in Chrome's private browsing mode, which has always allowed writing to local storage.
This is documented in Apple's Safari Technology Preview release notes - and the WebKit release notes - for release 29, which was in May 2017.
Specifically:
You can also sometimes get this error if you try to decrypt a secret while su
-ed to a different user on a system with GPG 2.x installed. This bug has been reported against RHEL 6 but there is no fix available; apparently this is due to some design decisions in GPG 2.x. One workaround suggested in the bug report is to run the decryption inside of a tmux or screen session. More reading here.
Settings > Language & input > Current keyboard > Hardware Switch ON.
It allows you to use your physical keyboard for input while at the same time showing the soft keyboard.
I just tested it on Android Lollipop and it works.
I needed to read several answers and some other info to understand what I was doing.
1. Ignore everything older than a certain commit
The file .git/info/grafts
can define fake parents for a commit. A line with just a commit id, says that the commit doesn't have a parent. If we wanted to say that we care only about the last 2000 commits, we can type:
git rev-parse HEAD~2000 > .git/info/grafts
git rev-parse gives us the commit id of the 2000th parent of the current commit. The above command will overwrite the grafts file if present. Check if it's there first.
2. Rewrite the Git history (optional)
If you want to make this grafted fake parent a real one, then run:
git filter-branch -- --all
It will change all commit ids. Every copy of this repository needs to be updated forcefully.
3. Clean up disk space
I didn't done step 2, because I wanted my copy to stay compatible with the upstream. I just wanted to save some disk space. In order to forget all the old commits:
git prune
git gc
Alternative: shallow copies
If you have a shallow copy of another repository and just want to save some disk space, you can update .git/shallow
. But be careful that nothing is pointing at a commit from before. So you could run something like this:
git fetch --prune
git rev-parse HEAD~2000 > .git/shallow
git prune
git gc
The entry in shallow works like a graft. But be careful not to use grafts and shallow at the same time. At least, don't have the same entries in there, it will fail.
If you still have some old references (tags, branches, remote heads) that point to older commits, they won't be cleaned up and you won't save more disk space.
You can simply use yield
feature introduced in ECMA6 and gen-run
library:
let run = require('gen-run');
function sleep(time) {
return function (callback) {
setTimeout(function(){
console.log(time);
callback();
}, time);
}
}
run(function*(){
console.log("befor sleeping!");
yield sleep(2000);
console.log("after sleeping!");
});
I just changed the Network settings from Native
to Manual
, restart and the error is gone.
I'm using RAD 8.0.4.3 with and old version of EGit connected to TFS/Git. ;-)
I was going to add this just to be silly, but also because it shows newcomers the potential usefulness of aliasing functions and/or imports.
Having written it, I think this code is more readable (i.e. lower time to grasp intention) than the other answers to date, and readability is (usually) king.
from os.path import dirname as up
two_up = up(up(__file__))
Note: you only want to do this kind of thing if your module is very small, or contextually cohesive.
You can also try this way
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
Some examples:
1 << 4
equal to 2^4
i.e. 16)1 << 4
or 1 << 5
is more readable.<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>
To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.
In nutshell,
@Pathparam
works for value passing through both Resources and Query String
/user/1
/user?id=1
@Queryparam
works for value passing only Query String
/user?id=1
Watch this YouTube video:
I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.
In that case you don't want to insert size
and color
inside an array, but into an object
var options = {
'size': size,
'color': color
};
Afterwards you can access the sets of keys by
var keys = Object.keys( options );
just note, The different between the methods are, if the header is not exist
request.headers.get('your-header-name')
will return None
or no exception, so you can use it like
if request.headers.get('your-header-name'):
....
but the following will throw an error
if request.headers['your-header-name'] # KeyError: 'your-header-name'
....
You can handle it by
if 'your-header-name' in request.headers:
customHeader = request.headers['your-header-name']
....
#include <iostream>
#include <string>
using namespace std;
int main() {
// your code goes here
string str;
cin >> str;
long map = 0;
for(int i =0; i < str.length() ; i++){
if((map & (1L << str[i])) > 0){
str[i] = 0;
}
else{
map |= 1L << str[i];
}
}
cout << str;
return 0;
}
Excel shows 24:03 as 3 minutes when you format it as time, because 24:03 is the same as 12:03 AM (in military time).
Instead of trying to format as Time, use the General Format and the following formula:
=number of minutes + (number of seconds / 60)
Ex: for 24 minutes and 3 seconds:
=24+3/60
This will give you a value of 24.05.
Do this for each time period. Let's say you enter this formula in cells A1
and A2
. Then, to get the total sum of elapsed time, use this formula in cell A3
:
=INT(A1+A2)+MOD(A1+A2,1)
If you put =24+3/60
into each cell, you will have a value of 48.1 in cell A3
.
Now you need to convert this back to minutes and seconds. Use the following formula in cell A4
:
=MOD(A3,1)*60
This takes the decimal portion and multiples it by 60. Remember, we divided by 60 in the beginning, so to convert it back to seconds we need to multiply.
You could have also done this separately, i.e. in cell A3 use this formula:
=INT(A1+A2)
and this formula in cell A4
:
=MOD(A1+A2,1)*60
Here's a screenshot showing the final formulas:
This is from antiquated technology: The old fashion typewriter style of printer. There was a roller (platen) that advanced the paper and a print head that hammered a metal key against an ink fabric.
\r Return the print head to the left side.
\n Advance the platen one line.
If the \n was not issued, you would type over what was on a line (used mostly for underlining text).
Just recently, I also encountered similar problem, and after I did this, it works:
I edited the file in /etc/profile
sudo nano /etc/profile
export JAVA_HOME=/home/abdul/java/jdk1.8.0_131
export PATH=$PATH:$JAVA_HOME/bin
export ANDROID_HOME=/home/abdul/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools
export GRADLE_ANDROID_HOME=/home/abdul/android-studio/gradle
export PATH=$PATH:$GRADLE_ANDROID_HOME/gradle-3.2/bin
export PATH=$PATH:$GRADLE_ANDROID_HOME/m2repository
Other info (just in case):
Not quite sure about m2repository
part, in the first try it pass the grandle but there is another error (gradlew-command-failed-with-exit-code-
I use:
Hope it can help anyone who might have the same problem like mine and need this too.
Thanks
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
Information on this will probably get outdated fast because Microsoft is running to complete its work on this, but as today, June 9th 2017, support to create SQL Server Integration Services (SSIS) projects on Visual Studio 2017 is not available. So, you can't see this option because so far it doesn't exist yet.
Beyond that, even installing what is being called SSDT (SQL Server Data Tools) in VS 2017 installer (what seems very confusing from Microsoft's part, using a known name for a different thing, breaking the behavior we expect as users), you won't see SQL Server Analysis Services (SSAS) and SQL Server Reporting Services (SSRS) project templates as well.
Actually, the Business Intelligence group under the Installed templates on the New Project dialog won't be present at all.
You need to go to this page (https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt) and install two separate installers, one for SSAS and one for SSRS.
Once you install at least one of these components, the Business Intelligence group will be created and the correspondent template(s) will be available. But as today, there is no installer for SSIS, so if you need to work with SSIS projects, you need to keep using SSDT 2015, for now.
You need the public key in your gpg key ring. To import the public key into your public keyring, place the public key block in a text file with a .gpg extension, and then issue the following command:
gpg --import <your-file>.gpg
The entity that encrypted the file should provide you with such a block. For example, ftp://ftp.gnu.org/gnu/gnu-keyring.gpg has the block for gnu.org.
For an even more in-depth explanation see Verifying files with GPG, without a .sig or .asc file?
try
if ! grep -q sysa /etc/passwd ; then
grep
returns true
if it finds the search target, and false
if it doesn't.
So NOT false
== true
.
if
evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).
Also, looking at your code as is, your use of the $( ... )
form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa")
to see what I mean. You can take that further by using the -c
(count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then
which works but is rather old school.
BUT, you could use the newest shell features (arithmetic evaluation) like
if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`
which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,%
and maybe a few others.
In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like
if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....
OR
if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....
Finally, there is an award called the Useless Use of Cat (UUOC)
. :-) Some people will jump up and down and cry gothca! I'll just say that grep
can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)
I hope this helps.
You can get at the data values like this:
string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
Or like this
class Movie
{
public string FilmName { get; set; }
public string Genre { get; set; }
}
...
var listofGenres = new List<string> { "action", "comedy" };
var Movies = new List<Movie> {new Movie {Genre="action", FilmName="Film1"},
new Movie {Genre="comedy", FilmName="Film2"},
new Movie {Genre="comedy", FilmName="Film3"},
new Movie {Genre="tragedy", FilmName="Film4"}};
var movies = Movies.Join(listofGenres, x => x.Genre, y => y, (x, y) => x).ToList();
Every solution's are not working in my system.
I can get using
#include <time.h>
double difftime(time_t time1, time_t time0);
This would be way easier:
char data [21];
int number_of_bytes_received;
if(Serial.available() > 0)
{
number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
}
bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp
if (result == 0)
{
Serial.println("data matches whatever");
}
else
{
Serial.println("data does not match whatever");
}
If you can make use of equals
, then filter the list by using distinct
within a stream (see answers above). If you can not or don't want to override the equals
method, you can filter
the stream in the following way for any property, e.g. for the property Name (the same for the property Id etc.):
Set<String> nameSet = new HashSet<>();
List<Employee> employeesDistinctByName = employees.stream()
.filter(e -> nameSet.add(e.getName()))
.collect(Collectors.toList());
You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
Try this:
$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[CheckBoxColumn1.Name].Value = true;
}
The Click event might look something like this:
private void button1_Click(object sender, EventArgs e)
{
List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
{
rows_with_checked_column.Add(row);
}
}
// Do what you want with the check rows
}
You can make <button>
tag to do action like this:
<a href="http://www.google.com/">
<button>Visit Google</button>
</a>
or:
<a href="http://www.google.com/">
<input type="button" value="Visit Google" />
</a>
It's simple and no javascript required!
NOTE:
This approach is not valid from HTML structure. But, it works on many modern browser. See following reference :
This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.
CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
DECLARE @Work VARCHAR(250)
SET @Work = @URL
SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))
SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))
--Alternate:
--SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)
RETURN @work
END
A neat solution that only uses numpy
(not scipy
nor the Counter
class):
A = np.array([[1,3,4,2,2,7], [5,2,2,1,4,1], [3,3,2,2,1,1]])
np.apply_along_axis(lambda x: np.bincount(x).argmax(), axis=0, arr=A)
array([1, 3, 2, 2, 1, 1])
Test below code:
'email' => 'required|email|unique:users,email_address,'. $id .'ID'
Where ID is the primary id of the table
Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.
String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
.replace("-----END RSA PRIVATE KEY-----", "");
// Base64 decode the data
byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);
try {
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
.fromByteArray(encodedPrivateKey);
Enumeration<?> e = primitive.getObjects();
BigInteger v = ((DERInteger) e.nextElement()).getValue();
int version = v.intValue();
if (version != 0 && version != 1) {
throw new IllegalArgumentException("wrong version for RSA private key");
}
/**
* In fact only modulus and private exponent are in use.
*/
BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException(e);
}
in my case, i couldn't delete container created with nomad jobs,
there's no output for the docker logs <ContainerID>
and, in general, it looks like frozen.
until now the solution is: sudo service docker restart
, may someone suggest better one?
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
You can try this. :) simple solution!
=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")
I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof
function without using dynamic_cast
like this:
if (dynamic_cast<B*>(aPtr) != nullptr) {
// aPtr is instance of B
} else {
// aPtr is NOT instance of B
}
But you're still reliant on RTTI
support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.
InstanceOfMacros.h
#include <set>
#include <tuple>
#include <typeindex>
#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class) \
static const std::set<std::type_index> baseTypeContainer; \
virtual bool instanceOfHelper(const std::type_index &_tidx) { \
if (std::type_index(typeid(ThisType)) == _tidx) return true; \
if (std::tuple_size<BaseTypes>::value == 0) return false; \
return baseTypeContainer.find(_tidx) != baseTypeContainer.end(); \
} \
template <typename... T> \
static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
return std::set<std::type_index>{std::type_index(typeid(T))...}; \
}
#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
protected: \
using ThisType = Class; \
_BASE_TYPE_DECL(Class, BaseClass) \
_INSTANCE_OF_DECL_BODY(Class)
#define INSTANCE_OF_BASE_DECL(Class) \
protected: \
using ThisType = Class; \
_EMPTY_BASE_TYPE_DECL() \
_INSTANCE_OF_DECL_BODY(Class) \
public: \
template <typename Of> \
typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
return instanceOfHelper(std::type_index(typeid(Of))); \
}
#define INSTANCE_OF_IMPL(Class) \
const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());
You can then use this stuff (with caution) as follows:
DemoClassHierarchy.hpp*
#include "InstanceOfMacros.h"
struct A {
virtual ~A() {}
INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)
struct B : public A {
virtual ~B() {}
INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)
struct C : public A {
virtual ~C() {}
INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)
struct D : public C {
virtual ~D() {}
INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)
The following code presents a small demo to verify rudimentary the correct behavior.
InstanceOfDemo.cpp
#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"
int main() {
A *a2aPtr = new A;
A *a2bPtr = new B;
std::shared_ptr<A> a2cPtr(new C);
C *c2dPtr = new D;
std::unique_ptr<A> a2dPtr(new D);
std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
std::cout << std::endl;
std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
std::cout << std::endl;
std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
std::cout << std::endl;
std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
std::cout << std::endl;
std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;
delete a2aPtr;
delete a2bPtr;
delete c2dPtr;
return 0;
}
Output:
a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0
a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0
a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0
c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1
a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1
The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast
. Therefore I've written a very basic performance measurement app.
InstanceOfPerformance.cpp
#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"
template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
auto start = std::chrono::high_resolution_clock::now();
volatile bool isInstanceOf = false;
for (unsigned i = 0; i < _loopCycles; ++i) {
Base *ptr = new Derived;
isInstanceOf = ptr->template instanceOf<Derived>();
delete ptr;
}
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<Duration>(end - start);
}
template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
auto start = std::chrono::high_resolution_clock::now();
volatile bool isInstanceOf = false;
for (unsigned i = 0; i < _loopCycles; ++i) {
Base *ptr = new Derived;
isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
delete ptr;
}
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<Duration>(end - start);
}
int main() {
unsigned testCycles = 10000000;
std::string unit = " us";
using DType = std::chrono::microseconds;
std::cout << "InstanceOf performance(A->D) : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "InstanceOf performance(A->C) : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "InstanceOf performance(A->B) : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "InstanceOf performance(A->A) : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
<< "\n"
<< std::endl;
std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
<< std::endl;
std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
<< "\n"
<< std::endl;
return 0;
}
The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp
the output on my local machine was:
InstanceOf performance(A->D) : 699638 us
InstanceOf performance(A->C) : 642157 us
InstanceOf performance(A->B) : 671399 us
InstanceOf performance(A->A) : 626193 us
DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us
Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast
approach. It is even less efficient for the special test case which tests if a pointer of A
is an instance ofA
. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp
. The result on my local machine was amazing:
InstanceOf performance(A->D) : 3035 us
InstanceOf performance(A->C) : 5030 us
InstanceOf performance(A->B) : 5250 us
InstanceOf performance(A->A) : 3021 us
DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us
If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.
Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2))
under macOS Sierra on a MacBook Pro Mid 2012.
Edit:
I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
. On this platform the perfomance benefit was not so significant as on macOs with clang.
Output (without compiler optimization):
InstanceOf performance(A->D) : 390768 us
InstanceOf performance(A->C) : 333994 us
InstanceOf performance(A->B) : 334596 us
InstanceOf performance(A->A) : 300959 us
DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us
Output (with compiler optimization):
InstanceOf performance(A->D) : 209501 us
InstanceOf performance(A->C) : 208727 us
InstanceOf performance(A->B) : 207815 us
InstanceOf performance(A->A) : 197953 us
DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us
saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
Updated answer
Check https://shatter-box.com/knowledgebase/android-apk-signing-tool-apk-signer/
Old answer
check apk-signer a nice way to sign your app
You'll have to use svn directly:
svn checkout URL[@REV]... [PATH]
and
svn help co
gives you a little more help.
Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.
Small and universal solution:
expr "$string" : "$prefix\(.*\)$suffix"
The input operator for number skips leading whitespace, so you can just read the number in a loop:
while (myfile >> a)
{
// ...
}
When you're doing it by code the trick is to call
WindowStyle = WindowStyle.None;
first and then
WindowState = WindowState.Maximized;
to get it to display over the Taskbar.
To reset your keyring.
Go into your home folder.
Press ctrl & h to show your hidden folders.
Now look in your .gnome2/keyrings directory.
Find the default.keyring file.
Move that file to a different folder.
Once done, reboot your computer.
The 1*y
method works in Numpy too:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
If you are asking for a way to convert Python lists from Boolean to int, you can use map
to do it:
>>> testList = [False, False, True, True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]
Or using list comprehensions:
>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:
$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%
This will use awk
to print out 100 minus the 12th field (idle), with a percentage sign after it. awk
will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/
).
You can also average five samples, one second apart:
$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'
Test it like this:
$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'
Just for future needs.
In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window
to make it work.
<Grid Name="myGrid" Height="437.274">
<TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>
From the reference docs of Comparable.compareTo(T):
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
In short:
this.compareTo(that)
returns
where the implementation of this method determines the actual semantics of <
>
and ==
(I don't mean ==
in the sense of java's object identity operator)
"abc".compareTo("def")
will yield something smaller than 0 as abc
is alphabetically before def
.
Integer.valueOf(2).compareTo(Integer.valueOf(1))
will yield something larger than 0 because 2 is larger than 1.
Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.
Note: you should read at least one of the following:
Warning: you should never rely on the return values of compareTo being -1
, 0
and 1
. You should always test for x < 0
, x == 0
, x > 0
, respectively.
See emulator-5554 unauthorized for adb devices. On API 29 emulator I run adb devices
command and got emulator-5554 unauthorized
message. Then I created a new avd
device from Google APIs
image (in my case Q, x86), not from Google Play
.
import java.util.Arrays;
public class sortNumber {
public static void main(String[] args) {
// Our array contains 13 elements
int[] array = {9, 238, 248, 138, 118, 45, 180, 212, 103, 230, 104, 41, 49};
Arrays.sort(array);
System.out.printf(" The result : %s", Arrays.toString(array));
}
}
I don't know why but (for now) httpclient can be compiled only as a jar into the libs directory in your project. HttpCore works fine when it is included from mvn like that:
dependencies {
compile 'org.apache.httpcomponents:httpcore:4.4.3'
}
you should use extend()
>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]
other info: append vs. extend
This uses kotlinx.serialization
like Elisha's answer. Meanwhile the API is being stabilized for the upcoming 1.0 release. Note that e.g. JSON.parse
was renamed to Json.parse
and is now Json.decodeFromString
. Also it is imported in gradle differently starting in Kotlin 1.4.0:
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC"
}
apply plugin: 'kotlinx-serialization'
Example usage:
@Serializable
data class Properties(val nid: Int, val tid: Int)
@Serializable
data class Feature(val pos: List<Double>, val properties: Properties? = null,
val count: Int? = null)
@Serializable
data class Root(val features: List<Feature>)
val root = Json.decodeFromString<Root>(jsonStr)
val rootAlt = Json.decodeFromString(Root.serializer(), jsonStr) // equivalent
val str = Json.encodeToString(root) // type 'Root' can be inferred!
// For a *top-level* list (does not apply in my case) you would use
val fList = Json.decodeFromString<List<Feature>>(jsonStr)
val fListAlt = Json.decodeFromString(ListSerializer(Feature.serializer()), jsonStr)
Kotlin's data class
defines a class that mainly holds data and has .toString()
and other methods (e.g. destructuring declarations) automatically defined. I'm using nullable (?
) types here for optional fields.
Or is it like saying "Since this is python v2.7, use that different 'print' function that has also been added to python v2.7, after it was added in python 3. So my 'print' will no longer be statements (eg print "message" ) but functions (eg, print("message", options). That way when my code is run in python 3, 'print' will not break."
In
from __future__ import print_function
print_function is the module containing the new implementation of 'print' as per how it is behaving in python v3.
This has more explanation: http://python3porting.com/noconv.html
I have changed in my activity but effected. Here is my code:
View layout = getLayoutInflater().inflate(R.layout.list_group,null);
try {
LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.ldrawernav);
linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
}
catch (Exception e) {
}
}
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
Content-Type: application/force-download
means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".
Use the correct mime type for whatever media you are using (e.g. audio/mpeg
for mp3).
Use the Content-Disposition: attachment; etc etc
header if you want to encourage the client to download it instead of following the default behaviour.
A solution which works quite well is described right here: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/radio
The idea is to use the property (appearance), which when sets to none allows to change the width and height of the radio button. The radio buttons are not blurry, and you can add other effect like transitions and stuff.
Here's an example :
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border-radius: 50%;
width: 16px;
height: 16px;
border: 2px solid #999;
transition: 0.2s all linear;
margin-right: 5px;
position: relative;
top: 4px;
}
input:checked {
border: 6px solid black;
outline: unset !important /* I added this one for Edge (chromium) support */
}
The only drawback is that it is not supported yet on IE.
Here's a GIF (with a not so good rendering) below to give an idea of what can be achieved: you will get way better results on an actual browser.
And the plunker : https://plnkr.co/plunk/1W3QXWPi7hdxZJuT
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.
Make all attributes optional
type User = {
attr0?: number
attr1?: string
}
type User = {
...
}
let u1: User = null;
Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:User
without any assignment.
Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.
More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.
let attr1: number = ...
let attr2: string = ...
let user1: User = {
attr1: attr1,
attr2: attr2
}
Use SimpleDateFormat
class. Take a look on its javadoc: it explains how to use format switches.
The above solutions were not working for me. I solved it by creating a View with the same background colour as the parent and added negative margin to move the image upwards.
<ScrollView style={{ backgroundColor: 'blue' }}>
<View
style={{
width: '95%',
paddingLeft: '5%',
marginTop: 80,
height: 800,
}}>
<View style={{ backgroundColor: 'white' }}>
<Thumbnail square large source={{uri: uri}} style={{ marginTop: -30 }}/>
<Text>Some Text</Text>
</View>
</View>
</ScrollView>
and I got the following result.
It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
In your code, jQuery just looks for the first instance of an input with name q12_3
, which in this case has a value of 1
. You want an input with name q12_3
that is :checked
.
$("#submit").click(() => {_x000D_
const val = $('input[name=q12_3]:checked').val();_x000D_
alert(val);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
Note that the above code is not the same as using .is(":checked")
. jQuery's is()
function returns a boolean (true or false) and not (an) element(s).
Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.
document.querySelector("#submit").addEventListener("click", () => {_x000D_
const val = document.querySelector("input[name=q12_3]:checked").value;_x000D_
alert(val);_x000D_
});
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
An alternative, I think for your purpose, is to use the round() function:
select round((10 * 1.5),2) // prints 15.00
You can try it here:
In MySQL, It should be like this
INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';
This is the working code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class JavaCalculator extends JFrame {
private JButton jbtNum1;
private JButton jbtNum2;
private JButton jbtNum3;
private JButton jbtNum4;
private JButton jbtNum5;
private JButton jbtNum6;
private JButton jbtNum7;
private JButton jbtNum8;
private JButton jbtNum9;
private JButton jbtNum0;
private JButton jbtEqual;
private JButton jbtAdd;
private JButton jbtSubtract;
private JButton jbtMultiply;
private JButton jbtDivide;
private JButton jbtSolve;
private JButton jbtClear;
private double TEMP;
private double SolveTEMP;
private JTextField jtfResult;
Boolean addBool = false;
Boolean subBool = false;
Boolean divBool = false;
Boolean mulBool = false;
String display = "";
public JavaCalculator() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
p1.add(jbtNum1 = new JButton("1"));
p1.add(jbtNum2 = new JButton("2"));
p1.add(jbtNum3 = new JButton("3"));
p1.add(jbtNum4 = new JButton("4"));
p1.add(jbtNum5 = new JButton("5"));
p1.add(jbtNum6 = new JButton("6"));
p1.add(jbtNum7 = new JButton("7"));
p1.add(jbtNum8 = new JButton("8"));
p1.add(jbtNum9 = new JButton("9"));
p1.add(jbtNum0 = new JButton("0"));
p1.add(jbtClear = new JButton("C"));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jtfResult = new JTextField(20));
jtfResult.setHorizontalAlignment(JTextField.RIGHT);
jtfResult.setEditable(false);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(5, 1));
p3.add(jbtAdd = new JButton("+"));
p3.add(jbtSubtract = new JButton("-"));
p3.add(jbtMultiply = new JButton("*"));
p3.add(jbtDivide = new JButton("/"));
p3.add(jbtSolve = new JButton("="));
JPanel p = new JPanel();
p.setLayout(new GridLayout());
p.add(p2, BorderLayout.NORTH);
p.add(p1, BorderLayout.SOUTH);
p.add(p3, BorderLayout.EAST);
add(p);
jbtNum1.addActionListener(new ListenToOne());
jbtNum2.addActionListener(new ListenToTwo());
jbtNum3.addActionListener(new ListenToThree());
jbtNum4.addActionListener(new ListenToFour());
jbtNum5.addActionListener(new ListenToFive());
jbtNum6.addActionListener(new ListenToSix());
jbtNum7.addActionListener(new ListenToSeven());
jbtNum8.addActionListener(new ListenToEight());
jbtNum9.addActionListener(new ListenToNine());
jbtNum0.addActionListener(new ListenToZero());
jbtAdd.addActionListener(new ListenToAdd());
jbtSubtract.addActionListener(new ListenToSubtract());
jbtMultiply.addActionListener(new ListenToMultiply());
jbtDivide.addActionListener(new ListenToDivide());
jbtSolve.addActionListener(new ListenToSolve());
jbtClear.addActionListener(new ListenToClear());
} //JavaCaluclator()
class ListenToClear implements ActionListener {
public void actionPerformed(ActionEvent e) {
//display = jtfResult.getText();
jtfResult.setText("");
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
TEMP = 0;
SolveTEMP = 0;
}
}
class ListenToOne implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "1");
}
}
class ListenToTwo implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "2");
}
}
class ListenToThree implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "3");
}
}
class ListenToFour implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "4");
}
}
class ListenToFive implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "5");
}
}
class ListenToSix implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "6");
}
}
class ListenToSeven implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "7");
}
}
class ListenToEight implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "8");
}
}
class ListenToNine implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "9");
}
}
class ListenToZero implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "0");
}
}
class ListenToAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
addBool = true;
}
}
class ListenToSubtract implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
subBool = true;
}
}
class ListenToMultiply implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
mulBool = true;
}
}
class ListenToDivide implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
divBool = true;
}
}
class ListenToSolve implements ActionListener {
public void actionPerformed(ActionEvent e) {
SolveTEMP = Double.parseDouble(jtfResult.getText());
if (addBool == true)
SolveTEMP = SolveTEMP + TEMP;
else if ( subBool == true)
SolveTEMP = SolveTEMP - TEMP;
else if ( mulBool == true)
SolveTEMP = SolveTEMP * TEMP;
else if ( divBool == true)
SolveTEMP = SolveTEMP / TEMP;
jtfResult.setText( Double.toString(SolveTEMP));
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaCalculator calc = new JavaCalculator();
calc.pack();
calc.setLocationRelativeTo(null);
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.setVisible(true);
}
} //JavaCalculator
/* array literal */
var aData = [];
/* object constructur */
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
return (this.firstname + " " + this.lastname);
};
}
/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]
aData.push(new Person("Jhon", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));
aData[aData.length] = new Person("stack", "overflow"); // aData[4]
/* loop array */
for (var i in aData) {
alert(aData[i].fullname());
}
/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
_x000D_
grid.Columns[0].HeaderText
or
grid.Columns["columnname"].HeaderText
You can read HTML page using 'urllib'.
#python 2.x
import urllib
page = urllib.urlopen("your path ").read()
print page
Custom toasts from the background are blocked, Android 11 protects users by deprecating custom toast views. For security reasons and to maintain a good user experience, the system blocks toasts that contain custom views if those toasts are sent from the background by an app that targets Android 11.
addCallback() method added in Android R If you want to be notified when a toast (text or custom) appears or disappears.
The most important text in toast API changes that for apps that target Android 11 the getView()
method returns null when you access it, So, ensure to protect your apps from FATAL EXCEPTION, you know what I mean :)
Use snackbars instead if applicable.
It's recommended that you use snackbars instead where possible. If your app's use case prevents you from using snackbars, such as when you need to send the user a message while your app is in the background, you can still use text toasts because they aren't restricted by the new behavior change.
See the official docs for more details on the topic.
INSERT INTO mt_magazine_subscription SELECT *
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
Chrome uses the same Internet Options as IE.
Try opening your Internet Options and removing the URL from "Trusted Sites." This should regenerate a 401 call for credentials when you restart the browser and visit the URL again.
You may need to remove it from "Intranet Sites" as well.
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
the simplest solution is.....open your website in vs2013 and go to Debug->WebsiteProperties (last option) a new window will open..
in this window go to "Build" option and change .net framework version from 4.5 to 4.0.....then select ok. [note: this step will only work if your project does not have dependencies with vs2013...]
Now open your website in vs2010
I improved upon the answer by Teo Inke. It no longer rotates the image unless it is actually necessary. It is also easier to read, and should run faster.
// Load Image
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
// Rotate Image if Needed
try
{
// Determine Orientation
ExifInterface exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
// Determine Rotation
int rotation = 0;
if (orientation == 6) rotation = 90;
else if (orientation == 3) rotation = 180;
else if (orientation == 8) rotation = 270;
// Rotate Image if Necessary
if (rotation != 0)
{
// Create Matrix
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
// Rotate Bitmap
Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// Pretend none of this ever happened!
bitmap.recycle();
bitmap = rotated;
rotated = null;
}
}
catch (Exception e)
{
// TODO: Log Error Messages Here
}
// TODO: Use Result Here
xxx.setBitmap(bitmap);
std::vector
has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end()
always holds. So you could do
const vector<type>::const_iterator pos = std::find_if( firstVector.begin()
, firstVector.end()
, some_predicate(parameter) );
if( position != firstVector.end() ) {
const vector<type>::size_type idx = pos-firstVector.begin();
doAction( secondVector[idx] );
}
As an alternative, there's always std::numeric_limits<vector<type>::size_type>::max()
to be used as an invalid value.
Adding padding to an inner div
, as in the currently accepted answer, won't work if for some reason you want to use box-model: border-box
.
What does work in both cases is increasing the width of the inner div
to 100% plus the scrollbar's width (assuming overflow: hidden
on the outer div).
For example, in CSS:
.container2 {
width: calc(100% + 19px);
}
In JavaScript, cross-browser:
var child = document.getElementById('container2');
var addWidth = child.offsetWidth - child.clientWidth + "px";
child.style.width = 'calc(100% + ' + addWidth + ')';
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
complete
executes after either the success
or error
callback were executed.
Maybe you should check the second parameter complete
offers too. It's a String holding the type of success the ajaxCall had.
The different callbacks are described a little more in detail here jQuery.ajax( options )
I guess you missed the fact that the complete
and the success
function (I know inconsistent API) get different data passed in. success
gets only the data, complete
gets the whole XMLHttpRequest
object. Of course there is no responseText
property on the data string.
So if you replace complete
with success
you also have to replace data.responseText
with data
only.
success
The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.
complete
The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
If you need to have access to the whole XMLHttpRequest
object in the success callback I suggest trying this.
var myXHR = $.ajax({
...
success: function(data, status) {
...do whatever with myXHR; e.g. myXHR.responseText...
},
...
});
<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='030' height='030'
src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
type='application/x-shockwave-flash'
allowscriptaccess='always' allowfullscreen='true'
frameborder='0'></iframe>
just insert your code after embed/
I'm not aware of a CSS-only solution.
As you mentioned, filters are the canonical approach to creating drop shadow effects in SVG. The SVG specification includes an example of this.
Edited: Fixed mistake in code that stopped it working if there were no
YourModel
entries in the db.
There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.
However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).
In your models.py
from django.db import models
def from_500():
'''
Returns the next default value for the `ones` field,
starts from 500
'''
# Retrieve a list of `YourModel` instances, sort them by
# the `ones` field and get the largest entry
largest = YourModel.objects.all().order_by('ones').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 500
return 500
# If an instance of `YourModel` is returned, we get it's
# `ones` attribute and increment it by 1
return largest.ones + 1
def add_ten():
''' Returns the next default value for the `tens` field'''
# Retrieve a list of `YourModel` instances, sort them by
# the `tens` field and get the largest entry
largest = YourModel.objects.all().order_by('tens').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 10
return 10
# If an instance of `YourModel` is returned, we get it's
# `tens` attribute and increment it by 10
return largest.tens + 10
class YourModel(model.Model):
ones = models.IntegerField(primary_key=True,
default=from_500)
tens = models.IntegerField(default=add_ten)
What comes after the "Where" is a constraint on the generic type T you declared, so:
class means that the T should be a class and not a value type or a struct.
new() indicates that the T class should have a public parameter-free default constructor defined.
chart.series[0].setData(data,true);
The setData
method itself will call the redraw method
Use a RelativeLayout
with layout_alignParentLeft
and layout_alignParentRight
:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="@+id/mytextview1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/mytextview2"/>
</RelativeLayout>
Also, you should probably be using dip
(or dp
) rather than sp
in your layout. sp
reflect text settings as well as screen density so they're usually only for sizing text items.
I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.
https://github.com/ansible/ansible/issues/39389
- hosts: localhost
connection: local
gather_facts: no
tasks:
- name: set_fact
set_fact:
foo: "{{ foo }} + [ '{{ item }}' ]"
with_items:
- "one"
- "two"
- "three"
vars:
foo: []
- name: Print the var
debug:
var: foo
Using virtualenvwrapper function:
wipeenv
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.
Please find the screen shot Get request with authentication and query params
To add Query param click on drop down arrow on left side of URL box.
For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:
\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}
It's the fontspec
package that allows for \setmainfont
and \setmonofont
. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.
Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).
Detect it in what? JavaScript? That would be impossible. If you just want it for logging purposes, you could use some sort of tracking scheme, where each page has JavaScript that will make a request for a special resource (probably a very small gif
or similar). That way you can just take the difference between unique page requests and requests for your tracking file.
Sadly git is so unrelable :( I just lost 2 days of work :(
It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.
I learned my lesson - next time backup first and only then commit. Never trust git for anything.
I prefer this way
Using ajaxStop
+ setInterval
,, this will refresh the page after any XHR[ajax] request in the same page
$(document).ajaxStop(function() {
setInterval(function() {
location.reload();
}, 3000);
});
All you need is a bit of improved markup. Wrap the second within the first and it will render under.
<div id="wrapper">
<div id="first">
Here comes the first content
<div id="second">I will render below the first content</div>
</div>
</div>
First of all, you can't prevent people from downloading fonts except if it is yours and that usually takes months. And it makes no sense to prevent people from using fonts. A lot of fonts that you see on websites can be found on free platforms like the one I mentioned below.
But if you want to implement a font into your website read this: There is a pretty simple and free way to implement fonts into your website. I would recommend Google fonts because it is free and easy to use. For example, I'll use the Bangers font from Google.(https://fonts.google.com/specimen/Bangers?query=bangers&sidebar.open&selection.family=Bangers) This is how it would look like: HTML
<head>
<link href="https://fonts.googleapis.com/css2?family=Bangers&display=swap" rel="stylesheet">
</head>
CSS
body {
font-family: 'Bangers', cursive;
}
Take a look at this one: http://code.google.com/p/xswingx/
It is not very difficult to implement it by yourself, btw. A couple of listeners and custom renderer and voila.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
i had the same problem. it was due to false name in the path. there was a special Character in the path like this: C:\User\My App\Projekte-Tablet&Handy i deleted the "&" character and it worked well.
As answer by Miles, {% comment %}...{% endcomment %}
is used for multi-line comments, but you can also comment out text on the same line like this:
{# some text #}
Layout changes can occur whenever any of the following events happens in a view:
a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling thesetNeedsLayout
orlayoutIfNeeded
method of a view.
e. Your application forces layout by calling thesetNeedsLayout
method of the view’s underlying layer object.
from my experience;
if it doesn't work from within php
do this in .htaccess
it worked for me
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://www.vknyvz.com
Header set Access-Control-Allow-Credentials true
</IfModule>
In 2007 my project successfully used OpenOffice.org's Universal Network Objects (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).
OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables.
We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival.
You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools.
UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An OpenOffice Software Development Kit (SDK) is available containing example applications and the UNO Developer's Guide.
I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.
The important things about OpenOffice UNO are:
Here are some useful web sites:
In my case I was drawing onto a canvas tag from a video. To address the tainted canvas error I had to do two things:
<video id="video_source" crossorigin="anonymous">
<source src="http://crossdomain.example.com/myfile.mp4">
</video>
To overcome the issue of Win7 32bit VB6, try copying from Windows Server 2003 C:\Windows\system32\
the files mscomctl.ocx
and mscomcctl.oba
.
You can use:
var dictionary = myList.ToDictionary(x => x);
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
Look at stat
for checking if the directory exists,
And mkdir
, to create a directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
You can see the manual of these functions with the man 2 stat
and man 2 mkdir
commands.
The HTTPConnection
object from the httplib
module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out httplib2
; it's a great library.
jakub.g's answer is correct, however an example using grunt seems a bit complex.
So my simpler answer:
- Sending a command line argument to an npm script
Syntax for sending command line arguments to an npm script:
npm run [command] [-- <args>]
Imagine we have an npm start task in our package.json to kick off webpack dev server:
"scripts": {
"start": "webpack-dev-server --port 5000"
},
We run this from the command line with npm start
Now if we want to pass in a port to the npm script:
"scripts": {
"start": "webpack-dev-server --port process.env.port || 8080"
},
running this and passing the port e.g. 5000 via command line would be as follows:
npm start --port:5000
- Using package.json config:
As mentioned by jakub.g, you can alternatively set params in the config of your package.json
"config": {
"myPort": "5000"
}
"scripts": {
"start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},
npm start
will use the port specified in your config, or alternatively you can override it
npm config set myPackage:myPort 3000
- Setting a param in your npm script
An example of reading a variable set in your npm script. In this example NODE_ENV
"scripts": {
"start:prod": "NODE_ENV=prod node server.js",
"start:dev": "NODE_ENV=dev node server.js"
},
read NODE_ENV in server.js either prod or dev
var env = process.env.NODE_ENV || 'prod'
if(env === 'dev'){
var app = require("./serverDev.js");
} else {
var app = require("./serverProd.js");
}
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
a.hover:hover
The error occurs when the DNS resolution fails. Check if you can wget (or curl) the api url from the command line. Changing the DNS server and testing it might help.
You are producing a filtered list by using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still 'three'
, even if it was subsequently filtered out from the list being produced.
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == 'two':
break
If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == 'two'), None)
which will set i
to None
if there is no such matching element.
The above is not that useful a filter; your are essentially testing if the value 'two'
is in the list. You can use in
for that:
elem = 'two' if 'two' in my_list else None
What context/language? Some languages use /
as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/
For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the /
has is it may be the designated pattern delimiter.
Also, you can check the compatibility troubleshooting
Check the detail steps, and other ways to always open VS as Admin at Visual Studio requires the application to have elevated permissions.
reg
and wire
specify how the object will be assigned and are therefore only meaningful for outputs.
If you plan to assign your output in sequential code,such as within an always
block, declare it as a reg
(which really is a misnomer for "variable" in Verilog). Otherwise, it should be a wire
, which is also the default.
In httpd.conf add (or change if it's already there):
AddDefaultCharset utf-8
You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.
When you are trying to visit a local filename through firefox browser, you have to force the file:\\\
protocol (http://en.wikipedia.org/wiki/File_URI_scheme) or else firefox will encode your space TWICE. Change the html snippet from this:
<img src="C:\Documents and Settings\screenshots\Image01.png"/>
to this:
<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>
or this:
<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>
Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.
Helpful link: http://support.mozilla.org/en-US/questions/900466
string userName="";
string userId = "";
int uid = 0;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
}
using (DevEntities context = new DevEntities())
{
uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
return uid;
}
return uid;
This is possible in case of variable a
being accessed by, say 2 web workers through a SharedArrayBuffer as well as some main script. The possibility is low, but it is possible that when the code is compiled to machine code, the web workers update the variable a
just in time so the conditions a==1
, a==2
and a==3
are satisfied.
This can be an example of race condition in multi-threaded environment provided by web workers and SharedArrayBuffer in JavaScript.
Here is the basic implementation of above:
main.js
// Main Thread
const worker = new Worker('worker.js')
const modifiers = [new Worker('modifier.js'), new Worker('modifier.js')] // Let's use 2 workers
const sab = new SharedArrayBuffer(1)
modifiers.forEach(m => m.postMessage(sab))
worker.postMessage(sab)
worker.js
let array
Object.defineProperty(self, 'a', {
get() {
return array[0]
}
});
addEventListener('message', ({data}) => {
array = new Uint8Array(data)
let count = 0
do {
var res = a == 1 && a == 2 && a == 3
++count
} while(res == false) // just for clarity. !res is fine
console.log(`It happened after ${count} iterations`)
console.log('You should\'ve never seen this')
})
modifier.js
addEventListener('message' , ({data}) => {
setInterval( () => {
new Uint8Array(data)[0] = Math.floor(Math.random()*3) + 1
})
})
On my MacBook Air, it happens after around 10 billion iterations on the first attempt:
Second attempt:
As I said, the chances will be low, but given enough time, it'll hit the condition.
Tip: If it takes too long on your system. Try only a == 1 && a == 2
and change Math.random()*3
to Math.random()*2
. Adding more and more to list drops the chance of hitting.
For me doing a svn update, followed by svn commit worked. There were no .svn folders present in folder which was failing to add.
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
Create images
folder in root level of your project.
Drop your image in this folder, it should look like
Go to your pubspec.yaml
file, add assets
header and pay close attention to all the spaces.
flutter:
uses-material-design: true
# add this
assets:
- images/profile.jpg
Tap on Packages get
at the top right corner of the IDE.
Now you can use your image anywhere using
Image.asset("images/profile.jpg")
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
replace works on char data type but replaceAll works on String datatype and both replace the all occurrences of first argument with second argument.
Wikipedia says "The Web Services Description Language is an XML-based language that provides a model for describing Web services". Put another way, WSDL is to a web service, as javadoc is to a java library.
The really sweet thing about WSDL, though, is that software can generate a client and server using WSDL.
In the new rspec
expect
syntax this would be:
expect(subject).to receive(:bar).with("an argument I want")
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
More space:
android:letterSpacing="0.1"
Less space:
android:letterSpacing="-0.07"
If you need to display all the records after 2014-09-01, add this to your query:
SELECT * FROM Events
WHERE Format(Events.DATE_TIME,'yyyy-MM-dd hh:mm:ss') >= Format("2014-09-01 00:00:00","yyyy-MM-dd hh:mm:ss")
You can not check for version support via command line. Best option would be checking OpenSSL changelog.
Openssl versions till 1.0.0h supports SSLv2, SSLv3 and TLSv1.0. From Openssl 1.0.1 onward support for TLSv1.1 and TLSv1.2 is added.
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).
Alternatively, you can use XPath query via XPathSelectElements
method:
var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");
Even both eacceleator and xcache perform quite well during moderate loads, APC maintains its stability under serious request intensity. If we're talking about a few hundred requests/sec here, you'll not feel the difference. But if you're trying to respond more, definetely stick with APC. Especially if your application has overly dynamic characteristics which will likely cause locking issues under such loads. http://www.ipsure.com/blog/2011/eaccelerator-as-zend-extension-high-load-averages-issue/ may help.
On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div
again). This is probably done on other architectures too.
Instruction:
DIV
srcNote: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.
int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */
Another example:
select
case when teamId < 10 then '0' + cast(teamId as char(1))
else cast(teamId as char(2)) end
as 'pretty id',
* from team
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
LPCWSTR
stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char
. Common for any C/C++ code that has to deal with non-ASCII only strings.=
To get a normal C literal string to assign to a LPCWSTR
, you need to prefix it with L
LPCWSTR a = L"TestWindow";
You can retrieve the contents of an iframe
first and then use jQuery
selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use
$this->db->set('time', 'NOW()', FALSE);
to set it correctly.
you can always check your sql afterward with
$this->db->last_query();
You can try this way.
byte ptext[] = myString.getBytes("ISO-8859-1");
String value = new String(ptext, "UTF-8");
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
to Vilx-:
var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
table = table.parentNode;
and what if row.parentNode
is TBODY
?
You should check it out first, and after that
do while
by .tBodies
, probably
The way to do this is to set the EnableHeadersVisualStyles
flag for the data grid view to False
, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor
property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
If you do not set the EnableHeadersVisualStyles
flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
1) Normally, you would want to return a Task
. The main exception should be when you need to have a void
return type (for events). If there's no reason to disallow having the caller await
your task, why disallow it?
2) async
methods that return void
are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:
static async void f()
{
await h();
}
static async Task g()
{
await h();
}
static async Task h()
{
throw new NotImplementedException();
}
private void button1_Click(object sender, EventArgs e)
{
f();
}
private void button2_Click(object sender, EventArgs e)
{
g();
}
private void button3_Click(object sender, EventArgs e)
{
GC.Collect();
}
f
's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g
's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException
handler runs. You should never let this happen. To use your example,
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
Yes, use async
and await
here, they make sure your method still works correctly if an exception is thrown.
for more information see: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Following query will give you the exact table names of the database having field name like '%myName'.
SELECT distinct(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myName%'
What TJ Crowder said, everyway will have some kind of hidden iteration, with lodash this becomes:
var index = _.findIndex(array, {prop2: 'yutu'})
In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful.
There are still bugs in mine, but if anyone wants it, here it is.
So in short, if you are looking for a speed gain, then MySQLi; if you want ease of use, then PDO.
Just create a multi-line comment around it. When you want it back, just erase the comment tags.
For example, <!-- Stuff to comment out or make inactive -->
Following is the code if you are not using jQuery. Demo
var myArray = [
{field: 'id', operator: 'eq', value: 'id'},
{field: 'cStatus', operator: 'eq', value: 'cStatus'},
{field: 'money', operator: 'eq', value: 'money'}
];
alert(myArray.length);
for(var i=0 ; i<myArray.length; i++)
{
if(myArray[i].value=='money')
myArray.splice(i);
}
alert(myArray.length);
You can also use underscore library which have lots of function.
Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
You can remove classes and add classes dynamically
$(document).ready(function(){
$('#div').removeClass('left').addClass('right');
});
select substr(orderno,1,2) from shipment;
You may want to have a look at the documentation too.
Check out this directive: https://github.com/samu/angular-table
It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.
I've written a one linear for this:
[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);
I feel however I can spend more time to make a JSON.parse(JSON.stringify())
-free version which is used for cloning here.
Btw, have a look at my another answer here.
I believe you are having the same problem here.
The sheet must be active before you can select a range on it.
Also, don't omit the sheet name qualifier:
Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select
Or,
With Sheets("BxWsn Simulation")
.Select
.Range("Result").Select
End WIth
which is the same.
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key
gpg --edit-key (keyIDNumber)
gpg> trust
Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)
1 = I don't know or won't say
2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu
and select 5 to enable that imported private key as one of your keys
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
How about:
df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days
This will return difference as int
if there are no missing values(NaT
) and float
if there is.
You can kill the process which is running the container.
With this command you can list the processes related with the docker container:
ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')
Now you have the process ids to kill with kill or kill -9.
This problem was caused by an orphaned SQL Login. I ran my favorite sp_fixusers script and the error was resolved. The suggestion above to look at the logs was a good one...and it led me to my answer.
Here is one more example. (check the reference)
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
const {otherIndustry, ...otherIndustry2} = myObject;_x000D_
console.log(otherIndustry2);
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
top: 0;_x000D_
}
_x000D_
.fa-file-o {
position: absolute;
left: 50px;
top: 15px;
color: #ffffff
}
<div>
<span class="fa fa-file-o"></span>
<input type="button" name="" value="IMPORT FILE"/>
</div>
Here's an example using an extension. This assumes the view has the same width and height.
Need to use a layout change listener to get the view size.
Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)
fun View.setRoundedBackground(@ColorInt color: Int) {
addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val shape = GradientDrawable()
shape.cornerRadius = measuredHeight / 2f
shape.setColor(color)
background = shape
removeOnLayoutChangeListener(this)
}
})
}