You can use the pathlib module.
from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))
int keyIndex = Array.FindIndex(words, w => w.IsKey);
That actually gets you the integer index and not the object, regardless of what custom class you have created
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Application Class:
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static Context mContext;
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getAppContext() {
return mContext;
}
}
Declare the Application in the AndroidManifest:
<application android:name=".MyApplication"
...
/>
Usage:
MyApplication.getAppContext()
As per the spec:
The
:focus
pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
The <div>
does not accept input, so it cannot have :focus
. Furthermore, CSS does not allow you to set styles on an element based on targeting its descendants. So you can't really do this unless you are willing to use JavaScript.
Try something like this to get the format you wanted:
Get-WebBinding | % {
$name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
New-Object psobject -Property @{
Name = $name
Binding = $_.bindinginformation.Split(":")[-1]
}
} | Group-Object -Property Name |
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap
In SQL Server direct division of two integer returns integer even if the result should be the float. There is an example below to get it across:
--1--
declare @weird_number_float float
set @weird_number_float=22/7
select @weird_number_float
--2--
declare @weird_number_decimal decimal(18,10)
set @weird_number_decimal=22/7
select @weird_number_decimal
--3--
declare @weird_number_numeric numeric
set @weird_number_numeric=22/7
select @weird_number_numeric
--Right way
declare @weird_number float
set @weird_number=cast(22 as float)/cast(7 as float)
select @weird_number
Just last block will return the 3,14285714285714. In spite of the second block defined with right precision the result will be 3.00000.
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.
Try this:
String[] columnDetail = column.split("\t", -1);
Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:
split
public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
When the last few fields (I guest that's your situation) are missing, you will get the column like this:
field1\tfield2\tfield3\t\t
If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.
When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.
For fire base to install properly all the versions of the fire base compiles must be in same version so
compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
this is the correct way to do it.
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
Similar problem on Ubuntu 16.04.
Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)
Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....
To fix the issue manually install Java Runtime Environment:
JDK version 9:
sudo apt install openjdk-9-jre
JDK version 8:
sudo apt install openjdk-8-jre
Open Jenkins configuration file:
sudo vi /etc/init.d/jenkins
Finally, append path to the new java executable (line 16):
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/
I am using Jupyter Notebooks. I had to write
%%latex
$sin(x)/x$
to get a LaTex font.
Upper Solution may not work for you if you have installed latest version of Python in Windows. I have installed Python 3.6.0 :: Anaconda 4.3.0 (64-bit) and I wanted to change the working directory of iPython Notebook called Jupyter and this is how it worked for me.
Step-1 : Open your CMD and type following command.
Step-2 : It has now generated a file in your .jupyter folder. For me, it's C:\Users\Admin.jupyter . There you will find a file called jupyter_notebook_config.py .Right click and edit it. Add the following line and set path of your working directory. Set your own working directory in place of "I:\STUDY\Y2-Trimester-1\Modern Data Science"
We are done. Now you can try restarting your Jupyter Notebook. Hope this is useful to you. Thanks
This seems to have changed (probably with log4j2) to:
-Dlog4j.configurationFile=file:C:\Users\me\log4j.xml
See: https://logging.apache.org/log4j/2.x/manual/configuration.html
For future visitors, you can also (best IMHO) import WordUtil
from Apache
and add a lot of useful methods to you app, like capitalize
as shown here:
How to capitalize the first character of each word in a string
The **
syntax tells Python to collect keyword arguments into a dictionary. The save2
is passing it down as a non-keyword argument (a dictionary object). The openX
is not seeing any keyword arguments so the **args
doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX
function.
def openX(filename, mode, kwargs):
pass
I think it will have a syntactic benefit, since you'll no longer be "faking" dynamically added properties by using a dictionary.
That, and interop with dynamic languages I would think.
I had the same problem and I Just Invalidate caches/restart
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.
.inline li {
display: inline;
}
On server
Install rsub:
wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub
On local
On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it
ssh -R 52698:localhost:52698 server_user@server_address
rsub path_to_file/file.txt
As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.
Use datetime.datetime.strptime
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5
The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.
You do not have to put an alias and the password of the keystore, you can just type:
keytool -v -import -file somefile.crt -alias somecrt -keystore my-cacerts
Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.
Update regarding the differences of cer and crt (just to clarify) According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider
CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.
Changing Command Execute Timeout in Management Studio:
Click on Tools -> Options
Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.
Changing Command Timeout in Server:
In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.
Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property
Remote query timeout (in seconds, 0 = no timeout):
[up/down control]
you can set the value in up/down control.
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
this works for me because it works fine in ie8.
$('#iframe').contents().find("html").html();
but if you like to use javascript aside for jquery you may use like this
var iframe = document.getElementById('iframecontent');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var val_1 = innerDoc.getElementById('value_1').value;
This is what I use in my application:
static void Main()
{
bool mutexCreated = false;
System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated )
{
if( MessageBox.Show(
"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
"slimKEYS already running",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question ) != DialogResult.Yes )
{
mutex.Close();
return;
}
}
// The usual stuff with Application.Run()
mutex.Close();
}
On Windows Powershell:
Get-PSDrive
[System.IO.DriveInfo]::getdrives()
wmic diskdrive
wmic volume
Also the utility dskwipe: http://smithii.com/dskwipe
dskwipe.exe -l
To count the number of values larger than x in any numpy array you can use:
n = len(matrix[matrix > x])
The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.
i == 'InvKey' && i == 'PostDate'
will never be true, since i
can never equal two different things at once.
You're probably trying to write
if (i !== 'InvKey' && i !== 'PostDate'))
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
You must have got the idea why you are getting this problem after going through above answers.
self.send_header('Access-Control-Allow-Origin', '*')
You just have to add the above line in your server side.
foreach($xml->code as $vals )
{
unset($geonames);
$vals=(array)$vals;
foreach($vals as $key => $value)
{
$value=(array)$value;
$geonames[$key]=$value[0];
}
}
print_r($geonames);
Use the Money pattern from Patterns of Enterprise Application Architecture. specify amount as decimal and the currency as an enum.
If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/
All you have to do is add:
#include <string>
using namespace std;
at the top. (BTW I know this was posted in 2013 but I just wanted to answer)
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
If you want to use only text while making swipe actions then you can use iOS default swipe actions but if you want image and text, then you have to customize it. I have found a great tutorial and sample that can resolve this problem.
Try out this repository to get the custom swipe cell. You can add multiple option here.
http://iosbucket.blogspot.in/2016/04/custom-swipe-table-view-cell_16.html
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
$('#tableId').on('draw.dt', function() {
//This will get called when data table data gets redrawn to the table.
});
Here is some code. It uses 2 classes (Card.java and Deck.java) to accomplish this issue, and to top it off it auto sorts it for you when you create the deck object. :)
import java.util.*;
public class deck2 {
ArrayList<Card> cards = new ArrayList<Card>();
String[] values = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] suit = {"Club", "Spade", "Diamond", "Heart"};
static boolean firstThread = true;
public deck2(){
for (int i = 0; i<suit.length; i++) {
for(int j=0; j<values.length; j++){
this.cards.add(new Card(suit[i],values[j]));
}
}
//shuffle the deck when its created
Collections.shuffle(this.cards);
}
public ArrayList<Card> getDeck(){
return cards;
}
public static void main(String[] args){
deck2 deck = new deck2();
//print out the deck.
System.out.println(deck.getDeck());
}
}
//separate class
public class Card {
private String suit;
private String value;
public Card(String suit, String value){
this.suit = suit;
this.value = value;
}
public Card(){}
public String getSuit(){
return suit;
}
public void setSuit(String suit){
this.suit = suit;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public String toString(){
return "\n"+value + " of "+ suit;
}
}
There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:
Example of charts:
Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/
What is cool about this lib:
Charts are free for non-commercial use, commercial licenses and technical support available as well.
Also interactive Time charts and Net Charts are there for you to use.
Charts come with extensive API and Settings, so you can control every aspect of the charts.
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
This error occurred for me when I was trying to update the same row from 2 different sessions. I updated a field in one browser while a second was open and had already stored the original object in its session. When I attempted to update from this second "stale" session I get the stale object error. In order to correct this I refetch my object to be updated from the database before I set the value to be updated, then save it as normal.
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.
Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).
Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.
CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).
Read this write-up on AES-CBC vulnerabilities.
WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.
SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.
Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.
Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.
You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.
Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.
crypto_box()
/ crypto_box_open()
offer authenticated public-key encryption.
crypto_secretbox()
/ crypto_secretbox_open()
offer shared-key authenticated encryption.
Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.
First, you need to decide one thing:
If you selected the first option, get CipherSweet.js.
The documentation is available online. EncryptedField
is sufficient for most use cases, but the EncryptedRow
and EncryptedMultiRows
APIs may be easier if you have a lot of distinct fields you want to encrypt.
With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.
Additionally, this handles int
/float
encryption without leaking facts about the contents through ciphertext size.
Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.
To install sodium-plus, simply run...
npm install sodium-plus
There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js
from the latest Github release if you need it.
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
if (!sodium) sodium = await SodiumPlus.auto();_x000D_
let plaintext = 'Your message goes here';_x000D_
let key = await sodium.crypto_secretbox_keygen();_x000D_
let nonce = await sodium.randombytes_buf(24);_x000D_
let ciphertext = await sodium.crypto_secretbox(_x000D_
plaintext,_x000D_
nonce,_x000D_
key _x000D_
);_x000D_
console.log(ciphertext.toString('hex'));_x000D_
_x000D_
let decrypted = await sodium.crypto_secretbox_open(_x000D_
ciphertext,_x000D_
nonce,_x000D_
key_x000D_
);_x000D_
_x000D_
console.log(decrypted.toString());_x000D_
})();
_x000D_
The documentation for sodium-plus is available on Github.
If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.
Consider adding
[appdefaults]
validate=false
to your /etc/krb5.conf. This can work around mismatching DNS.
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
Quotes!
if [ "$1" != -v ]; then
Otherwise, when $1
is completely empty, your test becomes:
[ != -v ]
instead of
[ "" != -v ]
...and !=
is not a unary operator (that is, one capable of taking only a single argument).
The technical difference according to two features:
1. Where the "work" is done
2. What is being transferred to/from the server
Web app
1. The "work" is done at the browser (JavaScript)
2. Data is being transferred from/to the server
In comparison: Faster
Website
1. The "work" (most of it) is done at the server
2. Rendered pages (data + UI) are being transferred from the server
In comparison: Easier SEO
Equivalent to "find and replace." Don't overthink it.
Try it with one:
library(tidyverse)
df <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))
df %>%
mutate(var1 = str_replace(var1, " ", ""))
#> name var1 var2
#> 1 a <2 <3
#> 2 a <2 <3
#> 3 a <2 <3
#> 4 b <2 <3
#> 5 b <2 <3
#> 6 b <2 <3
#> 7 c <2 <3
#> 8 c <2 <3
#> 9 c <2 <3
Apply to all
df %>%
mutate_all(funs(str_replace(., " ", "")))
#> name var1 var2
#> 1 a <2 <3
#> 2 a <2 <3
#> 3 a <2 <3
#> 4 b <2 <3
#> 5 b <2 <3
#> 6 b <2 <3
#> 7 c <2 <3
#> 8 c <2 <3
#> 9 c <2 <3
If the extra space was produced by uniting columns, think about making str_trim
part of your workflow.
Created on 2018-03-11 by the reprex package (v0.2.0).
In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.
In your second example, I agree with other commenters. Using the success flag is unnecessary.
I consider the following approach to be, essentially, a light weight best practice approach.
If you want to see how it handles an exception, change the value on the second insert from 255 to 256.
CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT INTO #TEMP( ID ) VALUES ( 1 )
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO #TEMP( ID ) VALUES ( 2 )
INSERT INTO #TEMP( ID ) VALUES ( 255 )
COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE
@ErrorMessage NVARCHAR(4000),
@ErrorSeverity INT,
@ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (
@ErrorMessage,
@ErrorSeverity,
@ErrorState
);
ROLLBACK TRANSACTION
END CATCH
SET NOCOUNT ON
SELECT ID
FROM #TEMP
DROP TABLE #TEMP
I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href
attribute of each links. It will match whether double or single quotes are used.
<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1
You can view a full explanation of this regex at here.
Snippet playground:
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
Text to match:_x000D_
<input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
_x000D_
<button>Match</button>_x000D_
</label>
_x000D_
You can use a script that I made. You need JRuby to run this though. https://bitbucket.org/ardee_aram/jscombiner (JSCombiner).
What sets this apart is that it watches file changes in the javascript, and combines it automatically to the script of your choice. So there is no need to manually "build" your javascript each time you test it. Hope it helps you out, I am currently using this.
Below is example you can use:
create temp table test2 (
id1 numeric,
id2 numeric,
id3 numeric,
id4 numeric,
id5 numeric,
id6 numeric,
id7 numeric,
id8 numeric,
id9 numeric,
id10 numeric)
with (oids = false);
do
$do$
declare
i int;
begin
for i in 1..100000
loop
insert into test2 values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;
I took SLaks' idea and wrapped it in a small class.
function HoverWatcher(selector){
this.hovering = false;
var self = this;
this.isHoveringOver = function() {
return self.hovering;
}
$(selector).hover(function() {
self.hovering = true;
}, function() {
self.hovering = false;
})
}
var box1Watcher = new HoverWatcher('#box1');
var box2Watcher = new HoverWatcher('#box2');
$('#container').click(function() {
alert("box1.hover = " + box1Watcher.isHoveringOver() +
", box2.hover = " + box2Watcher.isHoveringOver());
});
Simply create a Class Name and define your style there like this :
table.tdfont td {
font-size: 0.9em;
}
Menu items file looks like
res/menu/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/settings"
android:title="Setting"
app:showAsAction="never" />
<item
android:id="@+id/my_activity"
android:title="My Activity"
app:showAsAction="always"
android:icon="@android:drawable/btn_radio"/>
</menu>
Java code looks like
src/MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.my_activity) {
Intent intent1 = new Intent(this,MyActivity.class);
this.startActivity(intent1);
return true;
}
if (id == R.id.settings) {
Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
And add following code to your AndroidManifest.xml file
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
</activity>
I hope it will help you.
using ssh from java should not be as hard as jsch makes it. you might be better off with sshj.
Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource
property, not its DataContext
.
<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list
collection. The DataGrid is derived from ItemsControl
, which relies on its ItemsSource
property to define the collection it binds its rows to. Hence, if list
isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list}
and ItemsSource={Binding list}
on the DataGrid...)
As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x
git push --atomic origin <branch name> <tag>
(Note: this actually work with HTTPS only with Git 2.24)
As of git 2.4.1, you can do
git config --global push.followTags true
If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.
As noted in this thread by Matt Rogers answering Wes Hurd:
--follow-tags
only pushes annotated tags.
git tag -a -m "I'm an annotation" <tagname>
That would be pushed (as opposed to git tag <tagname>
, a lightweight tag, which would not be pushed, as I mentioned here)
Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:
The new "
--follow-tags
" option tells "git push
" to push relevant annotated tags when pushing branches out.
You can now try, when pushing new commits:
git push --follow-tags
That won't push all the local tags though, only the one referenced by commits which are pushed with the git push
.
Git 2.4.1+ (Q2 2015) will introduce the option push.followTags
: see "How to make “git push
” include tags within a branch?".
The nuclear option would be git push --mirror
, which will push all refs under refs/
.
You can also push just one tag with your current branch commit:
git push origin : v1.0.0
You can combine the --tags
option with a refspec like:
git push origin --tags :
(since --tags
means: All refs under refs/tags
are pushed, in addition to refspecs explicitly listed on the command line)
You also have this entry "Pushing branches and tags with a single "git push" invocation"
A handy tip was just posted to the Git mailing list by Zoltán Füzesi:
I use
.git/config
to solve this:
[remote "origin"]
url = ...
fetch = +refs/heads/*:refs/remotes/origin/*
push = +refs/heads/*
push = +refs/tags/*
With these lines added
git push origin
will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.
Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:
$ git push && git push --tags
Beware, as commented by Aseem Kishore
push = +refs/heads/*
will force-pushes all your branches.
This bit me just now, so FYI.
René Scheibe adds this interesting comment:
The
--follow-tags
parameter is misleading as only tags under.git/refs/tags
are considered.
Ifgit gc
is run, tags are moved from.git/refs/tags
to.git/packed-refs
. Afterwardsgit push --follow-tags ...
does not work as expected anymore.
That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.
A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the #
will cause the first line to be treated as a comment.
If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.
In pyspark 2.4.4
1) group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)
2) from pyspark.sql.functions import desc
group_by_dataframe.count().filter("`count` >= 10").orderBy('count').sort(desc('count'))
No need to import in 1) and 1) is short & easy to read,
So I prefer 1) over 2)
Try this on Debian/Ubuntu:
sudo apt-get install python-mechanize
You could easily use:
label1.Text = dateTimePicker1.Value.Date.ToString("dd/MM/yyyy")
and if you want to change '/' or '-', just add this:
label1.Text = label1.Text.Replace(".", "-")
More info about DateTimePicker.CustomFormat Property: Link
And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.
In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.
The way you are adding headers is the right way to do it.
For this you must first say for the browser that the user receive an error 403. For this you can use this code:
header("HTTP/1.1 403 Forbidden" );
Then, the script send "error, error, error, error, error.......", so you must stop it. You can use
exit;
With this two lines the server send an error and stop the script.
Don't forget : that emulate the error, but you must set it in a .htaccess file, with
ErrorDocument 403 /error403.php
For auto resizing, try imagemagick... it is used for many major open source content/photo management systems... and I believe that there are some .net extensions for it.
For Laravel Homestead Users: If anyone using Laravel with homestead you can access app backend using 192.168.10.10 in emulator
Still not working? Another good solution is to use ngrok https://ngrok.com/
You probably need to wrap the UNION
in a sub-SELECT
and apply the WHERE
clause afterward:
SELECT * FROM (
SELECT * FROM Table1 WHERE Field1 = Value1
UNION
SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3
Basically, the UNION
is looking for two complete SELECT
statements to combine, and the WHERE
clause is part of the SELECT
statement.
It may make more sense to apply the outer WHERE
clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.
foreach (DataGridViewRow row in datagrid.Rows)
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
Try This
var sessionValue = '<%=Session["usedData"]%>'
You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.
Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.
To find out more about the JS classes that let you define your unit tests, see the online API viewer.
For automated UI testing (based on Selenium RC), check out the Simulator project.
You can also switch environments in Anaconda Navigator, install Jupiter and run it.
For Powershell scripts
I have seen this problem multiple times while scheduling Powershell scripts with parameters on multiple Windows servers. The solution has always been to use the -File parameter:
Happy scheduling!
I think everyone has done a great job responding to your question. I'm just adding more information about thread versus process in Linux to clarify and summarize some of the previous responses in context of kernel. So, my response is in regarding to kernel specific code in Linux. According to Linux Kernel documentation, there is no clear distinction between thread versus process except thread uses shared virtual address space unlike process. Also note, the Linux Kernel uses the term "task" to refer to process and thread in general.
"There are no internal structures implementing processes or threads, instead there is a struct task_struct that describe an abstract scheduling unit called task"
Also according to Linus Torvalds, you should NOT think about process versus thread at all and because it's too limiting and the only difference is COE or Context of Execution in terms of "separate the address space from the parent " or shared address space. In fact he uses a web server example to make his point here (which highly recommend reading).
Full credit to linux kernel documentation
Try jamspell - it works pretty well for automatic spelling correction:
import jamspell
corrector = jamspell.TSpellCorrector()
corrector.LoadLangModel('en.bin')
corrector.FixFragment('Some sentnec with error')
# u'Some sentence with error'
corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
# ('sentence', 'senate', 'scented', 'sentinel')
new
and delete
Note: This only deals with the syntax of overloading new
and delete
, not with the implementation of such overloaded operators. I think that the semantics of overloading new
and delete
deserve their own FAQ, within the topic of operator overloading I can never do it justice.
In C++, when you write a new expression like new T(arg)
two things happen when this expression is evaluated: First operator new
is invoked to obtain raw memory, and then the appropriate constructor of T
is invoked to turn this raw memory into a valid object. Likewise, when you delete an object, first its destructor is called, and then the memory is returned to operator delete
.
C++ allows you to tune both of these operations: memory management and the construction/destruction of the object at the allocated memory. The latter is done by writing constructors and destructors for a class. Fine-tuning memory management is done by writing your own operator new
and operator delete
.
The first of the basic rules of operator overloading – don’t do it – applies especially to overloading new
and delete
. Almost the only reasons to overload these operators are performance problems and memory constraints, and in many cases, other actions, like changes to the algorithms used, will provide a much higher cost/gain ratio than attempting to tweak memory management.
The C++ standard library comes with a set of predefined new
and delete
operators. The most important ones are these:
void* operator new(std::size_t) throw(std::bad_alloc);
void operator delete(void*) throw();
void* operator new[](std::size_t) throw(std::bad_alloc);
void operator delete[](void*) throw();
The first two allocate/deallocate memory for an object, the latter two for an array of objects. If you provide your own versions of these, they will not overload, but replace the ones from the standard library.
If you overload operator new
, you should always also overload the matching operator delete
, even if you never intend to call it. The reason is that, if a constructor throws during the evaluation of a new expression, the run-time system will return the memory to the operator delete
matching the operator new
that was called to allocate the memory to create the object in. If you do not provide a matching operator delete
, the default one is called, which is almost always wrong.
If you overload new
and delete
, you should consider overloading the array variants, too.
new
C++ allows new and delete operators to take additional arguments.
So-called placement new allows you to create an object at a certain address which is passed to:
class X { /* ... */ };
char buffer[ sizeof(X) ];
void f()
{
X* p = new(buffer) X(/*...*/);
// ...
p->~X(); // call destructor
}
The standard library comes with the appropriate overloads of the new and delete operators for this:
void* operator new(std::size_t,void* p) throw(std::bad_alloc);
void operator delete(void* p,void*) throw();
void* operator new[](std::size_t,void* p) throw(std::bad_alloc);
void operator delete[](void* p,void*) throw();
Note that, in the example code for placement new given above, operator delete
is never called, unless the constructor of X throws an exception.
You can also overload new
and delete
with other arguments. As with the additional argument for placement new, these arguments are also listed within parentheses after the keyword new
. Merely for historical reasons, such variants are often also called placement new, even if their arguments are not for placing an object at a specific address.
Most commonly you will want to fine-tune memory management because measurement has shown that instances of a specific class, or of a group of related classes, are created and destroyed often and that the default memory management of the run-time system, tuned for general performance, deals inefficiently in this specific case. To improve this, you can overload new and delete for a specific class:
class my_class {
public:
// ...
void* operator new();
void operator delete(void*,std::size_t);
void* operator new[](size_t);
void operator delete[](void*,std::size_t);
// ...
};
Overloaded thus, new and delete behave like static member functions. For objects of my_class
, the std::size_t
argument will always be sizeof(my_class)
. However, these operators are also called for dynamically allocated objects of derived classes, in which case it might be greater than that.
To overload the global new and delete, simply replace the pre-defined operators of the standard library with our own. However, this rarely ever needs to be done.
With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:
import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);
Make sure to add these settings in the compilerOptions
section of your tsconfig.json
(documentation):
"resolveJsonModule": true,
"esModuleInterop": true,
Side notes:
import * as colorsJson from '../colors.json'
The power of jQuery. $(selector).modal('hide').destroy();
will first remove sinds you might have the sliding affect and then removes the element completely, however if you want the user to be able to open the modal again after you finished the steps. you might just wanna update only the settings you wanna have reseted so for reseting all the inputs in your modal this would look like the following:
$(selector).find('input, textarea').each(function(){
$(this).val('');
});
You can't achieve text size change with a state list drawable. To change text color and text size do this:
Text color
To change the text color, you can create color state list resource. It will be a separate resource located in res/color/
directory. In layout xml you have to set it as the value for android:textColor
attribute. The color selector will then contain something like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/text_pressed" />
<item android:color="@color/text_normal" />
</selector>
Text size
You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.
Probably the easiest solution might be utilizing View.onTouchListener()
and handle the up and down events accordingly. Use something like this:
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// change text size to the "pressed value"
return true;
case MotionEvent.ACTION_UP:
// change text size to the "normal value"
return true;
default:
return false;
}
}
});
A different solution might be to extend the view and override the setPressed(Boolean)
method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).
Capture the KeyboardInterrupt
(which is launched by pressing ctrl
+c
) and force the exit:
from sys import exit
try:
# Your code
command = input('Type your command: ')
except KeyboardInterrupt:
# User interrupt the program with ctrl+c
exit()
Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.
If you do indeed wish to access the state of a component's children, you can assign a property called ref
to each child. There are now two ways to implement references: Using React.createRef()
and callback refs.
React.createRef()
This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.
You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref
attribute.
class FormEditor extends React.Component {
constructor(props) {
super(props);
this.FieldEditor1 = React.createRef();
}
render() {
return <FieldEditor ref={this.FieldEditor1} />;
}
}
In order to access this kind of ref, you'll need to use:
const currentFieldEditor1 = this.FieldEditor1.current;
This will return an instance of the mounted component so you can then use currentFieldEditor1.state
to access the state.
Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />
) then this.divRef.current
will return the underlying DOM element instead of a component instance.
This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.
For example:
<FieldEditor
ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
{...props}
/>
In these examples the reference is stored on the parent component. To call this component in your code, you can use:
this.fieldEditor1
and then use this.fieldEditor1.state
to get the state.
One thing to note, make sure your child component has rendered before you try to access it ^_^
As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />
) then this.divRef
will return the underlying DOM element instead of a component instance.
If you want to read more about React's ref property, check out this page from Facebook.
Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state
to "make things happen".
Hope this helps ^_^
Edit: Added React.createRef()
method for creating refs. Removed ES5 code.
You may need to handle javax.persistence.RollbackException
use the pow
function (it takes float
s/double
s though).
man pow
:
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
EDIT: For the special case of positive integer powers of 2
, you can use bit shifting: (1 << x)
will equal 2
to the power x
. There are some potential gotchas with this, but generally, it would be correct.
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
... and so you should do something like this:
set(tuple ((a,b) for a in range(3)) for b in range(3))
... and if needed convert back to list
In Portrait only I use the view's frame's width and height to check:
override func viewDidLoad() {
super.viewDidLoad()
// iPhone Xr: -414 x 896
// iPhone Xs Max: -414 x 896
// iPhone X, Xs: -375 x 812
if view.frame.width == 414 && view.frame.height == 896 || view.frame.width == 375 && view.frame.height == 812 {
print("iPhone X")
} else {
print("not iPhone X")
}
}
The portrait screen dimensions are listed here
UPDATE
This is answer is old and now that there are more X series in the iPhone lineup you would either have to list all of those dimensions inside the the if-else
or it would be much easier to just check to see if the device has a notch. I got this answer/code from somewhere on SO about 1.5 yrs ago. If I could link to the code I would.
// 1. add an extension to UIDevice with this computed property
extension UIDevice {
var hasTopNotch: Bool {
if #available(iOS 11.0, tvOS 11.0, *) {
return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
}
return false
}
}
// 2. to use in any class
override func viewDidLoad() {
super.viewDidLoad()
if UIDevice.current.hasTopNotch {
print("X series")
} else {
print("regular phone")
}
}
Another solution which is permanent in nature between sessions without requiring you to run a specific command when opening chrome is as follows:
json = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\" +download_file[0]);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
globalThis is the future.
First, TypeScript files have two kinds of scopes
If your file hasn't any import
or export
line, this file would be executed in global scope that all declaration in it are visible outside this file.
So we would create global variables like this:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
All magic come from
var
. Replacevar
withlet
orconst
won't work.
If your file has any import
or export
line, this file would be executed within its own scope that we need to extend global by declaration-merging.
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
You can see more about module in official docs
This will do the trick:
public void itemClicked(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MyAndroidAppActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}
}
You can also limit the filter to only part of the ip address.
E.G. To filter 123.*.*.*
you can use ip.addr == 123.0.0.0/8
. Similar effects can be achieved with /16
and /24
.
See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.
... the number after the slash represents the number of bits used to represent the network.
For osX Mavericks Users you can install the ipa-file with the Apple Configurator. (Instead of the iPhone configuration utility, which crashes on OSX 10.9)
Try this I think this is better.
var images = [];
function preload() {
for (var i = 0; i < arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
//-- usage --//
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
It seems as the Chrome debugger loads source files into memory and wont let them go despite of browser cache updates, i.e. it has its own cache apart from the browser cache that is not in sync. At least, this is the case when working with source mapped files (I am debugging typescript sources). After successfully refreshing browser cache and validating that by browsing directly to the source file, you download the updated file, but as soon as you reopen the file in the debugger it will keep returning the old file no matter the version from the ordinary browser cache. Very anoying indeed.
I would consider this a bug in chrome. I use version Version 46.0.2490.71 m.
The only thing that helps, is restarting chrome (close down all chrome browsers).
I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?
html:
<div id="content">
<div id='bg'></div>
<h2>What is Lorem Ipsum?</h2>
<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
css:
#content {
text-align: left;
width: 75%;
margin: auto;
position: relative;
}
#bg {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
opacity: .4;
width: 100%;
height: 100%;
}
Way too complicated guys. Just include it in your gradle dependencies:
dependencies {
...
compile 'com.mcxiaoke.volley:library:1.0.17'
}
If you're not doing the else, why not do:
if (x==2) doSomething();
try this
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.htc</url-pattern>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
Edit: This is only valid for the servlet 2.5 spec and up.
"filter" and "indexOf" aren't supported on Array in IE. How about this:
var array1 = [1, 2, 3];
var array2 = [2, 3, 4, 5];
var intersection = [];
for (i in array1) {
for (j in array2) {
if (array1[i] == array2[j]) intersection.push(array1[i]);
}
}
https://www.timcosta.io/angular-js-object-comparisons/
Angular is pretty magical the first time people see it. Automatic DOM updates when you update a variable in your JS, and the same variable will update in your JS file when someone updates its value in the DOM. This same functionality works across page elements, and across controllers.
The key to all of this is the $$hashKey Angular attaches to objects and arrays used in ng-repeats.
This $$hashKey causes a lot of confusion for people who are sending full objects to an API that doesn't strip extra data. The API will return a 400 for all of your requests, but that $$hashKey just wont go away from your objects.
Angular uses the $$hashKey to keep track of which elements in the DOM belong to which item in an array that is being looped through in an ng-repeat. Without the $$hashKey Angular would have no way to apply changes the occur in the JavaScript or DOM to their counterpart, which is one of the main uses for Angular.
Consider this array:
users = [
{
first_name: "Tim"
last_name: "Costa"
email: "[email protected]"
}
]
If we rendered that into a list using ng-repeat="user in users", each object in it would receive a $$hashKey for tracking purposes from Angular. Here are two ways to avoid this $$hashKey.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
Add the following to your xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>annotations</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
The CGRectZero
constant is equal to a rectangle at position (0,0)
with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview
otherwise your view is not added to the view hierarchy.
Can you explain why you want to do this?
You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA
, but to a particular instance of ClassA
that you created when you wrote ClassA()
). If you want to have changes in one class show up in another, you can use class variables:
class ClassA(object):
var1 = 1
var2 = 2
@classmethod
def method(cls):
cls.var1 = cls.var1 + cls.var2
return cls.var1
In this scenario, ClassB
will pick up the values on ClassA
from inheritance. You can then access the class variables via ClassA.var1
, ClassB.var1
or even from an instance ClassA().var1
(provided that you haven't added an instance method var1
which will be resolved before the class variable in attribute lookup.
I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...
One more way - just add a selected = "selected"
attribute to the select
markup and call select2
on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
<option id="foo">Some Text</option>
<option id="bar" selected="selected">Other Text</option>
</select>
JavaScript
$('select').select2(); //oh yes just this!
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val
property of select2
to null
, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)
After this, it is simple enough to set val
to "Whatever You Want"
.
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="doSomething($event)">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
doSomething(e) {
alert(e);
}
}
This works for me!
All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.
php artisan make:controller SessionController --plain
Then
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class SessionController extends Controller {
public function accessSessionData(Request $request) {
if($request->session()->has('my_name'))
echo $request->session()->get('my_name');
else
echo 'No data in the session';
}
public function storeSessionData(Request $request) {
$request->session()->put('my_name','Ajay kumar');
echo "Data has been added to session";
}
public function deleteSessionData(Request $request) {
$request->session()->forget('my_name');
echo "Data has been removed from session.";
}
}
?>
And all route:
Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');
More Help: How To Set Session In Laravel?
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
The other answers were good answers when the question was asked. Time moves on, Date
and SimpleDateFormat
get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time
package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00
.
For only date use
date("Y-m-d");
and for only time use
date("H:i:s");
Dimension table : It is nothing but we can maintains information about the characterized date called as Dimension table.
Example : Time Dimension , Product Dimension.
Fact Table : It is nothing but we can maintains information about the metrics or precalculation data.
Example : Sales Fact, Order Fact.
Star schema : one fact table link with dimension table form as a Start Schema.
No -- neither. Per the Go for C++ programmers docs,
Go does not support function overloading and does not support user defined operators.
I can't find an equally clear statement that optional parameters are unsupported, but they are not supported either.
You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.
The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.
const p = document.querySelector('p')_x000D_
const result = document.querySelector('div')_x000D_
const observer = new MutationObserver((mutationRecords) => {_x000D_
result.textContent = mutationRecords[0].target.data_x000D_
// result.textContent = p.textContent_x000D_
})_x000D_
observer.observe(p, {_x000D_
characterData: true,_x000D_
subtree: true,_x000D_
})
_x000D_
<p contenteditable>abc</p>_x000D_
<div />
_x000D_
For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
Use the .c_str()
method for const char *
.
You can use &mystring[0]
to get a char *
pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).
There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string
worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.
Note that many string
member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class HeightAnimation extends Animation {
protected final int originalHeight;
protected final View view;
protected float perValue;
public HeightAnimation(View view, int fromHeight, int toHeight) {
this.view = view;
this.originalHeight = fromHeight;
this.perValue = (toHeight - fromHeight);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
view.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
}
uss to:
HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);
Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):
Function: Output:
scanf(...) EOF
gets(<variable>) NULL
feof(stdin) 1
getchar() EOF
If you're using the DefinitelyTyped repository in your project you might be experiencing this recent issue.
A decent workaround you might use (other than waiting for an updated build of the definitions file or refactoring your TS code) is to specify an explicit version+build for the core-js typings rather than let Visual Studio pick the latest/most recent one. I found one that seems to be unaffected by this problem (in my case at least), you can use it replacing the following line from your package.json file:
"scripts": {
"postinstall": "typings install dt~core-js --global"
}
With the following one:
"scripts": {
"postinstall": "typings install [email protected]+20161130133742 --global"
}
This fixed my issue for good. However, is highly recommended to remove the explicit version+build reference as soon as the issue will be released.
For further info regarding this issue, you can also read this blog post that I wrote on the topic.
select *
from dbo.March2010 A
where A.Date >= Convert(datetime, '2010-04-01' )
In your query, 2010-4-01
is treated as a mathematical expression, so in essence it read
select *
from dbo.March2010 A
where A.Date >= 2005;
(2010 minus 4 minus 1 is 2005
Converting it to a proper datetime
, and using single quotes will fix this issue.)
Technically, the parser might allow you to get away with
select *
from dbo.March2010 A
where A.Date >= '2010-04-01'
it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime
for the maintenance programmer that will come after you.
When this error occurred to me was because Pods folder was in iCloud and had no local copy on my computer. Go to your project's folder in Finder and check if there is iCloud's symbol in any of the folders inside it!
To check if a string is empty or contains only whitespace you could use:
shopt -s extglob # more powerful pattern matching
if [ -n "${str##+([[:space:]])}" ]; then
echo '$str is not null or space'
fi
See Shell Parameter Expansion and Pattern Matching in the Bash Manual.
The math.log
function is to the base e
, i.e. natural logarithm. If you want to the base 10 use math.log10
.
The report definition is not valid or supported by this version of Reporting Services. This could be the result of publishing a report definition of a later version of Reporting Services, or that the report definition contains XML that is not well-formed or the XML is not valid based on the Report Definition schema.
I got this error when I used ReportSync to upload some .rdl files to SQL Server Report Services. In my case, the issue was that these .rdl files had some Text Box containing characters like ©
, —
(Em dash), –
(En dash) characters, etc. When uploading .rdl files using ReportSync, I had to encode these characters (©
, —
, –
, etc.) and use Placeholder Properties to set the Markup type to HTML in order to get rid of this error.
I wouldn't get this error If I manually uploaded each of the .rdl files one-by-one using SQL Server Reporting Services. But I have a lot of .rdl files and uploading each one individually would be time-consuming, which is why I use ReportSync to mass upload all .rdl files.
Sorry, if my answer doesn't seem relevant, but I hope this helps anyone else getting this error message when dealing with SSRS .rdl files.
This depends on the database server, but it is often called something like CEIL
or CEILING
. For example, in MySQL...
mysql> select ceil(10.5);
+------------+
| ceil(10.5) |
+------------+
| 11 |
+------------+
You can then do UPDATE PRODUCT SET price=CEIL(some_other_field);
Simply check it by calling post method on your layout or view
view.post( new Runnable() {
@Override
public void run() {
// your layout is now drawn completely , use it here.
}
});
There are a couple of ways to do it.
To run the Docker overriding the USER setting
docker exec -u 0 -it containerName bash
or
docker exec -u root -it --workdir / <containerName> bash
Make necessary file permissions, etc., during the image build in the Docker file
If all the packages are available in your Linux image, chpasswd
in the dockerfile before the USER utility.
For complete reference: http://muralitechblog.com/root-password-of-a-docker-container/
com.android.support:support-v4 just recently got update and maybe affect to plugin that use updated version in their dependencies. But if you cannot find in the dependencies (like if you use crosswalk plugin), just put this code in top of your code gradle plugin (no need to add on build.gradle).
configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:24.0.0'
}
Example location to put the code in crosswalk plugin here
Feel free to edit version of com.android.support (DO NOT USE THE 28.0.0) because thats the problem
The easiest way to get a new list would be:
List<long> unique = longs.Distinct().ToList();
Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.
Note that Distinct()
isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct()
for more information.
If you don't need it to be a List<long>
, you could just keep it as:
IEnumerable<long> unique = longs.Distinct();
At this point it will go through the de-duping each time you iterate over unique
though. Whether that's good or not will depend on your requirements.
Yes you can usually see what SOAP version is supported based on the WSDL.
Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.
My answer comes from here
You can make a derived class, which will set the timeout property of the base WebRequest
class:
using System;
using System.Net;
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
and you can use it just like the base WebClient class.
Use /bin/sh
. Create a small shell script that sets the variables, and then parse the template using the shell itself. Like so (edit to handle newlines correctly):
the number is ${i}
the word is ${word}
#!/bin/sh
#Set variables
i=1
word="dog"
#Read in template one line at the time, and replace variables (more
#natural (and efficient) way, thanks to Jonathan Leffler).
while read line
do
eval echo "$line"
done < "./template.txt"
#sh script.sh
the number is 1
the word is dog
Try the following code will help you to Launch an application from your application
Note: Replace the name fantacy with actual application name
NSString *mystr=[[NSString alloc] initWithFormat:@"fantacy://location?id=1"];
NSURL *myurl=[[NSURL alloc] initWithString:mystr];
[[UIApplication sharedApplication] openURL:myurl];
I came across this error today when I wanted to add a new column like this
df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
I wanted to process the REMARK
column of df_temp
to return 1 or 0. However I typed wrong variable with df
. And it returned error like this:
----> 1 df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
2417 else:
2418 # set column
-> 2419 self._set_item(key, value)
2420
2421 def _setitem_slice(self, key, value):
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
2483
2484 self._ensure_valid_index(value)
-> 2485 value = self._sanitize_column(key, value)
2486 NDFrame._set_item(self, key, value)
2487
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
2633
2634 if isinstance(value, Series):
-> 2635 value = reindexer(value)
2636
2637 elif isinstance(value, DataFrame):
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in reindexer(value)
2625 # duplicate axis
2626 if not value.index.is_unique:
-> 2627 raise e
2628
2629 # other
ValueError: cannot reindex from a duplicate axis
As you can see it, the right code should be
df_temp['REMARK_TYPE'] = df_temp.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
Because df
and df_temp
have a different number of rows. So it returned ValueError: cannot reindex from a duplicate axis
.
Hope you can understand it and my answer can help other people to debug their code.
Add #include "afxwin.h"
in your source file. It will solve your issue.
Looking at the error message, part of the code of your Default.aspx
is :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AmeriaTestTask.Default" %>
but AmeriaTestTask.Default
does not exists, so you have to change it, most probably to the class defined in Default.aspx.cs. For example for web api aplications, the class defined in Global.asax.cs is : public class WebApiApplication : System.Web.HttpApplication
and in the asax page you have :
<%@ Application Codebehind="Global.asax.cs" Inherits="MyProject.WebApiApplication" Language="C#" %>
you can use this command as well:
cp -ru /zzz/zzz/* /xxx/xxx
it would update your existing file with the newer one though.
You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery
$('#toggle').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#sendNewSms').removeAttr('disabled'); //enable input
} else {
$('#sendNewSms').attr('disabled', true); //disable input
}
});
Each row in /proc/$PID/maps
describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:
address perms offset dev inode pathname
08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm
-
will appear instead of the r
/w
/x
. If a region is not shared, it is private, so a p
will appear instead of an s
. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect
system call.mmap
), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.[heap]
, [stack]
, or [vdso]
. [vdso]
stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"You might notice a lot of anonymous regions. These are usually created by mmap
but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.
Also, you can use spring annotation RequestMapping above controller class for receveing application/json;utf-8 in all responses
@Controller
@RequestMapping(produces = {"application/json; charset=UTF-8","*/*;charset=UTF-8"})
public class MyController{
...
}
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.
D
or dd
deletes and copies the line to the register. You can use Vx
which only deletes the line and stays in the normal mode.
The answer from @Emiliano is excellent. You can also pass named parameters like so:
powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"
Note the parameters are outside the command call, and you'll use:
[parameter(Mandatory=$false)]
[string]$NamedParam1,
[parameter(Mandatory=$false)]
[string]$NamedParam2
You are correct, I think the [0,len(xs)]
is throwing you off. You'll want to reuse the original x-axis variable xs
and plot that with another numpy array of the same length that has your variable in it.
annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')
#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--')
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()
Hopefully that fixes the problem!
Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.
Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.
You can convert an int
to an unsigned int
. The conversion is valid and well-defined.
Since the value is negative, UINT_MAX + 1
is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
In this case, since int
on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.
your problem is why your code doesn't work.
this your code:
Firebase ref = new Firebase(FIREBASE_URL); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Log.e("Count " ,""+snapshot.getChildrenCount()); for (DataSnapshot postSnapshot: snapshot.getChildren()) { <YourClass> post = postSnapshot.getValue(<YourClass>.class); Log.e("Get Data", post.<YourMethod>()); } } @Override public void onCancelled(FirebaseError firebaseError) { Log.e("The read failed: " ,firebaseError.getMessage()); } })
you miss the simplest thing: getChildren()
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference = FirebaseAuth.getInstance().getReference("Donald Trump");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.getChildrenCount(); // retrieve number of childrens under Donald Trump
String[] hairColors = new String[count];
index = 0;
for (DataSnapshot datas : dataSnapshot.getChildren()){
hairColors[index] = datas.getValue(String.class);
}
index ++
for (int i = 0; i < count; i++)
Toast(MainActivity.this, "hairColors : " + hairColors[i], toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
You need to change it at "class": "sidebar_label"
Example, in your .sublime-theme file:
// Sidebar entry
{
"class": "sidebar_label",
"color": [212, 212, 213],
"shadow_offset": [0, 0],
"font.size":13
}
Using new api fetch:
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
_x000D_
If the files are not too big, you can use:
public static byte[] ComputeFileHash(string fileName)
{
using (var stream = File.OpenRead(fileName))
return System.Security.Cryptography.MD5.Create().ComputeHash(stream);
}
It will only be feasible to compare hashes if the hashes are useful to store.
(Edited the code to something much cleaner.)
The css to modify the spinner arrows is obtuse and unreliable cross-browser.
The most stable option I have found, is to absolutely position an image with pointer-events: none; on top of the spinners.
Untested in Edge but works in all other browsers.
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
I ran into a similar issue where I wanted to call a function defined in my controller from my view. Although it perplexed me for a while trying to figure out how to get to the controller from the view it turned out to be fairly straightforward.
I hand off an array to my views with data records that the view formats and presents to the user with jQuery DataTables (big duh). One column in the presented UI table is a set of action buttons that need to be created per row based on the content of the data in each of the rows. I guess I could have added the button definitions to the data rows as a column sent to the views but not all views needed the buttons so why? Instead, I wanted the view that needed them add them.
In the controller I pass a reference to the controller itself to the view as in
->with('callbackController', $this)
I called it callbackController as that is what I was doing. Now, inside my view I can either escape to PHP to use $callbackController to access the parent controller as in
<?php echo $callbackController->makeButtons($parameters); ?>
or just use the Blade mechanism
{!! $callbackController->makeButtons($parameters); ?>
It seems to be working fine across multiple controllers and views. I have not noticed a performance penalty using this mechanism and I have one huge table with over 50K rows.
I have not tried to pass on references to other objects (e.g., models, etc) yet but I do not see what that would not work as well
Might not be elegant but it seems to get the job done.
Missing Dependency: libffi.so.5 is here :
data = [4, 5, 6] # Your global variable
def print_data(data): # <-- Pass in a parameter called "data"
print data # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?
print_data(data)
PHPUnit's current "best practices" for exception testing seem.. lackluster (docs).
Since I wanted more than the current expectException
implementation, I made a trait to use on my test cases. It's only ~50 lines of code.
assert
syntaxassertNotThrows
Throwable
errorsI published the AssertThrows
trait to Github and packagist so it can be installed with composer.
Just to illustrate the spirit behind the syntax:
<?php
// Using simple callback
$this->assertThrows(MyException::class, [$obj, 'doSomethingBad']);
// Using anonymous function
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
Pretty neat?
Please see below for a more comprehensive usage example:
<?php
declare(strict_types=1);
use Jchook\AssertThrows\AssertThrows;
use PHPUnit\Framework\TestCase;
// These are just for illustration
use MyNamespace\MyException;
use MyNamespace\MyObject;
final class MyTest extends TestCase
{
use AssertThrows; // <--- adds the assertThrows method
public function testMyObject()
{
$obj = new MyObject();
// Test a basic exception is thrown
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
// Test custom aspects of a custom extension class
$this->assertThrows(MyException::class,
function() use ($obj) {
$obj->doSomethingBad();
},
function($exception) {
$this->assertEquals('Expected value', $exception->getCustomThing());
$this->assertEquals(123, $exception->getCode());
}
);
// Test that a specific exception is NOT thrown
$this->assertNotThrows(MyException::class, function() use ($obj) {
$obj->doSomethingGood();
});
}
}
?>
When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(
If you don't encounter any permission errors with
pip install -U numpy
try:
pip install --user -U numpy
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.
To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.
This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:
More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.
The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.
Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv
This MsvcLibX library is by no means complete, and contributions for improving it are welcome!
I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
In a general sense, you're going to need to change your probability array. Instead of having one number for each instance and classifying based on whether or not it is greater than 0.5, you're going to need a list of scores (one for each class), then take the largest of the scores as the class that was chosen (a.k.a. argmax).
You could use a dictionary to hold the probabilities for each classification:
prob_arr = [{classification_id: probability}, ...]
Choosing a classification would be something like:
for instance_scores in prob_arr :
predicted_classes = [cls for (cls, score) in instance_scores.iteritems() if score = max(instance_scores.values())]
This handles the case where two classes have the same scores. You can get one score, by choosing the first one in that list, but how you handle that depends on what you're classifying.
Once you have your list of predicted classes and a list of expected classes you can use code like Torsten Marek's to create the confusion array and calculate the accuracy.
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
1,new Long(intValue);
2,Long.valueOf(intValue);
If I understand the question, then it seems to me that the questioner is really asking "OK, so 3-tier is well understood, but it seems that there's a mix of hype, confusion, and uncertainty around what 4-tier, or to generalize, N-tier architectures mean. So...what's a definition of N-tier that is widely understood and agreed upon?"
It's actually a fairly deep question, and to explain why, I need to go a little deeper. Bear with me.
The classic 3-tier architecture: database, "business logic" and presentation, is a good way to clarify how to honor the principle of separation of concerns. Which is to say, if I want to change how "the business" wants to service customers, I should not have to look through the entire system to figure out how to do this, and in particular, decisions business issues shouldn't be scattered willy-nilly through the code.
Now, this model served well for decades, and it is the classic 'client-server' model. Fast forward to cloud offerings, where web browsers are the user interface for a broad and physically distributed set of users, and one typically ends up having to add content distribution services, which aren't a part of the classic 3-tier architecture (and which need to be managed in their own right).
The concept generalizes when it comes to services, micro-services, how data and computation are distributed and so on. Whether or not something is a 'tier' largely comes down to whether or not the tier provides an interface and deployment model to services that are behind (or beneath) the tier. So a content distribution network would be a tier, but an authentication service would not be.
Now, go and read other descriptions of examples of N-tier architectures with this concept in mind, and you will begin to understand the issue. Other perspectives include vendor-based approaches (e.g. NGINX), content-aware load balancers, data isolation and security services (e.g. IBM Datapower), all of which may or may not add value to a given architecture, deployment, and use cases.
try this one:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData];
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];
may it will help.
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:
String value = "";//any text you are pre-filling in the EditText
final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:
I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I
Note that for colour images you would have to apply this to each of the channels in the image.
You will be much happier using a dictionary instead:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
Features color wheel and pallet picker dialogs
There are two approaches to centering a column <div>
in Bootstrap 3:
The first approach uses Bootstrap's own offset classes so it requires no change in markup and no extra CSS. The key is to set an offset equal to half of the remaining size of the row. So for example, a column of size 2 would be centered by adding an offset of 5, that's (12-2)/2
.
In markup this would look like:
<div class="row">
<div class="col-md-2 col-md-offset-5"></div>
</div>
Now, there's an obvious drawback for this method. It only works for even column sizes, so only .col-X-2
, .col-X-4
, col-X-6
, col-X-8
, and col-X-10
are supported.
margin:auto
)You can center any column size by using the proven margin: 0 auto;
technique. You just need to take care of the floating that is added by Bootstrap's grid system. I recommend defining a custom CSS class like the following:
.col-centered{
float: none;
margin: 0 auto;
}
Now you can add it to any column size at any screen size, and it will work seamlessly with Bootstrap's responsive layout:
<div class="row">
<div class="col-lg-1 col-centered"></div>
</div>
Note: With both techniques you could skip the .row
element and have the column centered inside a .container
, but you would notice a minimal difference in the actual column size because of the padding in the container class.
Update:
Since v3.0.1 Bootstrap has a built-in class named center-block
that uses margin: 0 auto
, but is missing float:none
, you can add that to your CSS to make it work with the grid system.
If you have too much watchers and you need to clear all of them, you can push them into an array and destroy every $watch
in a loop.
var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
//do something
}));
for(var i = 0; i < watchers.length; ++i){
if(typeof watchers[i] === 'function'){
watchers[i]();
}
}
watchers = [];
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
Different database systems have different names for the same type of index, so be careful with this. For example, what SQL Server and Sybase call "clustered index" is called in Oracle an "index-organised table".
To validate Phone number using regular expression in java script.
In india phone is 10 digit and starting digits are 6,7,8 and 9.
Javascript and HTML code:
function validate()
{
var text = document.getElementById("pno").value;
var regx = /^[6-9]\d{9}$/ ;
if(regx.test(text))
alert("valid");
else
alert("invalid");
}
_x000D_
<html>
<head>
<title>JS compiler - knox97</title>
</head>
<body>
<input id="pno" placeholder="phonenumber" type="tel" maxlength="10" >
</br></br>
<button onclick="validate()" type="button">submit</button>
</body>
</html>
_x000D_
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
You could do this:
sample_data = data[sample(nrow(data), sample_size, replace = FALSE), ]
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("Seconds since January 1, 1970 = %ld\n", seconds);
return(0);
}
And will get similar result:
Seconds since January 1, 1970 = 1476107865
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
I believe what are you asking about is a variable interpolation in PHP.
Let's do a simple fixture:
$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';
Now we have an object, where:
print_r($obj);
Will give output:
stdClass Object
(
[foo] => Array
(
[0] => bar
)
[property] => value
)
And we have variable $var
containing string "foo".
If you'll try to use:
$give_me_foo = $obj->$var[0];
Instead of:
$give_me_foo = $obj->foo[0];
You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0]
to object $obj
. And - as you can see from fixture - there is no content of $var[0]
defined. Variable $var
is a string and not an array.
What you can do in this case is to use curly braces, which will assure that at first is called content of $var
, and subsequently the rest of message-sent:
$give_me_foo = $obj->{$var}[0];
The result is "bar"
, as you would expect.
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
Set<String> keyList = new HashSet();
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher matcher = regex.matcher("Content goes here");
while(matcher.find()) {
keyList.add(matcher.group(1));
}
return keyList;
A little clearer... A software program that has kernel mode access has total access to all of the computer's data and its hardware.
Since Windows Vista Microsoft has stopped any and all I/O processes from accessing the kernel (ring 0) directly ever again. The closest we get is a folder created as a virtual kernel access partition, but technically no access to kernel itself; the kernel meets halfway.
This is because the software itself dictates which token to use, so if it asks for an administrator access token, instead of just allowing communications with the kernel like on Windows XP you are prompted to allow access to the kernel, each and every time. Changing UAC could reduce prompts, but never the kernel prompts.
Even when you login as an Administrator, you are running processes as a standard user until prompted to elevate the rights you have. I believe logged in as the administrator saves you from entering the credentials. But it also writes to the administrator users folder structure.
Kernel access is similar to root access in Linux. When you elevate your permissions you are isolating yourself from the root of C:\ and whatever lovely environment variables are contained within.
If you remember BSODs this was the OS shutting down when it believed a bad I/O reached the kernel.
That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?
Also, have you perhaps changed the file's properties' Build Action
to something other than Compile
?
The response of staff is correct, but if you want to further automate can do:
$ sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"
Done! You saved User = postgres and password = postgres.
If you do not have a password for the User postgres ubuntu do:
$ sudo passwd postgres
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
I had this error message with boot2docker on windows with the docker-oracle-xe-11g image (https://registry.hub.docker.com/u/wnameless/oracle-xe-11g/).
The reason was that the virtual box disk was full (check with boot2docker.exe ssh df
). Deleting old images and restarting the container solved the problem.
A little bit of validation with:
/<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(htmlStringHere)
This searches for empty tags (some predefined) and /
terminated XHTML empty tags and validates as HTML because of the empty tag OR will capture the tag name and attempt to find it's closing tag somewhere in the string to validate as HTML.
Explained demo: http://regex101.com/r/cX0eP2
Update:
Complete validation with:
/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(htmlStringHere)
This does proper validation as it contains ALL HTML tags, empty ones first followed by the rest which need a closing tag.
Explained demo here: http://regex101.com/r/pE1mT5
Just another option, if you want to use only a cli interface, just use the define
option of webpack. I add the following script in my package.json
:
"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"
So I just have to run npm run build-production
.
If we define dx = x2 - x1
and dy = y2 - y1
, then the normals are (-dy, dx)
and (dy, -dx)
.
Note that no division is required, and so you're not risking dividing by zero.
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()