Here is a SUMMARY of all the major answers above (or maybe below later :)
For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.
For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).
For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)
There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.
As this is only tagged sql
(which does not indicate any specific DBMS), here is a solution for Postgres:
select d::date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):
create table calendar
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
1)Please add multiDexEnabled true 2)if you get compilation error then check your app level build.gradle weather same dependencies are implemented with different versions. 3)Remove one if you find same dependencies.
android { compileSdkVersion 28 defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
hope it works fine :) Happy Coding
http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx
// Find a book by its ID.
Book result = Books.Find(
delegate(Book bk)
{
return bk.ID == IDtoFind;
}
);
if (result != null)
{
DisplayResult(result, "Find by ID: " + IDtoFind);
}
else
{
Console.WriteLine("\nNot found: {0}", IDtoFind);
}
.phtml
was the standard file extension for PHP 2 programs. .php3
took over for PHP 3. When PHP 4 came out they switched to a straight .php
.
The older file extensions are still sometimes used, but aren't so common.
If nginx_ajp_module is used, try adding
ajp_read_timeout 10m;
in nginx.conf file.
If you wish to open the batch file in another window, use start
. This way, you can basically run two scripts at the same time. In other words, you don't have to wait for the script you just called to finish.
All examples below work:
start batch.bat
start call batch.bat
start cmd /c batch.bat
If you want to wait for the script to finish, try start /w call batch.bat
, but the batch.bat has to end with exit
.
Array.from(element.parentNode.children).indexOf(element)
element.parentNode.children
? Returns the brothers of element
, including that element.
Array.from
? Casts the constructor of children
to an Array
object
indexOf
? You can apply indexOf
because you now have an Array
object.
Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.
Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.
Not since Lollipop. Starting with Android 5.0, the guidelines say:
Notification icons must be entirely white.
Even if they're not, the system will only consider the alpha channel of your icon, rendering them white
The only way to have a coloured icon on Lollipop is to lower your targetSdkVersion
to values <21
, but I think you would do better to follow the guidelines and use white icons only.
If you still however decide you want colored icons, you could use the DrawableCompat.setTint method from the new v4 support library.
Just go to the combo box properties - DropDownStyle and change it to "DropDownList"
This will make visible the first item.
This is simple code, but of course a little bit slower.
String s = ...;
int countDollar = s.length()-s.replaceAll("\\$","").length();
int counta = s.length()-s.replaceAll("a","").length();
An even better answer is here in a duplicate question
The easiest would be to use a regular expression with g
flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences of foo
with bar
in the string str
. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
re = new RegExp(pattern, "g");
There is a problem with using Solution 1 while appling it on only column in rows. Would like to improve Solution 1.
[class^="col-"]:not([class*="-12"]){
margin-bottom: -99999px;
padding-bottom: 99999px;
}
(Sorry, can't comment Popnoodles's anwer. I have not enough reputations)
You don't fetch a branch, you fetch an entire remote:
git fetch origin
git merge origin/an-other-branch
Think of it as just another safety level. You can design your table without foreign key relationships - perfectly valid - and ensure existence of associated entities entirely on the business layer. However, foreign keys are considered good design practice because they add another constraint level in case something messes up on the business layer. Same goes for field size limitation and not using varchar MAX.
You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.
On the other hand, you have PAGE that seems active and works in python 2.7 and py3k
As you indicate on your comment, none of these use the grid
geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.
It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:
By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.
if (listA.Except(listB).Any())
This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>
If you are using Python 3.6+
you can make use of the new so called f-strings
which stands for formatted strings and it can be used by adding the character f
at the beginning of a string to identify this as an f-string.
price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!
The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:
Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen
No doubt that the new f-strings
are more readable, as you don't have to remap the strings, but is it faster though as stated in the aformentioned quote?
price = 123
name = "Jerry"
def new():
x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
def old():
x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776 #new
> 5.861819514350163 #old
Running 10 Million test's it seems that the new f-strings
are actually faster in mapping.
For a dict we can use a for loop to iterate through the index
, key
and value
:
dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
## Code here ##
In general class loaders do not allow for scanning through all the classes on the classpath. But usually the only used class loader is UrlClassLoader from which we can retrieve the list of directories and jar files (see getURLs) and open them one by one to list available classes. This approach, called class path scanning, is implemented in Scannotation and Reflections.
Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);
Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:
// package-info.java
@IndexSubclasses
package my.package;
// your code
Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");
Notice that no additional setup is needed as the scanning is fully automated thanks to Java compiler automatically discovering any processors found on the classpath.
If you are using display: flex
for whatever reason and need on browsers like Edge/IE, you can instead use:
display: inline-flex
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .
#include<stdio.h>
#define n 3
struct {
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}bodies[n];
There are a few different ways to accomplish this, I'll outline my favourites.
Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.
My preferred method is to define a graphic for the button in css:
.toggle-button {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}
.toggle-button:selected {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
OR use the attached css to define a background image.
// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
.toggle-button:selected {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.
And some sample code:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImage extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
toggle.getStylesheets().add(this.getClass().getResource(
"imagetogglebutton.css"
).toExternalForm());
toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
Some advantages of doing this are:
An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImageViaGraphic extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
final Image unselected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
);
final Image selected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
);
final ImageView toggleImage = new ImageView();
toggle.setGraphic(toggleImage);
toggleImage.imageProperty().bind(Bindings
.when(toggle.selectedProperty())
.then(selected)
.otherwise(unselected)
);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
The code based approach has the advantage that you don't have to use css if you are unfamilar with it.
For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.
In CPython, the number of arguments is
a_method.func_code.co_argcount
and their names are in the beginning of
a_method.func_code.co_varnames
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable way to admit "pass-through" arguments is to define your function with the signature func(*args, **kwargs)
. This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.
To answer your questions.
The option 1 sounds not too efficient. What if there is no space in the client to do a clone and then remove the .git
folder?
Today I found myself trying to do this, where the client is a Raspberry Pi with almost no space left. Furthermore, I also want to exclude some heavy folder from the repository.
Option 2 and others answers here do not help in this scenario. Neither git archive
(because require to commit a .gitattributes
file, and I don't want to save this exclusion in the repository).
Here I share my solution, similar to option 3, but without the need of git clone
:
tmp=`mktemp`
git ls-tree --name-only -r HEAD > $tmp
rsync -avz --files-from=$tmp --exclude='fonts/*' . raspberry:
Changing the rsync
line for an equivalent line for compress will also work as a git archive
but with a sort of exclusion option (as is asked here).
I also struggled a lot with different options on how to detect in Javascript whether the page is displayed on a touch screen device or not. IMO, as of now, no real option exists to detect the option properly. Browsers either report touch events on desktop machines (because the OS maybe touch-ready), or some solutions don't work on all mobile devices.
In the end, I realized that I was following the wrong approach from the start: If my page was to look similar on touch and non-touch devices, I maybe shouldn't have to worry about detecting the property at all: My scenario was to deactivate tooltips over buttons on touch devices as they lead to double-taps where I wanted a single tap to activate the button.
My solution was to refactor the view so that no tooltip was needed over a button, and in the end I didn't need to detect the touch device from Javascript with methods that all have their drawbacks.
In other way you can get ddl of table creation from command listed below, and execute the creation.
SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL
TYPE
is TABLE
,PROCEDURE
etc.With this command you can get majority of ddl from database objects.
For better understand how it works!
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
if(n == 0)
{
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
}
else if(n == 1)
{
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
}
else if (n == 2)
{
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
}
else if (n == -1)
{
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
}
OR
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
switch (n) {
case 0:
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
break;
case 1:
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
break;
case 2:
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
break;
case -1:
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
break;
default:
break;
}
You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)
I ran into this scenario when trying to load a type (via reflection) in an assembly that was built against a different version of a reference common to the application where this error popped up.
As I'm sure the type is unchanged in both versions of the assembly I ended up creating a custom assembly resolver that maps the missing assembly to the one my application has already loaded. Simplest way is to add a static constructor to the program class like so:
using System.Reflection
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {
AssemblyName requestedName = new AssemblyName(e.Name);
if (requestedName.Name == "<AssemblyName>")
{
// Load assembly from startup path
return Assembly.LoadFile($"{Application.StartupPath}\\<AssemblyName>.dll");
}
else
{
return null;
}
};
}
This of course assumes that the Assembly is located in the startup path of the application and can easily be adapted.
Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Directive:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.
For a time field, use:
import time
time.strftime('%Y-%m-%d %H:%M:%S')
I think strftime also applies to datetime.
Checkbox
You can create your own CheckBox control extending UIButton with Swift:
import UIKit
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
// Bool property
var isChecked: Bool = false {
didSet {
if isChecked == true {
self.setImage(checkedImage, for: UIControl.State.normal)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
self.isChecked = false
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
And then add it to your views with Interface Builder:
Radio Buttons
Radio Buttons can be solved in a similar way.
For example, the classic gender selection Woman - Man:
import UIKit
class RadioButton: UIButton {
var alternateButton:Array<RadioButton>?
override func awakeFromNib() {
self.layer.cornerRadius = 5
self.layer.borderWidth = 2.0
self.layer.masksToBounds = true
}
func unselectAlternateButtons() {
if alternateButton != nil {
self.isSelected = true
for aButton:RadioButton in alternateButton! {
aButton.isSelected = false
}
} else {
toggleButton()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
unselectAlternateButtons()
super.touchesBegan(touches, with: event)
}
func toggleButton() {
self.isSelected = !isSelected
}
override var isSelected: Bool {
didSet {
if isSelected {
self.layer.borderColor = Color.turquoise.cgColor
} else {
self.layer.borderColor = Color.grey_99.cgColor
}
}
}
}
You can init your radio buttons like this:
override func awakeFromNib() {
self.view.layoutIfNeeded()
womanRadioButton.selected = true
manRadioButton.selected = false
}
override func viewDidLoad() {
womanRadioButton?.alternateButton = [manRadioButton!]
manRadioButton?.alternateButton = [womanRadioButton!]
}
Hope it helps.
We produced the 'Barcodes' application for the iPhone. It can decode QR Codes. The source code is available from the zxing project; specifically, you want to take a look at the iPhone client and the partial C++ port of the core library. The port is a little old, from circa the 0.9 release of the Java code, but should still work reasonably well.
If you need to scan other formats, like 1D formats, you could continue the port of the Java code within this project to C++.
EDIT: Barcodes and the iphone
code in the project were retired around the start of 2014.
Even though is not the fastest choice, if performance is not an issue you can use:
sum(~np.isnan(data))
.
In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop
In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop
In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop
Official Documentation on facebook developer site:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
Yes Go does accept first-class functions.
See the article "First Class Functions in Go" for useful links.
The Heroku CLI has an easy shortcut for this. For an app named 'falling-wind-1624':
$ heroku git:remote -a falling-wind-1624
Git remote heroku added.
See https://devcenter.heroku.com/articles/git#creating-a-heroku-remote
You can use somthing like this.
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
If you like it short simply use a RegExp:
var streetAddress = /[^,]*/.exec(addy)[0];
You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.
def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
"""
Reads a .properties file and returns the key value pairs as dictionary.
if key value is specified, then it will return its value alone.
"""
with open(propertiesFile) as f:
l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
d = {key.strip(): value.strip() for key, value in l}
if key:
return d[key]
else:
return d
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
This becomes a one-liner if you download File Checksum Integrity Verifier (FCIV) from Microsoft.
I downloaded FCIV from here: Availability and description of the File Checksum Integrity Verifier utility
Run the following command. I had ten files to check.
Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}
try putting both images next to each other. Like this:
<div id="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a><a href="https://twitter.com"><img src="images/twitter.png"></a>
</div>
I think the number of lines added is highly dependent upon the state of the project, the rate of adding to a new project will be much higher than the rate of a starting project.
The work is different between the two - at a large project you usually spend most of the time figuring the relationships between the parts, and only a small amount to actually changing/adding. whereas in a new project - you mostly write... until it's big enough and the rate decreases.
Danield's answer is good, but it can only be used when the div fills the whole viewport, or by using a bit of calc
, can be used if the width and height of the other content in the viewport is known.
However, by combining the margin-bottom
trick with the method in the aforementioned answer, the problem can be reduced to just having to know the height of the other content. This is useful if you have a fixed height header, but the width of the sidebar, for example, is not known.
body {_x000D_
margin: 0;_x000D_
margin-top: 100px; /* simulating a header */_x000D_
}_x000D_
_x000D_
main {_x000D_
margin: 0 auto;_x000D_
max-width: calc(200vh - 200px);_x000D_
}_x000D_
_x000D_
section {_x000D_
padding-bottom: 50%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div {_x000D_
position:absolute;_x000D_
background-color: red;_x000D_
top: 0;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
}
_x000D_
<main>_x000D_
<section>_x000D_
<div></div>_x000D_
</section>_x000D_
</main>
_x000D_
Here it is in a jsfiddle using scss, which makes it more obvious where the values come from.
Without you providing any specific error message, it's hard to give specific suggestions.
However, I was using the same example and was getting a permissions exception on File.OpenWrite - using the localFileName variable, because using Path.GetFile was pointing to a location that obviously would not have permissions for opening a file > C:\ProgramFiles\IIS(Express)\filename.doc
I found that using System.IO.Path.GetFileName is not correct, use System.IO.Path.GetFullPath instead, point to your file starting with "C:\..."
Also open your solution in FileExplorer and grant permissions to asp.net for the file or any folders holding the file. I was able to download my file at that point.
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
I got a similar problem.
Due to timeout !
Timeout can be indicated like this :
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => "POST",
'content' => http_build_query($data2),
'timeout' => 30,
),
);
$context = stream_context_create($options); $retour =
$retour = @file_get_contents("http://xxxxx.xxx/xxxx", false, $context);
Ubuntu 17.10 default doesn't have the ~/.vimrc
file, we need create it and put the setting colorscheme color_scheme_name
in it.
By the way, colorscheme desert
is good scheme to choose.
Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:
domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ include:/\n/g' | \
tail -n+2)
for domain in $domainsToDig ; do
dig @8.8.8.8 $domain TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ ip.:/\n/g' | \
tail -n+2
done
The WebIntoApp.com V.2 allows you to convert HTML5 / JS / CSS into a mobile app for Android APK (free) and iOS.
(I'm the author)
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
Before submitting the form, call tinyMCE.triggerSave();
It comes down to whether the feature is used by one person or if others are working off of it.
You can force the push after the rebase if it's just you:
git push origin feature -f
However, if others are working on it, you should merge and not rebase off of master.
git merge master
git push origin feature
This will ensure that you have a common history with the people you are collaborating with.
On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.
This is my article on the subject called branch per feature.
Hope this helps.
In my case, on a Windows box, my TCP/IP stack seems to have needed to be reset. Resetting the TCP/IP stack of the client PC caused git to start behaving properly again. Run this command in Administrator mode at a command prompt and retry the git command:
netsh int ip reset
Manually disabling and re-enabling the network adapter via the Control Panel produces a similar result.
I suspect DNS resolution problems inside the TCP stack on my Windows box.
If you do <form action="identification" >
for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post">
and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........
I have solved my problem by this way:
Edit the c:\php\php.ini file:
change extension_dir = "ext" into extension_dir = "c:\php\ext" (please write
ur own path)
I Hope it will work for u.
If your site is not live yet, and you just want to update the stylesheet at your pleased intervals, then use this:
Ctrl + F5
This will force your browser to reload and refresh all the resources related to the website's page.
So everytime you change something in your stylesheet and you wanna view the new results, use this.
On Mac OS Chrome use: Command + Shift + R.
Bundler now has a bundle remove GEM_NAME
command (since v1.17.0, 25 October 2018).
Use TextView
inside a ScrollView
<ScrollView
android:id="@+id/ScrollView01"
android:layout_width="wrap_content"
android:layout_height="150dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</ScrollView>
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
Here is one more possible way using reshape
:
a_norm = (a/a.sum(axis=1).reshape(-1,1)).round(3)
print(a_norm)
Or using None
works too:
a_norm = (a/a.sum(axis=1)[:,None]).round(3)
print(a_norm)
Output:
array([[0. , 0.333, 0.667],
[0.25 , 0.333, 0.417],
[0.286, 0.333, 0.381]])
Target>Build Setting>Product name
You can also make an exception for leaving the page via submitting a particular form:
$(window).bind('beforeunload', function(){
return "Do you really want to leave now?";
});
$("#form_id").submit(function(){
$(window).unbind("beforeunload");
});
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
Change your ref into: ref='title'
and delete name='title'
Then delete var title = this.title
and write:
console.log(this.refs.title.value)
Also you should add .bind(this)
to this.onSubmit
(It worked in my case which was quite similar, but instead of onClick
I had onSubmit={...}
and it was put in form ( <form onSubmit={...} ></form>)
)
You can use Apache Commons Math:
Precision.round(double x, int scale)
I've found that the solution the works best for me is to just perform the merge and abort it if there are conflicts. This particular syntax feels clean and simple to me. This is Strategy 2 below.
However, if you want to ensure you don't mess up your current branch, or you're just not ready to merge regardless of the existence of conflicts, simply create a new sub-branch off of it and merge that:
git checkout mybranch
git checkout -b mynew-temporary-branch
git merge some-other-branch
That way you can simply throw away the temporary branch if you just want to see what the conflicts are. You don't need to bother "aborting" the merge, and you can go back to your work -- simply checkout 'mybranch' again and you won't have any merged code or merge conflicts in your branch.
This is basically a dry-run.
git checkout mybranch
git merge some-other-branch
If git reports conflicts (and ONLY IF THERE ARE conflicts) you can then do:
git merge --abort
If the merge is successful, you cannot abort it (only reset).
If you're not ready to merge, use the safer way above.
[EDIT: 2016-Nov - I swapped strategy 1 for 2, because it seems to be that most people are looking for "the safe way". Strategy 2 is now more of a note that you can simply abort the merge if the merge has conflicts that you're not ready to deal with. Keep in mind if reading comments!]
I think you should also implement the error function of the $.ajax method.
error(XMLHttpRequest, textStatus, errorThrown)Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
},
error: function(xhr, statusText, err){
alert("Error:" + xhr.status);
}
});
Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup
To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression
Sometimes I need to extract several command line parameters, but not all of them and not from the first one. Let's assume the following call:
Test.bat uno dos tres cuatro cinco seis siete
Of course, the extension ".bat" is not needed at least you have test.exe in same folder. What we want is to get the output "tres cuatro cinco" (no matter if one line or three). The goal is that only I need three parameters and starting in the third one. In order to have a simple example the action for each one is just "echo", but you can think in some other more complex action over the selected parameters.
I've produced some examples, (options) in order you can see which one you consider better for you. Unfortunately, there is not a nice (or I don't know about) way based on a for loop over the range like "for %%i in (%3, 1, %5)".
@echo off
setlocal EnableDelayedExpansion
echo Option 1: one by one (same line)
echo %3, %4, %5
echo.
echo Option 2: Loop For one by one
for %%a in (%3, %4, %5) do echo %%a
echo.
echo Option 3: Loop For with check of limits
set i=0
for %%a in (%*) do (
set /A i=i+1
If !i! GTR 2 if !i! LSS 6 echo %%a
)
echo.
echo Option 4: Loop For with auxiliary list
for /l %%i in (3,1,5) do (
set a=%%i
set b=echo %%
set b=!b!!a!
call !b!
)
echo.
echo Option 5: Assigning to an array of elements previously
set e[0]=%0
set i=0
for %%a in (%*) do (
set /A i=i+1
set e[!i!]=%%a
)
for /l %%i in (3,1,5) do (
echo !e[%%i]!
)
echo.
echo Option 6: using shift and goto loop. It doesn't work with for loop
set i=2
:loop6
set /A i=i+1
echo %3
shift
If %i% LSS 5 goto :loop6
Probably you can find more options or combine several ones. Enjoy them.
What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL.
Here an example: (I used a procedure instead of a function, like @Thilo did)
create or replace procedure myprocedure(retval in out sys_refcursor) is
begin
open retval for
select TABLE_NAME from user_tables;
end myprocedure;
declare
myrefcur sys_refcursor;
tablename user_tables.TABLE_NAME%type;
begin
myprocedure(myrefcur);
loop
fetch myrefcur into tablename;
exit when myrefcur%notfound;
dbms_output.put_line(tablename);
end loop;
close myrefcur;
end;
Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.
If you don't mind using a bit of html, something like this should work.
from IPython.display import HTML, display
def display_table(data):
html = "<table>"
for row in data:
html += "<tr>"
for field in row:
html += "<td><h4>%s</h4><td>"%(field)
html += "</tr>"
html += "</table>"
display(HTML(html))
And then use it like this
data = [[1,2,3],[4,5,6],[7,8,9]]
display_table(data)
That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).
The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:
[data getBytes:&byteData length:len];
Which fills the array you have allocated with data from the NSData object.
Here's my solution:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
Output: 00000101
try this
String g1="Male";
String g2="Female";
if(gender.equals(g1))
salutation ="Mr.";
if(gender.equals(g2))
salutation ="Ms.";
you were ending your if statement if(gender.equals(g1));
<<--- here by adding ";"
Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) +
(select sum(hours) from projects-time)
) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
) t
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
Angular 7,8 fix is in app.module.ts
import {APP_BASE_HREF} from '@angular/common';
inside @NgModule add
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.
In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.
As of the latest version of Python - 3.6.2 - there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.
An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.
Here is an example using the dict
built-in:
>>> dict = {}
>>> dict
{}
>>>
As you can see, Python allowed us to assign the dict
name, to reference a dictionary object.
To put it simply, the reason the error is occurring is because you re-assigned the builtin name list
in the script:
list = [1, 2, 3, 4, 5]
When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list
, which is a class object representing Python list.
Thus, when you tried to use the list
class to create a new list from a range
object:
myrange = list(range(1, 10))
Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list
was referring to a list object. So the above would be the equivalent of doing:
[1, 2, 3, 4, 5](range(1, 10))
Which of course makes no sense. You cannot call a list object.
Suppose you have code such as the following:
list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))
for number in list:
if number in myrange:
print(number, 'is between 1 and 10')
Running the above code produces the following error:
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'list' object is not callable
If you are getting a similar error such as the one above saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case and other cases the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list
variable to ints
:
ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))
for number in ints: # Renamed "list" to "ints"
if number in myrange:
print(number, 'is between 1 and 10')
PEP8 - the official Python style guide - includes many recommendations on naming variables.
This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str
, dict
, list
, range
, etc.
Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.
Another common cause for the above error is attempting to index a list using parenthesis (()
) rather than square brackets ([]
). For example:
>>> lst = [1, 2]
>>> lst(0)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
lst(0)
TypeError: 'list' object is not callable
For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.
If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.
<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>
Make sure both your System and User paths are set correctly.
Yes, you need to negate File.Exists(path)
if you want to check if the file doesn't exist.
Try Following custome class for prevant copy and paste in Edittext
public class SegoeUiEditText extends AppCompatEditText {
private final Context context;
@Override
public boolean isSuggestionsEnabled() {
return false;
}
public SegoeUiEditText(Context context) {
super(context);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
private void setFonts(Context context) {
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "Fonts/Helvetica-Normal.ttf"));
}
private void init() {
setTextIsSelectable(false);
this.setCustomSelectionActionModeCallback(new ActionModeCallbackInterceptor());
this.setLongClickable(false);
}
@Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
/**
* Prevents the action bar (top horizontal bar with cut, copy, paste, etc.) from appearing
* by intercepting the callback that would cause it to be created, and returning false.
*/
private class ActionModeCallbackInterceptor implements ActionMode.Callback, android.view.ActionMode.Callback {
private final String TAG = SegoeUiEditText.class.getSimpleName();
public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; }
public void onDestroyActionMode(ActionMode mode) {}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
menu.clear();
return false;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
}
}
}
document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;
where TestToggleRadioButtonList
is the id of the RadioButtonList
.
I figured it out.
<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?>
From one moment to the other I also got this error without a clear reason. I changed all kinds of settings on the compiler/module etc. But in the end I just recreated the IntelliJ project by reimporting the Maven project and the issue was solved. I think this is a bug.
IntelliJ 12 129.961
Local storage can store up to 5mb offline data, whereas session can also store up to 5 mb data. But cookies can store only 4kb data in text format.
LOCAl and Session storage data in JSON format, thus easy to parse. But cookies data is in string format.
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
on emulator this work for me
Intent i = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("sms_body", remindingReason);
startActivity(i);
Explicit access to module level variables by accessing them explicity on the module
In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).
Think of it like self for the current module instead of the current instance !
# db.py
import sys
# this is a pointer to the module object instance itself.
this = sys.modules[__name__]
# we can explicitly make assignments on it
this.db_name = None
def initialize_db(name):
if (this.db_name is None):
# also in local function scope. no scope specifier like global is needed
this.db_name = name
# also the name remains free for local use
db_name = "Locally scoped db_name variable. Doesn't do anything here."
else:
msg = "Database is already initialized to {0}."
raise RuntimeError(msg.format(this.db_name))
As modules are cached and therefore import only once, you can import db.py
as often on as many clients as you want, manipulating the same, universal state:
# client_a.py
import db
db.initialize_db('mongo')
# client_b.py
import db
if (db.db_name == 'mongo'):
db.db_name = None # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value
# that "db.db_name" has at import time of "client_c".
if (db_name == 'mongo'): # checking is fine if "db.db_name" doesn't change
db_name = None # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.
As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.
This code just fixes @CrimsonX answer's bug:
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
You just need to continue calling the method recursively if types are matching but names don't (this happens when you pass FrameworkElement
as T
). otherwise it's gonna return null
and that's wrong.
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.
Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.
var validations ={
email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
// Check all the input fields of type email. This function will handle all the email addresses validations
$("input[type=email]").change( function(){
// Set the regular expression to validate the email
validation = new RegExp(validations['email'][0]);
// validate the email value against the regular expression
if (!validation.test(this.value)){
// If the validation fails then we show the custom error message
this.setCustomValidity(validations['email'][1]);
return false;
} else {
// This is really important. If the validation is successful you need to reset the custom error message
this.setCustomValidity('');
}
});
})
Consider what happens if you go back and forth between B and C...voila
(relevant only if the graph is not directed)
Edited: I believe the problem has to do with the fact that the path with AC* can only be better than AB with the existence of negative weight edges, so it doesn't matter where you go after AC, with the assumption of non-negative weight edges it is impossible to find a path better than AB once you chose to reach B after going AC.
Let the number be n
then the number of digits in n
is given by:
math.floor(math.log10(n))+1
Note that this will give correct answers for +ve integers < 10e15. Beyond that the precision limits of the return type of math.log10
kicks in and the answer may be off by 1. I would simply use len(str(n))
beyond that; this requires O(log(n))
time which is same as iterating over powers of 10.
Thanks to @SetiVolkylany for bringing my attenstion to this limitation. Its amazing how seemingly correct solutions have caveats in implementation details.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):
getApplicationInfo().dataDir
http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()
TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);
I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Bootstrap 4.3 - use code from below snippet - more here
$('#exampleModal').on('show.bs.modal', function (event) {_x000D_
let bookId = $(event.relatedTarget).data('bookid') _x000D_
$(this).find('.modal-body input').val(bookId)_x000D_
})
_x000D_
a.btn.btn-primary.open-AddBookDialog {color: white }
_x000D_
<!-- Initialize Bootstrap 4 -->_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<!-- BUTTON -->_x000D_
_x000D_
<a _x000D_
class="btn btn-primary open-AddBookDialog" _x000D_
data-toggle="modal" _x000D_
data-target="#exampleModal" _x000D_
data-bookid="@book.Id" _x000D_
title="Add this item"_x000D_
>Open</a>_x000D_
_x000D_
<!-- MODAL -->_x000D_
_x000D_
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
_x000D_
<div class="modal-body">_x000D_
<input type="hidden" name="bookId" id="bookId" value=""/>_x000D_
<input type="text" class="form-control" id="recipient-name"> _x000D_
</div>_x000D_
_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
\n
must be in double quotes!
echo "hello\nworld";
Output
hello
world
A nice way around this is to use PHP as a more of a templating language
<p>
Hello <span><?php echo $world ?></span>
</p>
Output
<p>
Hello <span>Planet Earth</span>
</p>
Notice, all newlines are kept in tact!
Simply do it....
<form>
<!-- Your Input Elements -->
</form>
and here goes your JQuery
$(document).on('submit', 'form', function(e){
e.preventDefault();
//your code goes here
//100% works
return;
});
You can completely avoid manually doing the transforms and scaling yourself, as suggested by an0 in this answer here:
- (UIImage *)normalizedImage {
if (self.imageOrientation == UIImageOrientationUp) return self;
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
[self drawInRect:(CGRect){0, 0, self.size}];
UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return normalizedImage;
}
The documentation for the UIImage methods size and drawInRect explicitly states that they take into account orientation.
If sounds like the type ACTInterface
is not public
, but is using the default accessibility of either internal
(if it is top-level) or private
(if it is nested in another type).
Giving the type the public
modifier would fix it.
Another approach is to make both the type and the method internal
, if that is your intent.
The issue is not the accessibility of the field (oActInterface
), but rather of the type ACTInterface
itself.
Adding up to other answers you need to export the class to use in a different class. This is a typescript version of it.
//Constants.tsx
const DEBUG: boolean = true;
export class Constants {
static get DEBUG(): boolean {
return DEBUG;
}
}
//Anotherclass.tsx
import { Constants } from "Constants";
if (Constants.DEBUG) {
console.log("debug mode")
}
_x000D_
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
You can use built-in function open: I use it in all of my programs in which I need to store some history (Including Calculator, etc.) for example:
#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
username = open("history.txt").readline().strip("\n")
user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
username = input("Enter Username: ")
user_age = input("Enter User's Age: ")
open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!
I would thank to all of them who liked my comments! Thank you for reading this!
Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
Try, Its working for me.
[[self.textField valueForKey:@"textInputTraits"] setValue:[UIColor redColor] strong textforKey:@"insertionPointColor"];
Try this code
Convert ArrayList to Collection
ArrayList<User> usersArrayList = new ArrayList<User>();
Collection<User> userCollection = new HashSet<User>(usersArrayList);
Convert Collection to ArrayList
Collection<User> userCollection = new HashSet<User>(usersArrayList);
List<User> userList = new ArrayList<User>(userCollection );
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
If you only want to display then you can use date pipe in HTML like this :
Just Date:
your date | date: 'dd MMM yyyy'
Date With Time:
your date | date: 'dd MMM yyyy hh:mm a'
And if you want to take input only date from new Date() then :
You can use angular formatDate() in ts file like this -
currentDate = new Date();
const cValue = formatDate(currentDate, 'yyyy-MM-dd', 'en-US');
This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:
If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True
Advantages of this approach:
1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.
There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.
Here the link it is on github
https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py
It might be easier to read when written out in longhand using the 'simple case' e.g.
CASE DeviceID
WHEN '7 ' THEN '01'
WHEN '10 ' THEN '01'
WHEN '62 ' THEN '01'
WHEN '58 ' THEN '01'
WHEN '60 ' THEN '01'
WHEN '46 ' THEN '01'
WHEN '48 ' THEN '01'
WHEN '50 ' THEN '01'
WHEN '137' THEN '01'
WHEN '139' THEN '01'
WHEN '142' THEN '01'
WHEN '143' THEN '01'
WHEN '164' THEN '01'
WHEN '8 ' THEN '02'
WHEN '9 ' THEN '02'
WHEN '63 ' THEN '02'
WHEN '59 ' THEN '02'
WHEN '61 ' THEN '02'
WHEN '47 ' THEN '02'
WHEN '49 ' THEN '02'
WHEN '51 ' THEN '02'
WHEN '138' THEN '02'
WHEN '140' THEN '02'
WHEN '141' THEN '02'
WHEN '144' THEN '02'
WHEN '165' THEN '02'
ELSE 'NA'
END AS clocking
...which kind makes me thing that perhaps you could benefit from a lookup table to which you can JOIN
to eliminate the CASE
expression entirely.
I use lots of erasing level
String donen = "lots of stupid whitespaces and new lines and others..."
//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");
and now we have a clean one row
Since it is hard to find good themes for IntelliJ IDEA, I've created this site: https://github.com/sdvoynikov/color-themes (note: site archived to GitHub repo) where there is a large collection of themes. There are 270 themes for now and the site is growing.
P.S.: Help me and other people — do not forget to upvote when you download themes from this site!
I use strrchr(). For instance to find the extension of a file I use this function:
$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns ".jpg"
if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1
end
else
begin
print 'the record does not exits'
end
If you only need the first row from each group we can do with drop_duplicates
, Notice the function default method keep='first'
.
df.drop_duplicates('id')
Out[1027]:
id value
0 1 first
3 2 first
5 3 first
9 4 second
11 5 first
12 6 first
15 7 fourth
Add this code where you want to click and load Fragment. I hope it's work for you.
Fragment fragment = new yourfragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
While xrange
is faster than range
in most circumstances, the difference in performance is pretty minimal. The little program below compares iterating over a range
and an xrange
:
import timeit
# Try various list sizes.
for list_len in [1, 10, 100, 1000, 10000, 100000, 1000000]:
# Time doing a range and an xrange.
rtime = timeit.timeit('a=0;\nfor n in range(%d): a += n'%list_len, number=1000)
xrtime = timeit.timeit('a=0;\nfor n in xrange(%d): a += n'%list_len, number=1000)
# Print the result
print "Loop list of len %d: range=%.4f, xrange=%.4f"%(list_len, rtime, xrtime)
The results below shows that xrange
is indeed faster, but not enough to sweat over.
Loop list of len 1: range=0.0003, xrange=0.0003
Loop list of len 10: range=0.0013, xrange=0.0011
Loop list of len 100: range=0.0068, xrange=0.0034
Loop list of len 1000: range=0.0609, xrange=0.0438
Loop list of len 10000: range=0.5527, xrange=0.5266
Loop list of len 100000: range=10.1666, xrange=7.8481
Loop list of len 1000000: range=168.3425, xrange=155.8719
So by all means use xrange
, but unless you're on a constrained hardware, don't worry too much about it.
It seems that the good-old ENVIRON
awk built-in hash is not mentioned at all. An example of its usage:
$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt
What I don't understand is what's the point of having a byte? Why not say 8 bits?
Apart from the technical point that a byte isn't necessarily 8 bits, the reasons for having a term is simple human nature:
economy of effort (aka laziness) - it is easier to say "byte" rather than "eight bits"
tribalism - groups of people like to use jargon / a private language to set them apart from others.
Just go with the flow. You are not going to change 50+ years of accumulated IT terminology and cultural baggage by complaining about it.
FWIW - the correct term to use when you mean "8 bits independent of the hardware architecture" is "octet".
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
Instead of using group concat()
you can use just concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.
This will change inputs, select etc to the old style grey not sure if you can manipulate after that:
In <head>
put:
<meta http-equiv="MSThemeCompatible" content="NO">
Additional to nanselm2's answer, you can use 0
instead of False
:
df["col"].str.contains(word)==0
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
This fixed the same issue for me:
My eclipse is installed in /usr/local/bin/eclipse
1) Changed permission for eclipse from root to owner: sudo chown -R $USER eclipse
2) Right click on project/Maven
right click on Update Maven
select Force update maven project
Just want to mention another option here.
You can compute the coefficients using numpy.polyfit(), and feed the coefficients to numpy.poly1d(). This function can construct polynomials using the coefficients, you can find more examples here
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.poly1d.html
Let's say, given two data points (-0.3, -0.5) and (0.8, 0.8)
import numpy as np
import matplotlib.pyplot as plt
# compute coefficients
coefficients = np.polyfit([-0.3, 0.8], [-0.5, 0.8], 1)
# create a polynomial object with the coefficients
polynomial = np.poly1d(coefficients)
# for the line to extend beyond the two points,
# create the linespace using the min and max of the x_lim
# I'm using -1 and 1 here
x_axis = np.linspace(-1, 1)
# compute the y for each x using the polynomial
y_axis = polynomial(x_axis)
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.set_xlim(-1, 1)
axes.set_ylim(-1, 1)
axes.plot(x_axis, y_axis)
axes.plot(-0.3, -0.5, 0.8, 0.8, marker='o', color='red')
Hope it helps.
Indeed ADD go /usr/local/
will add content of go
folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR
to /usr/local/
then add your directory to it like:
WORKDIR /usr/local/
COPY go go/
or
WORKDIR /usr/local/go
COPY go ./
But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . .
and exclude all unwanted directories and files in .dockerignore
, let's say I got folders and files:
- src
- tmp
- dist
- assets
- go
- justforfun
- node_modules
- scripts
- .dockerignore
- Dockerfile
- headache.lock
- package.json
and I want to add src assets package.json justforfun go
so:
in Dockerfile:
FROM galaxy:latest
WORKDIR /usr/local/
COPY . .
in .dockerignore file:
node_modules
headache.lock
tmp
dist
Or for more fun (or you like to confuse more people make them suffer as well :P) can be:
*
!src
!assets
!go
!justforfun
!scripts
!package.json
In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".
It is a late answer but adding more ways to do the same covering even more cases.
Since typeof
is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof
and _Alignof
are also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;
can only be determined at run time.
At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.
Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.
I'm using Ember.js which generates a file named .eslintrc.js
. Adding "no-console": 0
to the rules object did the job for me. The updated file looks like this:
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
extends: 'eslint:recommended',
env: {
browser: true
},
rules: {
"no-console": 0
}
};
There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD
so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:
import java.time.Instant;
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
try {
Instant myDate = Instant.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant
directly, can be done via Calendar
in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:
myDate.toString().substring(0,4);
Funny you mention that, I did a blog post on this very subject.
See Oracle vs MySQL vs SQL Server: Aggregation vs Joins
Short answer: you have to test it and individual databases vary a lot.
For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here it is:
`ALTER TABLE `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0
Carefully observe that I haven't added single quotes/double quotes around the 0.
Important update:
This answer was posted long back. Back then, it worked on my (probably latest) installation of MySQL and I felt like sharing it. Please read the comments below before you decide to use this solution now.
Here's a hackish solution I discovered:
#image {
max-width: 10%;
max-height: 10%;
transform: scale(10);
}
This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.
Unlike the background-image
solution, this will also work with <video>
elements.
Interactive example:
function step(timestamp) {
var container = document.getElementById('container');
timestamp /= 1000;
container.style.left = (200 + 100 * Math.sin(timestamp * 1.0)) + 'px';
container.style.top = (200 + 100 * Math.sin(timestamp * 1.1)) + 'px';
container.style.width = (500 + 500 * Math.sin(timestamp * 1.2)) + 'px';
container.style.height = (500 + 500 * Math.sin(timestamp * 1.3)) + 'px';
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
_x000D_
#container {
outline: 1px solid black;
position: relative;
background-color: red;
}
#image {
display: block;
max-width: 10%;
max-height: 10%;
transform-origin: 0 0;
transform: scale(10);
}
_x000D_
<div id="container">
<img id="image" src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png">
</div>
_x000D_
You should change/add in your PostController: (and change PostsController to PostController)
public function create()
{
$categories = Category::all();
return view('create',compact('categories'));
}
public function store(Request $request)
{
$post = new Posts;
$post->title = $request->get('title'); // CHANGE THIS
$post->body = $request->get('body'); // CHANGE THIS
$post->save(); // ADD THIS
$post->categories()->attach($request->get('categories_id')); // CHANGE THIS
return redirect()->route('posts.index'); // PS ON THIS ONE
}
PS: using route() means you have named your route as such
Route::get('example', 'ExampleController@getExample')->name('getExample');
UPDATE
The comments above are also right, change your 'Posts' Model to 'Post'
Make sure that while using : Button "varName" =findViewById("btID"); you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.
Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');
Hope you got this.
According to official Microsoft docs for Ubuntu 18.04 you should run next commands:
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
apt-get update
ACCEPT_EULA=Y apt-get install msodbcsql17
exit
If you are using python3.7, it is very important to run:
sudo apt-get install python3.7-dev
Add A Tap Gesture Recognizer to your view.And define it ibaction
your .m file will be like
- (IBAction)hideKeyboardGesture:(id)sender {
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *window in windows) [window endEditing:true];
[[UIApplication sharedApplication].keyWindow endEditing:true];
}
It's worked for me
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
Default arguments must be specified with the first occurrence of the function name—typically, in the function prototype. If the function prototype is omitted because the function definition also serves as the prototype, then the default arguments should be specified in the function header.
table:
---------------------
| column1 | column2 |
---------------------
| abc | xyz |
---------------------
In Oracle
:
SELECT column1 || column2 AS column3
FROM table_name;
Output:
table:
---------------------
| column3 |
---------------------
| abcxyz |
---------------------
If you want to put ','
or '.'
or any string within two column data then you may use:
SELECT column1 || '.' || column2 AS column3
FROM table_name;
Output:
table:
---------------------
| column3 |
---------------------
| abc.xyz |
---------------------
Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide Worker
s, that are second scripts which gets executed in background and can return a result.
So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.
The code below contains the function async
to call in background.
Function.prototype.async = function(callback) {
let blob = new Blob([ "self.addEventListener('message', function(e) { self.postMessage({ result: (" + this + ").apply(null, e.data) }); }, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
this(e.data.result);
}.bind(callback), false);
return function() {
this.postMessage(Array.from(arguments));
}.bind(worker);
};
This is an example for usage:
(function(x) {
for (let i = 0; i < 999999999; i++) {}
return x * 2;
}).async(function(result) {
alert(result);
})(10);
This executes a function which iterate a for
with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number.
The async
method provides a function
which calls the wanted function in background, and in that which is provided as parameter of async
callbacks the return
in its unique parameter.
So in the callback function I alert
the result.
Very grateful I found this great post. As for my case, the user executing the stored procedure did not have EXECUTE
permissions. The solution was to grant EXECUTE
permissions for the user within the stored procedure by adding below code to the end of the stored procedure.
GRANT EXECUTE ON dbo.StoredProcNameHere TO UsernameRunningreports
GO
This may be the best way for the email validation for your textbox.
string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
if (Regex.IsMatch("txtemail.Text", pattern))
{
MessageBox.Show ("Valid Email address ");
}
else
{
MessageBox.Show("Invalid Email Email");
}
Just include in any function where you want.
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
I think the OP's problem was that he wants to do BOTH of the following:
As several posters have mentioned, to pass a parameter containing spaces, you must surround the actual parameter value with double quotes.
To test whether a parameter is missing, the method I always learned was:
if "%1" == ""
However, if the actual parameter is quoted (as it must be if the value contains spaces), this becomes
if ""actual parameter value"" == ""
which causes the "unexpected" error. If you instead use
if %1 == ""
then the error no longer occurs for quoted values. But in that case, the test no longer works when the value is missing -- it becomes
if == ""
To fix this, use any other characters (except ones with special meaning to DOS) instead of quotes in the test:
if [%1] == []
if .%1. == ..
if abc%1xyz == abcxyz
unless [nil, 0].include?(discount) # ... end
Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");
this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
According to the fs
documentation, fsPromises
currently provides the recursive
option on an experimental basis, which, at least in my own case on Windows, removes the directory and any files therein.
fsPromises.rmdir(path, {
recursive: true
})
Does recursive: true
remove the files on Linux and MacOS?
The information there is I think partially correct:
That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.
As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the +
is defined, though %20
is standard.
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.
<
stands for lesser than (<) symbol
and, the >
sign stands for greater than (>) symbol
.
For more information on HTML Entities, visit this link:
The Default Expiration Period for Session is 20 Minutes.
You can update sessionstate and configure the minutes under timeout
<sessionState
timeout="30">
</sessionState>
TRY
<?php
$rowID=$productid=$name=$price=$description="";
if (isset($_POST['submit'])) {
$rowID = $_POST['rowID'];
$productid = $_POST['productid']; //this is line 32 and so on...
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
}
First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.
A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.
For more info Refer : http://www.informit.com/articles/article.aspx?p=1856389&seqNum=5
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html
There are some tips which might help you.
Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.
The desired result can be achieved by wrapping the two tables within another table:
<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>
and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).
I conclude that there are some layouts that can only be achieved with tables.
I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.
Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing.
Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other.
Strangely enough they continued running in background after I had killed all my terminals.
Had to kill them manually using fuser -k 8080/tcp
form.MySelect.options[form.MySelect.selectedIndex].value
You need to use the overflow option, but with the following parameters:
.nav {
max-height:300px;
overflow-y:auto;
}
Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.
If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.
Presumably you want something that adapts itself to the content rather then the the opposite.
Hope it may helpful
Let's say we have an external table called employee
hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
id string,
fname string,
lname string,
salary double)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
'colelction.delim'=':',
'field.delim'=',',
'line.delim'='\n',
'serialization.format'=',')
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
'COLUMN_STATS_ACCURATE'='false',
'numFiles'='0',
'numRows'='-1',
'rawDataSize'='-1',
'totalSize'='0',
'transient_lastDdlTime'='1487884795')
To create a person
table like employee
CREATE TABLE person LIKE employee;
To create a person
external table like employee
CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';
then use
DESC person;
to see the newly created table schema.
The first error message is telling you more about the problem:
verify error:num=20:unable to get local issuer certificate
The issuing certificate authority of the end entity server certificate is
VeriSign Class 3 Secure Server CA - G3
Look closely in your CA file - you will not find this certificate since it is an intermediary CA - what you found was a similar-named G3 Public Primary CA of VeriSign.
But why does the other connection succeed, but this one doesn't? The problem is a misconfiguration of the servers (see for yourself using the -debug
option). The "good" server sends the entire certificate chain during the handshake, therefore providing you with the necessary intermediate certificates.
But the server that is failing sends you only the end entity certificate, and OpenSSL is not capable of downloading the missing intermediate certificate "on the fly" (which would be possible by interpreting the Authority Information Access extension). Therefore your attempt fails using s_client
but it would succeed nevertheless if you browse to the same URL using e.g. FireFox (which does support the "certificate discovery" feature).
Your options to solve the problem are either fixing this on the server side by making the server send the entire chain, too, or by passing the missing intermediate certificate to OpenSSL as a client-side parameter.
For Java 8 you can use the following command line to get the heap space utilization in kB:
jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'
The command basically sums up:
You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.
you can use cURL library for posting data: http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
Found the solution here
Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:
$(document).ready(function(){
$("#span1").on('DOMSubtreeModified',function(){
// text change handler
});
});
On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.
But, What if you want to destroy the token on the Node server -
The problem with JWT package is that it doesn't provide any method or way to destroy the token.
So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT
This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method
it works in this way :
1) Install jwt-redis from npm
2) To Create -
var redis = require('redis');
var JWTR = require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);
jwtr.sign(payload, secret)
.then((token)=>{
// your code
})
.catch((error)=>{
// error handling
});
3) To verify -
jwtr.verify(token, secret);
4) To Destroy -
jwtr.destroy(token)
Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.
Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Read below for legacy browser support.
The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.
The window.onbeforeunload
is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload
(including a function that returns null
).
You set window.onbeforeunload
to a function reference, but in older browsers you have to set the returnValue
of the event instead of just returning a string:
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
You can't have that confirmOnPageExit
do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
With -Raw
you should get what you expect
ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.
An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...
Just look at what each offers to decide.
In Maven the META-INF folder is understood because of the Standard Directory Layout, which by name convention package your project resources within JARs: any directories or files placed within the ${basedir}/src/main/resources directory are packaged into your JAR with the exact same structure starting at the base of the JAR. The Folder ${basedir}/src/main/resources/META-INF usually contains .properties files while in the jar contains a generated MANIFEST.MF, pom.properties, the pom.xml, among other files. Also frameworks like Spring use classpath:/META-INF/resources/
to serve web resources. For more information see How do I add resources to my Maven Project.
Here is another option that outputs mm/dd/yy:
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
In Case of not considering '0' or 'NULL' in average function. Simply use
AVG(NULLIF(your_column_name,0))
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.