formatCalendarDate = function (dateTime) {
return moment.utc(dateTime).format('LL')
}
If you're in an async function you can simply do it in one line:
console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);
FYI, if target is NodeJS you can use this if you want (it's a predefined promisified setTimeout function):
await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](3000) // 3 sec
If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:
public static boolean download(final File output, final String source) {
try {
if (!output.createNewFile()) {
throw new RuntimeException("Could not create new file!");
}
URL url = new URL(source);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
// connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
final FileOutputStream fos = new FileOutputStream(output);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
return true;
} catch (final Exception e) {
e.printStackTrace();
}
return false;
}
All you should need to do is set the proper name for the auth token and fill it in.
Example usage:
download(new File("C:\\output.xls"), "http://www.website.com/endpoint");
It should help you.
{% for user in users if user.active and user.id not 1 %}
{{ user.name }}
{% endfor %}
More info: http://twig.sensiolabs.org/doc/tags/for.html
In it's simplest form, you are saying "for this cell, if it's value is X, then apply format foo". However, if you use the "formula" method, you can select the whole row, enter the formula and associated format, then use copy and paste (formats only) for the rest of the table.
You're limited to only 3 rules in Excel 2003 or older so you might want to define a pattern for the colours rather than using raw values. Something like this should work though:
Are you looking for...
a if b else c
Or perhaps you misunderstand Python's or
? True or True
is True
.
You want to use the gesturestart
, gesturechange
, and gestureend
events. These get triggered any time 2 or more fingers touch the screen.
Depending on what you need to do with the pinch gesture, your approach will need to be adjusted. The scale
multiplier can be examined to determine how dramatic the user's pinch gesture was. See Apple's TouchEvent documentation for details about how the scale
property will behave.
node.addEventListener('gestureend', function(e) {
if (e.scale < 1.0) {
// User moved fingers closer together
} else if (e.scale > 1.0) {
// User moved fingers further apart
}
}, false);
You could also intercept the gesturechange
event to detect a pinch as it happens if you need it to make your app feel more responsive.
I suggest you look into getting composer
. https://getcomposer.org
Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.
Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php
Delete your C:\Inetpub\wwwroot\php\PHPMailer\
directory.
Use composer.phar
to get the phpmailer package using the command line to execute
cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer
After it is finished it will create a C:\Inetpub\wwwroot\php\vendor
directory along with all of the phpmailer files and generate an autoloader.
Next in your main project configuration file you need to include the autoload file.
require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';
The vendor\autoload.php
will include the information for you to use $mail = new \PHPMailer;
Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
I needed to do this because I have an ajax login form. When users login successfully I redirect to a new page and end the previous request because the other page handles redirecting back to the relying party (because it's a STS SSO System).
However, I also wanted it to work with javascript disabled, being the central login hop and all, so I came up with this,
public static string EnsureUrlEndsWithSlash(string url)
{
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException("url");
if (!url.EndsWith("/"))
return string.Concat(url, "/");
return url;
}
public static string GetQueryStringFromArray(KeyValuePair<string, string>[] values)
{
Dictionary<string, string> dValues = new Dictionary<string,string>();
foreach(var pair in values)
dValues.Add(pair.Key, pair.Value);
var array = (from key in dValues.Keys select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(dValues[key]))).ToArray();
return "?" + string.Join("&", array);
}
public static void RedirectTo(this HttpRequestBase request, string url, params KeyValuePair<string, string>[] queryParameters)
{
string redirectUrl = string.Concat(EnsureUrlEndsWithSlash(url), GetQueryStringFromArray(queryParameters));
if (request.IsAjaxRequest())
HttpContext.Current.Response.Write(string.Format("<script type=\"text/javascript\">window.location='{0}';</script>", redirectUrl));
else
HttpContext.Current.Response.Redirect(redirectUrl, true);
}
For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.
For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.
Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/
An example with list items:
li {
list-style: none;
padding: 0 10px;
display: inline-block;
border-right: 1px solid #000;
line-height: 5px;
margin: 20px 0;
}
<ul>
<li>cats</li>
<li>dogs</li>
<li>birds</li>
<li>swine!</li>
</ul>
in swift ;)
UPDATE SWIFT 3.0 :D
func sFunc_imageFixOrientation(img:UIImage) -> UIImage {
// No-op if the orientation is already correct
if (img.imageOrientation == UIImageOrientation.up) {
return img;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform:CGAffineTransform = CGAffineTransform.identity
if (img.imageOrientation == UIImageOrientation.down
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: img.size.height)
transform = transform.rotated(by: CGFloat(M_PI))
}
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
}
if (img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: 0, y: img.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
}
if (img.imageOrientation == UIImageOrientation.upMirrored
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
}
if (img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: img.size.height, y: 0);
transform = transform.scaledBy(x: -1, y: 1);
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx:CGContext = CGContext(data: nil, width: Int(img.size.width), height: Int(img.size.height),
bitsPerComponent: img.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: img.cgImage!.colorSpace!,
bitmapInfo: img.cgImage!.bitmapInfo.rawValue)!
ctx.concatenate(transform)
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored
) {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.height,height:img.size.width))
} else {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.width,height:img.size.height))
}
// And now we just create a new UIImage from the drawing context
let cgimg:CGImage = ctx.makeImage()!
let imgEnd:UIImage = UIImage(cgImage: cgimg)
return imgEnd
}
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
You could use $
extraction:
class(aframe$a1)
[1] "numeric"
or the double square bracket:
class(aframe[["a1"]])
[1] "numeric"
You can try something similar to this :
String s = "65";
byte value = Byte.valueOf(s);
Use the Byte.ValueOf()
method for all the elements in the String array to convert them into Byte values.
Possibly using different Port for MySQL than using in your Code
$conn = new PDO("mysql:host=".SERVER_NAME.";port=3307;dbname=".DB_NAME, DB_USER, DB_PASS);
Both ports should be same.
Another approach can be taken into account
library(stringr)
str_replace_all(" xx yy 11 22 33 ", regex("\\s*"), "")
#[1] "xxyy112233"
\\s: Matches Space, tab, vertical tab, newline, form feed, carriage return
*: Matches at least 0 times
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.
import scala.collection.mutable.ListBuffer
val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)
if you want you can convert this to a list by using .toList
For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?
Um... There is no "concise" description of this. It's complex. You've designed it to be complex. And it requires complex documentation in the docstring.
Sorry, but complexity is -- well -- complex.
Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.
var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();
It can also be done as follows:
csv_files = s3.list_objects_v2(s3_bucket_path)
for obj in csv_files['Contents']:
key = obj['Key']
Other's have answered your question. If you rebase a branch you will need to force to push that branch.
Rebase and a shared repository generally do not get along. This is rewriting history. If others are using that branch or have branched from that branch then rebase will be quite unpleasant.
In general, rebase works well for local branch management. Remote branch management works best with explicit merges (--no-ff).
We also avoid merging master into a feature branch. Instead we rebase to master but with a new branch name (e.g adding a version suffix). This avoids the problem of rebasing in the shared repository.
var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
this.parentElement.removeChild(this);
};
var table = document.getElementById('content');
table.appendChild(newTH);
Working example: http://jsfiddle.net/23tBM/
You can also just hide with this.style.display = 'none'
.
If you need it in SELECT section can use like this.
SELECT ct.ID,
ISNULL(NULLIF(ct.LaunchDate, ''), null) [LaunchDate]
FROM [dbo].[CustomerTable] ct
you can replace the null
with your substitution value.
You can use two way:
1: You just keep the necessary columns:
drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])
2: This is the more elegant way.
df = df.drop("col_name")
You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!
Try
//*[text()='qwerty']
because .
is your current element
You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time
In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:
Just build on the system with the oldest GLIBC you still want to support.
This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:
Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.
Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.
With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Use children()
and each()
, you can optionally pass a selector to children
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
You could also just use the immediate child selector:
$('#mydiv > input').each(function () { /* ... */ });
Each time you set the same seed, you get the same sequence. So of course if you're setting the seed to the time in a fast loop, you'll probably call it with the same seed many times.
In your case, as you're calling your randInt
function until you have a different value, you're waiting for the time (as returned by Nano) to change.
As for all pseudo-random libraries, you have to set the seed only once, for example when initializing your program unless you specifically need to reproduce a given sequence (which is usually only done for debugging and unit testing).
After that you simply call Intn
to get the next random integer.
Move the rand.Seed(time.Now().UTC().UnixNano())
line from the randInt function to the start of the main and everything will be faster.
Note also that I think you can simplify your string building:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
fmt.Println(randomString(10))
}
func randomString(l int) string {
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(randInt(65, 90))
}
return string(bytes)
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.
In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.
This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS
If you use an =
statement to assign a value to a var
with an object on the right side, javascript will not copy but reference the object.
You can use lodash's clone
method
var obj = {a: 25, b: 50, c: 75};
var A = _.clone(obj);
Or lodash's cloneDeep
method if your object has multiple object levels
var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.cloneDeep(obj);
Or lodash's merge
method if you mean to extend the source object
var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.merge({}, obj, {newkey: "newvalue"});
Or you can use jQuerys extend
method:
var obj = {a: 25, b: 50, c: 75};
var A = $.extend(true,{},obj);
Here is jQuery 1.11 extend method's source code :
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
When you use the following (without disable-output-escaping
!) you'll get a single non-breaking space:
<xsl:text> </xsl:text>
On Mac OS X, go to folder /$HOME (/Users/{user home}/). You will see file '.eclipse_keyring'. Remove it. All saved credentials will be lost.
Can't you use the classical 2>
redirection operator.
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
'foo'
}
I don't like errors so I avoid them at all costs.
java
packages are base, and javax
packages are extensions.
Swing was an extension because AWT was the original UI API. Swing came afterwards, in version 1.1.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
getWeekOfYear: function(date) {
var target = new Date(date.valueOf()),
dayNumber = (date.getUTCDay() + 6) % 7,
firstThursday;
target.setUTCDate(target.getUTCDate() - dayNumber + 3);
firstThursday = target.valueOf();
target.setUTCMonth(0, 1);
if (target.getUTCDay() !== 4) {
target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
}
return Math.ceil((firstThursday - target) / (7 * 24 * 3600 * 1000)) + 1;
}
Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601
I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).
Both approaches call a constructor, they just call different ones. This code:
var albumData = new Album
{
Name = "Albumius",
Artist = "Artistus",
Year = 2013
};
is syntactic shorthand for this equivalent code:
var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;
The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:
public Album() { }
then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.
Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:
private Album() { }
public Album(string name)
{
this.Name = name;
}
Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:
var albumData = new Album("Albumius")
{
Artist = "Artistus",
Year = 2013
};
The post-compilation result would then be identical to:
var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;
add ng-model="$ctrl.formName"
attribute to your form, and then in the controller you can access the form as an object inside your controller by this.formName
You can use the asXML method
echo $xml->asXML();
You can also give it a filename
$xml->asXML('filename.xml');
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
If you're working with a long list of substrings consisting of full "words" separated by spaces or any other common character, you can be a little clever in your search.
First divide your string into groups of X, then X+1, then X+2, ..., up to Y. X and Y should be the number of words in your substring with the fewest and most words respectively. For example if X is 1 and Y is 4, "Alpha Beta Gamma Delta" becomes:
"Alpha" "Beta" "Gamma" "Delta"
"Alpha Beta" "Beta Gamma" "Gamma Delta"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
If X would be 2 and Y be 3, then you'd omit the first and last row.
Now you can search on this list quickly if you insert it into a Set (or a Map), much faster than by string comparison.
The downside is that you can't search for substrings like "ta Gamm". Of course you could allow for that by splitting by character instead of by word, but then you'd often need to build a massive Set and the time/memory spent doing so outweighs the benefits.
Here is one using .padStart()
:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<title>timer</title>
</head>
<body>
<span id="minutes">00</span>:<span id="seconds">00</span>
<script>
const minutes = document.querySelector("#minutes")
const seconds = document.querySelector("#seconds")
let count = 0;
const renderTimer = () => {
count += 1;
minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
seconds.innerHTML = (count % 60).toString().padStart(2, "0");
}
const timer = setInterval(renderTimer, 1000)
</script>
</body>
</html>
The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
Follow these Steps Restore your "Default Website" Website :
You could try to do this with getcode()
from urllib
>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200
EDIT: For more modern python, i.e. python3
, use:
import urllib.request
print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
>>> 200
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
self.myArray.add(indexPath.row)
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
self.myArray.removeObject(at: indexPath.row)
self.myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
deleteAction.backgroundColor = UIColor.red
// action three
let shareAction = UITableViewRowAction(style: .default, title: "Share", handler: { (action , indexPath)in
print("Share Tapped")
})
shareAction.backgroundColor = UIColor .green
return [editAction, deleteAction, shareAction]
}
In my case in global.asax/application_start method, I was registering web api routes AFTER mvc routes like so:
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
Reverting the order fixed the issue
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Complete tutorial here
Demo link
JavaScript
$('.owl-carousel').owlCarousel({
margin: 10,
nav: true,
navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
CSS Style for navigation
.owl-carousel .nav-btn{
height: 47px;
position: absolute;
width: 26px;
cursor: pointer;
top: 100px !important;
}
.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}
.owl-carousel .prev-slide{
background: url(nav-icon.png) no-repeat scroll 0 0;
left: -33px;
}
.owl-carousel .next-slide{
background: url(nav-icon.png) no-repeat scroll -24px 0px;
right: -33px;
}
.owl-carousel .prev-slide:hover{
background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}
for i in range(10,0,-1):
print i,
The range() function will include the first value and exclude the second.
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
You could use an XPath, too. A bit old fashioned but still effective:
using System.Xml;
...
XmlDocument xmlDocument;
xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
foreach (XmlElement xmlElement in
xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
Console.Out.WriteLine(xmlElement.OuterXml);
}
I solved it through googling:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.
Check this fiddle:
It shows how to manually indent ul and ol using CSS.
HTML
<head>
<title>Lines</title>
</head>
<body>
<ol type="1" style="list-style-position:inside;">
<li>Text</li>
<li>Text</li>
<li >longer Text, longer Text, longer Text, longer Text second line of longer Text </li>
</ol>
<br/>
<ul>
<li>Text</li>
<li>Text</li>
<li>longer Text, longer Text, longer Text, longer Text second line of longer Text </li>
</ul>
</body>
CSS
ol
{
margin:0px;
padding-left:15px;
}
ol li
{
margin: 0px;
padding: 0px;
text-indent: -1em;
margin-left: 1em;
}
ul
{
margin:0;
padding-left:30px;
}
ul li
{
margin: 0px;
padding: 0px;
text-indent: 0.5em;
margin-left: -0.5em;
}
Also I edited your fiddle
Make a note of it.
First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
This answer is for TextInputEditText :
In the layout XML file set your input method options to your required type. for example done.
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionGo"/>
</com.google.android.material.textfield.TextInputLayout>
Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc
In the java add the editor action listener.
TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
textInputLayout.getEditText().setOnEditorActionListener(new
TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction();
return true;
}
return false;
}
});
If you're using kotlin :
textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction()
}
true
}
Based on @Chris's function to calculate the mode or related metrics, however using Ken Williams's method to calculate frequencies. This one provides a fix for the case of no modes at all (all elements equally frequent), and some more readable method
names.
Mode <- function(x, method = "one", na.rm = FALSE) {
x <- unlist(x)
if (na.rm) {
x <- x[!is.na(x)]
}
# Get unique values
ux <- unique(x)
n <- length(ux)
# Get frequencies of all unique values
frequencies <- tabulate(match(x, ux))
modes <- frequencies == max(frequencies)
# Determine number of modes
nmodes <- sum(modes)
nmodes <- ifelse(nmodes==n, 0L, nmodes)
if (method %in% c("one", "mode", "") | is.na(method)) {
# Return NA if not exactly one mode, else return the mode
if (nmodes != 1) {
return(NA)
} else {
return(ux[which(modes)])
}
} else if (method %in% c("n", "nmodes")) {
# Return the number of modes
return(nmodes)
} else if (method %in% c("all", "modes")) {
# Return NA if no modes exist, else return all modes
if (nmodes > 0) {
return(ux[which(modes)])
} else {
return(NA)
}
}
warning("Warning: method not recognised. Valid methods are 'one'/'mode' [default], 'n'/'nmodes' and 'all'/'modes'")
}
Since it uses Ken's method to calculate frequencies the performance is also optimised, using AkselA's post I benchmarked some of the previous answers as to show how my function is close to Ken's in performance, with the conditionals for the various ouput options causing only minor overhead:
Answer: NO
Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.
You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.
Does not seem so. Quote from ECMAScript 6 modules: the final syntax:
You may be wondering – why do we need named exports if we could simply default-export objects (like CommonJS)? The answer is that you can’t enforce a static structure via objects and lose all of the associated advantages (described in the next section).
That is because you are not fully qualifying your cells object. Try this
With Worksheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
Notice the DOT before Cells?
My personal favorite is http://www.codeproject.com/KB/recipes/plossum_commandline.aspx by Peter Palotas:
[CommandLineManager(ApplicationName="Hello World",
Copyright="Copyright (c) Peter Palotas")]
class Options
{
[CommandLineOption(Description="Displays this help text")]
public bool Help = false;
[CommandLineOption(Description = "Specifies the input file", MinOccurs=1)]
public string Name
{
get { return mName; }
set
{
if (String.IsNullOrEmpty(value))
throw new InvalidOptionValueException(
"The name must not be empty", false);
mName = value;
}
}
private string mName;
}
Velocity is a good candidate for writing this kind of stuff.
It allows you to keep your html and data-generation code as separated as possible.
small script i wrote to replace all files with .txt extension to .cpp extension under /tmp and sub directories recursively
#!/bin/bash
for file in $(find /tmp -name '*.txt')
do
mv $file $(echo "$file" | sed -r 's|.txt|.cpp|g')
done
What about:
@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof
:concat
set myvar=%myvar% %1;
goto :eof
To get a connection from a data source, the following code should work:
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
Context ctx = new InitialContext();
DataSource dataSource = ctx.lookup("java:comp/env/jdbc/xxxx");
Connection conn = dataSource.getConnection();
// use the connection
conn.close();
While you can look up a data source as defined in the Websphere Data Sources config (i.e. through the websphere console) directly, the lookup from java:comp/env/jdbc/xxxx means that there needs to be an entry in web.xml:
<resource-ref>
<res-ref-name>jdbc/xxxx</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
This means that data sources can be mapped on a per application bases and you don't need to change the name of the data source if you want to point your app to a different data source. This is useful when deploying the application to different servers (e.g. test, preprod, prod) which need to point to different databases.
First of all it is unclear what type name has. If it has the type std::string
then instead of
string nametext;
nametext = "Your name is" << name;
you should write
std::string nametext = "Your name is " + name;
where operator + serves to concatenate strings.
If name
is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write
std::string nametext( "Your name is " );
nametext.append( name );
or
std::string nametext( "Your name is " );
nametext += name;
Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).
Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".
If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
In XCode under Targets, right-click on your project and Get Info. Under the Build tab look for iOS Deployment Target. By changing this you should be able to test different iOS version.
Simply you can aadd --force
at the end of the command. Like:
sudo docker rmi <docker_image_id> --force
To make it more intelligent you can add as:
sudo docker stop $(docker ps | grep <your_container_name> | awk '{print $1}')
sudo docker rm $(docker ps | grep <your_container_name> | awk '{print $1}')
sudo docker rmi $(docker images | grep <your_image_name> | awk '{print $3}') --force
Here in docker ps
$1 is the first column, i.e. the Docker container ID.
And docker images
$3 is the third column, i.e. the Docker image ID.
the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.
next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.
in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.
i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (
The DataGrid has an XAML property IsReadOnly
that you can set to true
:
<my:DataGrid
IsReadOnly="True"
/>
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.
Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:
$(function() {_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
In other words, doesn't DEFAULT render NOT NULL redundant ?
No, it is not redundant. To extended accepted answer. For column col
which is nullable awe can insert NULL even when DEFAULT is defined:
CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);
-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);
+-----+------+
| ID | COL |
+-----+------+
| 1 | null |
+-----+------+
Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL
:
CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL);
INSERT INTO t2(id, col) VALUES(1, NULL);
+-----+-----+
| ID | COL |
+-----+-----+
| 1 | 10 |
+-----+-----+
Here we tried to insert NULL but get default instead.
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.
The
Element.getClientRects()
method returns a collection ofDOMRect
objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection ofDOMRect
objects, one for each CSS border box associated with the element. EachDOMRect
object contains read-onlyleft
,top
,right
andbottom
properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.
Element.getClientRects() by Mozilla Contributors is licensed under CC-BY-SA 2.5.
Summing up all returned rectangle widths yields the total text width in pixels.
document.getElementById('in').addEventListener('input', function (event) {_x000D_
var span = document.getElementById('text-render')_x000D_
span.innerText = event.target.value_x000D_
var rects = span.getClientRects()_x000D_
var widthSum = 0_x000D_
for (var i = 0; i < rects.length; i++) {_x000D_
widthSum += rects[i].right - rects[i].left_x000D_
}_x000D_
document.getElementById('width-sum').value = widthSum_x000D_
})
_x000D_
<p><textarea id='in'></textarea></p>_x000D_
<p><span id='text-render'></span></p>_x000D_
<p>Sum of all widths: <output id='width-sum'>0</output>px</p>
_x000D_
An integer value is a mathematical representation of a number and is ignorant of leading zeroes.
You can get a string with leading zeroes like this:
someNumber.ToString("00000000")
We could type our variable with an explicit return type:
const script: HTMLScriptElement = document.getElementsByName(id).item(0);
Or assert as (needed with TSX):
const script = document.getElementsByName(id).item(0) as HTMLScriptElement;
Or in simpler cases assert with angle-bracket syntax.
A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.
Documentation:
name() is literally the textual name in the java code of the enum. That means it is limited to strings that can actually appear in your java code, but not all desirable strings are expressible in code. For example, you may need a string that begins with a number. name() will never be able to obtain that string for you.
Quick and clean solution (linux tested) (After fatidic February 27, 2014)
Uninstall npm
npm rm npm -g
Install npm (new URL is www.npmjs.org instead npmjs.org)
curl https://www.npmjs.org/install.sh | sh
Tip: how to install node.js in linux https://stackoverflow.com/a/22099363/333061
The only time you should worry your users about something that happened in the code is if there is something they can or need to do to avoid the issue. If they can change data on a form, push a button or change a application setting in order to avoid the issue then let them know. But warnings or errors that the user has no ability to avoid just makes them lose confidence in your product.
Exceptions and Logs are for you, the developer, not your end user. Understanding the right thing to do when you catch each exception is far better than just applying some golden rule or rely on an application-wide safety net.
Mindless coding is the ONLY kind of wrong coding. The fact that you feel there is something better that can be done in those situations shows that you are invested in good coding, but avoid trying to stamp some generic rule in these situations and understand the reason for something to throw in the first place and what you can do to recover from it.
If someone is looking for analogy , this answer might be helpful.
WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.
XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.
For the main logfile/appender, set up a .Threshold = INFO
to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.
As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.
However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
For selenium automation users
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
Make a fake checkbox with no name and value, force the value in an hidden field:
<input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">
Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name
Here is what fixed for me:
1) Make sure you are running Visual Studio as Administrator
2) Install and run winhttpcertcfg.exe to grant access
https://msdn.microsoft.com/en-us/library/windows/desktop/aa384088(v=vs.85).aspx
The command is similar to below: (enter your certificate subject and service name)
winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "NetworkService"
winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "LOCAL SERVICE"
winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "My Apps Service Account"
Also note that "in" keyword does not work on arrays. It works on objects only.
propName in myObject
Array inclusion test is
myArray.includes('three');
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).No one mentioned yet streams added in Java 8 so here it goes:
int[] array = list.stream().mapToInt(i->i).toArray();
//OR
//int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
simple Stream#toArray
returns Object[]
, so it is not what we want. Also Stream#toArray(IntFunction<A[]> generator)
doesn't do what we want because generic type A
can't represent primitive int
so it would be nice to have some stream which could handle primitive type int
instead of wrapper Integer
, because its toArray
method will most likely also return int[]
array (returning something else like Object[]
or even boxed Integer[]
would be unnatural here). And fortunately Java 8 has such stream which is IntStream
so now only thing we need to figure out is how to convert our Stream<Integer>
(which will be returned from list.stream()
) to that shiny IntStream
. Here Stream#mapToInt(ToIntFunction<? super T> mapper)
method comes to a rescue. All we need to do is pass to it mapping from Integer
to int
. We could use something like Integer#intValue
which returns int
like :
mapToInt( (Integer i) -> i.intValue() )
(or if someone prefers mapToInt(Integer::intValue)
)
but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int
(lambda in mapToInt
is implementation of ToIntFunction
interface which expects body for int applyAsInt(T value)
method which is expected to return int
).
So we can simply write
mapToInt((Integer i)->i)
Also since Integer
type in (Integer i)
can be inferred by compiler because List<Integer>#stream()
returns Stream<Integer>
we can also skip it which leaves us with
mapToInt(i -> i)
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).Strong points of PyLint
:
Cons of Pylint:
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
The problem with your code is that you are selecting the .remode_hover
that is a descendant of .remode_selected
. So the first part of getting your code to work correctly is by removing that space
.reMode_selected.reMode_hover:hover
Then, in order to get the style to not work, you have to override the style set by the :hover
. In other words, you need to counter the background-color
property. So the final code will be
.reMode_selected.reMode_hover:hover {
background-color:inherit;
}
.reMode_hover:hover {
background-color: #f0ac00;
}
An alternative method would be to use :not()
, as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected
in there. This will target all elements that don't have a class of .remode_selected
However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.
A third method would be to use jQuery. You can target the .not()
selector, which would be similar to using :not()
in CSS, but with much better browser support
I believe you can also do:
$sortDirection = 'desc';
$user->with(['comments' => function ($query) use ($sortDirection) {
$query->orderBy('column', $sortDirection);
}]);
That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:
$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);
Try something like the following in your script:
set_time_limit(1200);
You need to implement the UITableViewDelegate method
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.
print_elapsed_time function is below
def print_elapsed_time(prefix=''):
e_time = time.time()
if not hasattr(print_elapsed_time, 's_time'):
print_elapsed_time.s_time = e_time
else:
print(f'{prefix} elapsed time: {e_time - print_elapsed_time.s_time:.2f} sec')
print_elapsed_time.s_time = e_time
use it in this way
print_elapsed_time()
.... heavy jobs ...
print_elapsed_time('after heavy jobs')
.... tons of jobs ...
print_elapsed_time('after tons of jobs')
result is
after heavy jobs elapsed time: 0.39 sec
after tons of jobs elapsed time: 0.60 sec
the pros and cons of this function is that you don't need to pass start time
Now, there's also another option for any general csv file: https://github.com/seahboonsiew/pyspark-csv as follows:
Assume we have the following context
sc = SparkContext
sqlCtx = SQLContext or HiveContext
First, distribute pyspark-csv.py to executors using SparkContext
import pyspark_csv as pycsv
sc.addPyFile('pyspark_csv.py')
Read csv data via SparkContext and convert it to DataFrame
plaintext_rdd = sc.textFile('hdfs://x.x.x.x/blah.csv')
dataframe = pycsv.csvToDataFrame(sqlCtx, plaintext_rdd)
I think, UNSIGNED
would be the best option to store something like time_duration
(Eg: resolved_call_time = resolved_time(DateTime)-creation_time(DateTime)
) value in minutes or hours or seconds format which will definitely be a non-negative number
You can use zIndex
for placing a view on top of another. It works like the CSS z-index property - components with a larger zIndex
will render on top.
You can refer: Layout Props
Snippet:
<ScrollView>
<StatusBar backgroundColor="black" barStyle="light-content" />
<Image style={styles.headerImage} source={{ uri: "http://www.artwallpaperhi.com/thumbnails/detail/20140814/cityscapes%20buildings%20hong%20kong_www.artwallpaperhi.com_18.jpg" }}>
<View style={styles.back}>
<TouchableOpacity>
<Icons name="arrow-back" size={25} color="#ffffff" />
</TouchableOpacity>
</View>
<Image style={styles.subHeaderImage} borderRadius={55} source={{ uri: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Albert_Einstein_1947.jpg/220px-Albert_Einstein_1947.jpg" }} />
</Image>
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white"
},
headerImage: {
height: height(150),
width: deviceWidth
},
subHeaderImage: {
height: 110,
width: 110,
marginTop: height(35),
marginLeft: width(25),
borderColor: "white",
borderWidth: 2,
zIndex: 5
},
firstOrCreate()
checks for all the arguments to be present before it finds
a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value'])
with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate()
and firstOrNew()
:
firstOrCreate()
will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.firstOrNew()
will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save()
on the model). Otherwise it will give you the matched item.Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name
or some mandatory field), you should use firstOrNew()
. If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate()
.
Use Eclipse to search and replace (remove) all instances of "@Override". Then add back the non-interface overrides using "Clean Up".
Steps:
From verify
documentation:
If a certificate is found which is its own issuer it is assumed to be the root CA.
In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:
openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem
It will verify your entire chain in a single command.
In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.
I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.
After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.
Good luck! David
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
Don't use "source"
, it's designed to run a small number of sql queries
and display the output, not to import large databases.
I use Wamp Developer
(not XAMPP
) but it should be the same.
What you want to do is use the MySQL Client
to do the work for you.
MySQL
is running.phpMyAdmin
or the MySQL shell
.cmd.exe
, and change to the directory your sql
file is
located in.mysql -u root -p database_name_here < dump_file_name_here.sql
database name
and dump file name
.MySQL root account password
when prompted (if no password set, remove the "-p" switch).This assumes that mysql.exe
can be located via the environmental path, and that sql
file is located in the directory you are running this from. Otherwise, use full paths.
outfile.write(infile.read()) # time: 2.1085190773010254s
shutil.copyfileobj(fd, wfd, 1024*1024*10) # time: 0.60599684715271s
A simple benchmark shows that the shutil performs better.
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value
method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
Right click on your my computer icon and the CPU will be listed on the properties page. Or open device manager and look at the CPU.
It must be an Intel processor that supports VT and NX bit (XD) - you can check your CPU # at http://ark.intel.com
Also make sure hyperV off bcdedit /set hypervisorlaunchtype off
XD bit is on bcdedit /set nx AlwaysOn
Use the installer from https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
If you're using Avast, disable "Enable hardware-assisted virtualization" under: Settings > Troubleshooting. Restart the PC and try to run the HAXM installation again
Yes:
<script type="text/javascript">
var counter = 0;
</script>
and
<button onclick="counter++">Increment</button>
Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:
root:~# python -V
Python 3.5.2
root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.5 3 auto mode
1 /usr/bin/python2.7 2 manual mode
2 /usr/bin/python3.5 3 manual mode
root:~# update-alternatives --remove python /usr/bin/python3.5
root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/bin/python2.7 2 auto mode
* 1 /usr/bin/python2.7 2 manual mode
Press <enter> to keep the current choice[*], or type selection number: 0
root:~# python -V
Python 2.7.12
root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.
Understand this has been solved, but the solution provided above might not work in all situation.
For my case,
<div style="height: 490px; position:relative; overflow:hidden">
<div id="map-canvas"></div>
</div>
I think double quotes works too:
SELECT "Business Name","Other Name" FROM your_Table
But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.
You are correct in thinking that display
is not animatable. It won't work, and you shouldn't bother including it in keyframe animations.
visibility
is technically animatable, but in a round about way. You need to hold the property for as long as needed, then snap to the new value. visibility
doesn't tween between keyframes, it just steps harshly.
.ele {_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
_x000D_
background-color: #ff6699;_x000D_
animation: 1s fadeIn;_x000D_
animation-fill-mode: forwards;_x000D_
_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
99% {_x000D_
visibility: hidden;_x000D_
}_x000D_
100% {_x000D_
visibility: visible;_x000D_
}_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
If you want to fade, you use opacity
. If you include a delay, you'll need visibility
as well, to stop the user from interacting with the element while it's not visible.
.ele {_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
_x000D_
background-color: #ff6699;_x000D_
animation: 1s fadeIn;_x000D_
animation-fill-mode: forwards;_x000D_
_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
100% {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
Both examples use animation-fill-mode
, which can hold an element's visual state after an animation ends.
array_slice() is best thing to try, following are the examples:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
It is simple, as a java, Android also supporting singleton. -
Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.
-> Static member : This contains the instance of the singleton class.
-> Private constructor : This will prevent anybody else to instantiate the Singleton class.
-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.
use getInstance() of Singleton class
public class Logger{
private static Logger objLogger;
private Logger(){
//ToDo here
}
public static Logger getInstance()
{
if (objLogger == null)
{
objLogger = new Logger();
}
return objLogger;
}
}
while use singleton -
Logger.getInstance();
What do you get when you do puts lines
? That will give you a clue.
By default File.open
opens the file in text mode, so your \r\n
characters will be automatically converted to \n
. Maybe that's the reason lines
are always equal to lines2
. To prevent Ruby from parsing the line ends use the rb
mode:
C:\> copy con lala.txt a file with many lines ^Z C:\> irb irb(main):001:0> text = File.open('lala.txt').read => "a\nfile\nwith\nmany\nlines\n" irb(main):002:0> bin = File.open('lala.txt', 'rb').read => "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n" irb(main):003:0>
But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read
.
I would recommend to call the script like this
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>
The js and css files must be treat differently
Put
jquery
as the first before otherJS scripts
at the bottom of<BODY>
tag
HTTP/1.1 specification
suggests that browsers download no more than two components in parallel per hostname. <head>
tags and let the rest including the jquery
to be called on the bottom <body>
tag.Put
CSS style
on top of<HEAD>
tag after the other more priority tags
HEAD
makes pages appear to be loading faster. This is because putting style sheets in the HEAD
allows the page to render progressively.css
sheets, it is better to put them all on the <head>
tag but let the style that shall be immediately rendered to be put in <style>
tags inside <HEAD>
and the rest in <body>
.You may also find other suggestion when you test your page like on Google PageSpeed Insight
There are more suitable functions for this in os
package. But if you have to use os.walk
, here is what I come up with
def walkdir(dirname):
for cur, _dirs, files in os.walk(dirname):
pref = ''
head, tail = os.path.split(cur)
while head:
pref += '---'
head, _tail = os.path.split(head)
print(pref+tail)
for f in files:
print(pref+'---'+f)
output:
>>> walkdir('.')
.
---file3
---file2
---my.py
---file1
---A
------file2
------file1
---B
------file3
------file2
------file4
------file1
---__pycache__
------my.cpython-33.pyc
To run it as a full daemon from a shell, you'll need to use setsid
and redirect its output. You can redirect the output to a logfile, or to /dev/null
to discard it. Assuming your script is called myscript.sh, use the following command:
setsid myscript.sh >/dev/null 2>&1 < /dev/null &
This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null
with your /path/to/logfile.
You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).
jQuery('#main').css('opacity') = '0.6';
should be
jQuery('#main').css('opacity', '0.6');
Update:
http://jsfiddle.net/GegMk/ if you type in the text box. Click away, the opacity changes.
The expression stringexpression = ''
yields:
TRUE
.. for ''
(or for any string consisting of only spaces with the data type char(n)
)
NULL
.. for NULL
FALSE
.. for anything else
So to check for: "stringexpression
is either NULL or empty":
(stringexpression = '') IS NOT FALSE
Or the reverse approach (may be easier to read):
(stringexpression <> '') IS NOT TRUE
Works for any character type including char(n)
. The manual about comparison operators.
Or use your original expression without trim()
, which is costly noise for char(n)
(see below), or incorrect for other character types: strings consisting of only spaces would pass as empty string.
coalesce(stringexpression, '') = ''
But the expressions at the top are faster.
Asserting the opposite is even simpler: "stringexpression
is neither NULL nor empty":
stringexpression <> ''
char(n)
This is about the data type char(n)
, short for: character(n)
. (char
/ character
are short for char(1)
/ character(1)
.) Its use is discouraged in Postgres:
In most situations
text
orcharacter varying
should be used instead.
Do not confuse char(n)
with other, useful, character types varchar(n)
, varchar
, text
or "char"
(with double-quotes).
In char(n)
an empty string is not different from any other string consisting of only spaces. All of these are folded to n spaces in char(n)
per definition of the type. It follows logically that the above expressions work for char(n)
as well - just as much as these (which wouldn't work for other character types):
coalesce(stringexpression, ' ') = ' '
coalesce(stringexpression, '') = ' '
Empty string equals any string of spaces when cast to char(n)
:
SELECT ''::char(5) = ''::char(5) AS eq1
, ''::char(5) = ' '::char(5) AS eq2
, ''::char(5) = ' '::char(5) AS eq3;
Result:
eq1 | eq2 | eq3
----+-----+----
t | t | t
Test for "null or empty string" with char(n)
:
SELECT stringexpression
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::char(5))
, ('')
, (' ') -- not different from '' in char(n)
, (NULL)
) sub(stringexpression);
Result:
stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3 ------------------+-----------+-------+-------+-----------+-----------+----------- foo | f | f | f | f | f | f | t | t | t | t | t | t | t | t | t | t | t | t null | null | t | t | t | t | t
Test for "null or empty string" with text
:
SELECT stringexpression
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::text)
, ('')
, (' ') -- different from '' in a sane character types
, (NULL)
) sub(stringexpression);
Result:
stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3 ------------------+-----------+-------+-------+-----------+-----------+----------- foo | f | f | f | f | f | f | t | t | t | t | f | f | f | f | f | f | f | f null | null | t | t | t | t | f
Related:
I think a for-loop should be a valid solution :
public int getIndexByname(String pName)
{
for(AuctionItem _item : *yourArray*)
{
if(_item.getName().equals(pName))
return *yourarray*.indexOf(_item)
}
return -1;
}
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();
. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox
and call it btnOK
. Set the DialogResult
property in the property window to DialogResult.OK
. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
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
This should work:
quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE
Have a look at the white-space
property, used like this:
th {
white-space: nowrap;
}
This will force the contents of <th>
to display on one line.
From linked page, here are the various options for white-space
:
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.
There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:
It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.
Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?
What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");
My app has a fragment to loading in 3 secs, but when the fist screen is preparing to show, I press home button and resume run it, it show the same error, so It edit my code and it ran very smooth:
new Handler().post(new Runnable() {
public void run() {
if (saveIns == null) {
mFragment = new Fragment_S1_loading();
getFragmentManager().beginTransaction()
.replace(R.id.container, mFragment).commit();
}
getActionBar().hide();
// Loading screen in 3 secs:
mCountDownTimerLoading = new CountDownTimer(3000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
if (saveIns == null) {// TODO bug when start app and press home
// button
getFragmentManager()
.beginTransaction()
.replace(R.id.container,
new Fragment_S2_sesstion1()).commitAllowingStateLoss();
}
getActionBar().show();
}
}.start();
}
});
NOTE: add commitAllowingStateLoss() instead of commit()
Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Example::Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.
Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/yourname/full-backup
In your case, for 2.30PM
,
30 14 * * * YOURCMD
To know more about cron, visit this website.
//if the problem is "just" to verify that the element exist in the xml-file before you //extract the value you could do like this
XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");
if (YOURTEMPVARIABLE.Count > 0 )
{
doctype = YOURTEMPVARIABLE[0].InnerXml;
}
else
{
doctype = "";
}
You could try this for a database SELECT query based on user input using PDO:
$param = $_GET['username'];
$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();
$result = $query -> fetch();
print_r($result);
This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function
fun! DelBlank()
let _s=@/
let l = line(".")
let c = col(".")
:g/^\n\{2,}/d
let @/=_s
call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>
For RHEL-mysql 5.5:
/etc/init.d/mysql stop
/etc/init.d/mysql start --skip-grant-tables
mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
mysql -uroot -pnewpwd
mysql>
I've posted this comment on a seperate StackOverflow thread, but thought it was worth repeating here:
For our in-house ASP.Net app, adding the "X-UA-Compatible" tag on the web page, in the web.config or in the code-behind made absolutely no difference.
The only thing that worked for us was to manually turn off this setting in IE8:
(Sigh.)
This problem only seems to happen with IE8 & IE9 on intranet sites. External websites will work fine and use the correct version of IE8/9, but for internal websites, IE9 suddenly decides it's actually IE7, and doesn't have any HTML 5 support.
No, I don't quite understand this logic either.
My reluctant solution has been to test whether the browser has HTML 5 support (by creating a canvas, and testing if it's valid), and displaying this message to the user if it's not valid:
It's not particularly user-friendly, but getting the user to turn off this annoying setting seems to be the only way to let them run in-house HTML 5 web apps properly.
Or get the users to use Chrome. ;-)
If it's only about getting the number of records (rows) I'd suggest using:
SELECT TABLE_ROWS
FROM information_schema.tables
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB
AND table_schema = DATABASE(); -- See comment below if > 1 DB
(at least for MySQL) instead.
Insertion:
INSERT INTO ... VALUES ('bob', MD5('bobspassword'));
retrieval:
SELECT ... FROM ... WHERE ... AND password=md5('hopefullybobspassword');
is how'd you'd do it directly in the queries. However, if your MySQL has query logging enabled, then the passwords' plaintext will get written out to this log. So... you'd want to do the MD5 conversion in your script, and then insert that resulting hash into the query.
Use the formula by tigeravatar:
=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50
as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).
To find all of those values, highlight col A. Data > Filter and choose Filter by color.
you can always make a bash alias to setup*.exe files in $home/.bashrc
cygwin 32bit
alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"
cygwin 64bit
alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"
now you can install packages with
cyg-get <package>
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.
Here are my test implementations:
import re
hex_digits = set("ABCDEF1234567890")
hex_match = re.compile(r'^[A-F0-9]+\Z')
hex_search = re.compile(r'[^A-F0-9]')
def test_set(input):
return set(input) <= hex_digits
def test_not_any(input):
return not any(c not in hex_digits for c in input)
def test_re_match1(input):
return bool(re.compile(r'^[A-F0-9]+\Z').match(input))
def test_re_match2(input):
return bool(hex_match.match(input))
def test_re_match3(input):
return bool(re.match(r'^[A-F0-9]+\Z', input))
def test_re_search1(input):
return not bool(re.compile(r'[^A-F0-9]').search(input))
def test_re_search2(input):
return not bool(hex_search.search(input))
def test_re_search3(input):
return not bool(re.match(r'[^A-F0-9]', input))
And the tests, in Python 3.4.0 on Mac OS X:
import cProfile
import pstats
import random
# generate a list of 10000 random hex strings between 10 and 10009 characters long
# this takes a little time; be patient
tests = [ ''.join(random.choice("ABCDEF1234567890") for _ in range(l)) for l in range(10, 10010) ]
# set up profiling, then start collecting stats
test_pr = cProfile.Profile(timeunit=0.000001)
test_pr.enable()
# run the test functions against each item in tests.
# this takes a little time; be patient
for t in tests:
for tf in [test_set, test_not_any,
test_re_match1, test_re_match2, test_re_match3,
test_re_search1, test_re_search2, test_re_search3]:
_ = tf(t)
# stop collecting stats
test_pr.disable()
# we create our own pstats.Stats object to filter
# out some stuff we don't care about seeing
test_stats = pstats.Stats(test_pr)
# normally, stats are printed with the format %8.3f,
# but I want more significant digits
# so this monkey patch handles that
def _f8(x):
return "%11.6f" % x
def _print_title(self):
print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream)
print('filename:lineno(function)', file=self.stream)
pstats.f8 = _f8
pstats.Stats.print_title = _print_title
# sort by cumulative time (then secondary sort by name), ascending
# then print only our test implementation function calls:
test_stats.sort_stats('cumtime', 'name').reverse_order().print_stats("test_*")
which gave the following results:
50335004 function calls in 13.428 seconds Ordered by: cumulative time, function name List reduced from 20 to 8 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.005233 0.000001 0.367360 0.000037 :1(test_re_match2) 10000 0.006248 0.000001 0.378853 0.000038 :1(test_re_match3) 10000 0.010710 0.000001 0.395770 0.000040 :1(test_re_match1) 10000 0.004578 0.000000 0.467386 0.000047 :1(test_re_search2) 10000 0.005994 0.000001 0.475329 0.000048 :1(test_re_search3) 10000 0.008100 0.000001 0.482209 0.000048 :1(test_re_search1) 10000 0.863139 0.000086 0.863139 0.000086 :1(test_set) 10000 0.007414 0.000001 9.962580 0.000996 :1(test_not_any)
where:
The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different.
It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.
test_set was twice as slow as re_search and thrice as slow as re_match
test_not_any was a full order of magnitude slower than test_set
TL;DR: Use re.match or re.search
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.
The exact instructions on how to achieve this will depend on your web server.
The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)
For now, use an EditText
. Use android:inputType="number"
to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())
).
In the future, you might consider a NumberPicker
widget, once that becomes available (slated to be in Honeycomb).
This error message...
FileNotFoundError: [WinError 2] The system cannot find the file specified
...implies that your program was unable to locate the specified file and while handling the exception the following exception occurred:
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
... which implies that your program was unable to locate the GeckoDriver in the process of initiating/spawnning a new Browsing Context i.e. Firefox Browser session.
You can download the latest GeckoDriver from mozilla / geckodriver, unzip/untar and store the GeckoDriver binary/executable anywhere with in your system passing the absolute path of the GeckoDriver through the key executable_path
as follows:
from selenium import webdriver
driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
driver.get('http://google.com/')
In case firefox is not installed at the default location (i.e. installed at a custom location) additionally you need to pass the absolute path of firefox
binary through the attribute binary_location
as follows:
# An Windows example
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get('http://google.com/')
You could use Function.name
:
In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name
You could use Function.callee
:
The native arguments.caller
method has been deprecated, but most browsers support Function.caller
, which will return the actual invoking object (its body of code):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller
You could create a source map:
If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys()
and your array of strings, or look into Mozilla's source maps library on GitHub, for bigger projects:
https://github.com/mozilla/source-map
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.
In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name
, which is the logged in user identifier as set during the ASP.NET authentication.
However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.
Lets assume our application uses a userId
to identify each user. Now, we need to send message to a specific user. We have userId
and message
, but SignalR must also know the mapping between our userId and the connection.
To achieve this, first we need to create a new class which implements IUserIdProvider
:
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
// your logic to fetch a user identifier goes here.
// for example:
var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
return userId.ToString();
}
}
The second step is to tell SignalR to use our CustomUserIdProvider
instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var idProvider = new CustomUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
Now, you can send message to a specific user using his userId
as mentioned in the documentation, like:
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
Hope this helps.
The easiest solution is to just run your own counter thus:
int i = 0;
for (String s : stringArray) {
doSomethingWith(s, i);
i++;
}
The reason for this is because there's no actual guarantee that items in a collection (which that variant of for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).
See for example, the following code:
import java.util.*;
public class TestApp {
public static void AddAndDump(AbstractSet<String> set, String str) {
System.out.println("Adding [" + str + "]");
set.add(str);
int i = 0;
for(String s : set) {
System.out.println(" " + i + ": " + s);
i++;
}
}
public static void main(String[] args) {
AbstractSet<String> coll = new HashSet<String>();
AddAndDump(coll, "Hello");
AddAndDump(coll, "My");
AddAndDump(coll, "Name");
AddAndDump(coll, "Is");
AddAndDump(coll, "Pax");
}
}
When you run that, you can see something like:
Adding [Hello]
0: Hello
Adding [My]
0: Hello
1: My
Adding [Name]
0: Hello
1: My
2: Name
Adding [Is]
0: Hello
1: Is
2: My
3: Name
Adding [Pax]
0: Hello
1: Pax
2: Is
3: My
4: Name
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
To access the properties of an object without knowing the names of those properties you can use a for ... in
loop:
for(key in data) {
if(data.hasOwnProperty(key)) {
var value = data[key];
//do something with value;
}
}
Solved it as follows,
in CSS
#my{
zoom: 100%;
}
Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.
Though this is not the best way to do it, there is another effective solution
Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.
Edit: Since this turned out to be a popular answer, I'm adding the disclaimer that @crush mentioned in a comment below. If you use this work around, be aware that you're opening yourself up for an XSS vulnerability. Only use this solution if you know what you're doing and can be certain of the HTML content in the attribute.
The easiest way to do this is to supply a function to the content
option that overrides the default behavior:
$(function () {
$(document).tooltip({
content: function () {
return $(this).prop('title');
}
});
});
Example: http://jsfiddle.net/Aa5nK/12/
Another option would be to override the tooltip widget with your own that changes the content
option:
$.widget("ui.tooltip", $.ui.tooltip, {
options: {
content: function () {
return $(this).prop('title');
}
}
});
Now, every time you call .tooltip
, HTML content will be returned.
Example: http://jsfiddle.net/Aa5nK/14/
Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.
I faced this problem today, and the issue was I was preventing event default action in document onclick:
document.onclick = function(e) {
e.preventDefault();
}
Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:
document.onclick = function(e) {
if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}
In Python, overloading is not an applied concept. However, if you are trying to create a case where, for instance, you want one initializer to be performed if passed an argument of type foo
and another initializer for an argument of type bar
then, since everything in Python is handled as object, you can check the name of the passed object's class type and write conditional handling based on that.
class A:
def __init__(self, arg)
# Get the Argument's class type as a String
argClass = arg.__class__.__name__
if argClass == 'foo':
print 'Arg is of type "foo"'
...
elif argClass == 'bar':
print 'Arg is of type "bar"'
...
else
print 'Arg is of a different type'
...
This concept can be applied to multiple different scenarios through different methods as needed.
You can use the by()
function:
by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)
But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?
Windows 10
It could be that your server doesn't start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:
pg_ctl -D "C:\Program Files\PostgreSQL\11.4\data" start
You need to be inside "C:\Program Files\PostgreSQL\11.4\bin" directory to execute the above command.
EX:
You still need to be inside the bin directory to work with psql
Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.
The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.
try this
<table style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%;">
<tr>
<td>
<div style="text-align: left; display: inline-block;">
Your Html code Here
</div>
</td>
</tr>
</table>
Or this
<div style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%; display: table">
<div style="display: table-row">
<div style="display: table-cell; vertical-align:middle;">
<div style="text-align: left; display: inline-block;">
Your Html code here
</div>
</div>
</div>
</div>
There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.
void RunFooAsync(..., Action<bool> callback) {
// do some stuff
bool result = ...
if(callback != null) callback(result);
}
Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.
Also, if you are using the TPL, you can use ContinueWith
:
Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
bool result = task.Result;
// do something with that
});
In Python 3, TemporaryDirectory in the tempfile module can be used.
This is straight from the examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
If you would like to keep the directory a bit longer, you could do something like this:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest
may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory...
if you rely on this, though.
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
<head>
<link rel="shortcut icon" href="favicon.ico">
</head>
What are -moz- and -webkit-?
CSS properties starting with -webkit-
, -moz-
, -ms-
or -o-
are called vendor prefixes.
Why do different browsers add different prefixes for the same effect?
A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:
Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.
Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.
Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds
-ms-grid
.The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.
UPDATE AS OF THE YEAR 2016
As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.
As mentioned in this glossary about Mozilla's view on Vendor Prefix
on May 3, 2016
,
Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.
For example, just a few years ago, to set a rounded corner on a box you had to write:
-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;
But now that browsers have come to fully support this feature, you really only need the standardized version:
border-radius: 10px 5px;
Finding the right rules for all browsers
As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.
You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.
Input:
a {
column-count: 3;
column-gap: 10px;
column-fill: auto;
}
Output:
a {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-fill: auto;
column-fill: auto;
}
How to address your textbox depends on the HTML-code:
<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />
If you use the 'id' attribute:
var textbox = document.getElementById('Tue');
for 'name':
var textbox = document.getElementsByName('Tue')[0]
(Note that getElementsByName() returns all elements with the name as array, therefore we use [0] to access the first one)
Then, use the 'value' attribute:
textbox.value = 'Foobar';
Today NodeJS supports new async/await
syntax. This is an easy syntax and makes the life much easier
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)
Learn more:
public static class DateTool
{
public static DateTime Min(DateTime x, DateTime y)
{
return (x.ToUniversalTime() < y.ToUniversalTime()) ? x : y;
}
public static DateTime Max(DateTime x, DateTime y)
{
return (x.ToUniversalTime() > y.ToUniversalTime()) ? x : y;
}
}
This allows the dates to have different 'kinds' and returns the instance that was passed in (not returning a new DateTime constructed from Ticks or Milliseconds).
[TestMethod()]
public void MinTest2()
{
DateTime x = new DateTime(2001, 1, 1, 1, 1, 2, DateTimeKind.Utc);
DateTime y = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local);
//Presumes Local TimeZone adjustment to UTC > 0
DateTime actual = DateTool.Min(x, y);
Assert.AreEqual(x, actual);
}
Note that this test would fail East of Greenwich...
Probably the simplest way would be to pull the XXX stuff into a branch in YYY and then merge it into master:
In YYY:
git remote add other /path/to/XXX
git fetch other
git checkout -b ZZZ other/master
mkdir ZZZ
git mv stuff ZZZ/stuff # repeat as necessary for each file/dir
git commit -m "Moved stuff to ZZZ"
git checkout master
git merge ZZZ --allow-unrelated-histories # should add ZZZ/ to master
git commit
git remote rm other
git branch -d ZZZ # to get rid of the extra branch before pushing
git push # if you have a remote, that is
I actually just tried this with a couple of my repos and it works. Unlike Jörg's answer it won't let you continue to use the other repo, but I don't think you specified that anyway.
Note: Since this was originally written in 2009, git has added the subtree merge mentioned in the answer below. I would probably use that method today, although of course this method does still work.
Solution 1 : Creation of a JniLibs folder
Create a folder called “jniLibs” into your app and the folders containing your *.so inside. The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.
Solution 2 : Modification of the build.gradle file
If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !
In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
You will have more explanations, with screenshots to help you here ( Step 6 ):
http://blog.guillaumeagis.eu/setup-andengine-with-android-studio/
EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.
If flutter SDK is already downloaded in the system, then just add path using the below command. This tested on MAC OS
export PATH='sdkpath':$PATH
Eg:
export PATH='/Users/apple/dev/flutter/sdk/flutter/bin':$PATH
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
It's an older question, but if anyone has a problem with setting this, their documentation is outdated. I made a copy of the php.ini
file named php5.ini
and now it works.
Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
__str__
is only called when a string representation is required of an object.
For example str(uno)
, print "%s" % uno
or print uno
However, there is another magic method called __repr__
this is the representation of an object. When you don't explicitly convert the object to a string, then the representation is used.
If you do this uno.neighbors.append([[str(due),4],[str(tri),5]])
it will do what you expect.
You can pass this
when you call the function
<button onclick="doSomething('param',this)" id="id_button">action</button>
<script>
function doSomething(param,me){
var source = me
console.log(source);
}
</script>
Like @Sunkas wrote, performSelector:withObject:afterDelay:
is the pendant to the dispatch_after
just that it is shorter and you have the normal objective-c
syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject
and you will receive it in the selector
you call:
[self performSelector:@selector(testStringMethod:)
withObject:@"Test Test"
afterDelay:0.5];
- (void)testStringMethod:(NSString *)string{
NSLog(@"string >>> %@", string);
}
If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:
If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
For boolean fields in Rails 3.2.6 at least, this will work in your migration.
def change
add_column :users, :eula_accepted, :boolean, default: false
end
Putting a 1
or 0
for a default will not work here, since it is a boolean field. It must be a true
or false
value.
I know this topic is old, but I thought I could add something to it.
I could not make an Update with Select query work using SQL in MS Access 2010. I used Tomalak's suggestion to make this work. I had a screenshot, but am apparently too much of a newb on this site to be able to post it.
I was able to do this using the Query Design tool, but even as I was looking at a confirmed successful update query, Access was not able to show me the SQL that made it happen. So I could not make this work with SQL code alone.
I created and saved my select query as a separate query. In the Query Design tool, I added the table I'm trying to update the the select query I had saved (I put the unique key in the select query so it had a link between them). Just as Tomalak had suggested, I changed the Query Type to Update. I then just had to choose the fields (and designate the table) I was trying to update. In the "Update To" fields, I typed in the name of the fields from the select query I had brought in.
This format was successful and updated the original table.
The Solution from https://github.com/gitlabhq/gitlab-shell/issues/46 worked for me.
By setting the permissions:
chmod 700 /home/git/.ssh
chmod 600 /home/git/.ssh/authorized_keys
password prompt disappears.
I wanted to add more details about how the @Valid
works, especially in spring.
Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid
works incase the link goes down.
The @Valid
annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:
So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.
For example, suppose I had controller method like this:
@RestController
class ValidateRequestBodyController {
@PostMapping("/validateBody")
ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
return ResponseEntity.ok("valid");
}
}
So this is a POST request which takes in a response body, and we're mapping that response body to a class Input
.
Here's the class Input
:
class Input {
@Min(1)
@Max(10)
private int numberBetweenOneAndTen;
@Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
private String ipAddress;
// ...
}
The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen
is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.
side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.
Here's an example of validating a query variable and path variable:
@RestController
@Validated
class ValidateParametersController {
@GetMapping("/validatePathVariable/{id}")
ResponseEntity<String> validatePathVariable(
@PathVariable("id") @Min(5) int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameter")
ResponseEntity<String> validateRequestParameter(
@RequestParam("param") @Min(5) int param) {
return ResponseEntity.ok("valid");
}
}
In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5)
right on the parameter instead of using @Valid
.
In your string file use this
<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>
And in your code use as accordingly
coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
, rewardPoints.getConversion_rate(), getString(R.string.rs)));
You can do this with psutil which is cross-platform:
import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]
It is also worth noting the sorted()
function:
for x in sorted(list):
print x
This returns a new, sorted version of a list without changing the original list.
There is a new option called validateStatus
in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:
const {status} = axios.get('foo.com', {validateStatus: () => true})
OAuth 2.0 spec doesn't define the part. But there could be couple of options:
When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.
Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.
I have used wxWidgets for small project and I loved it. Qt is another good choice but for commercial use you would probably need to buy a licence. If you write in C++ don't use Win32 API as you will end up making it object oriented. This is not easy and time consuming. Also Win32 API has too many macros and feels over complicated for what it offers.