Just use HTML anchor tag <a>
and start the attribute href
with tel:
. I suggest starting the phone number with the country code. pay attention to the following example:
<a href="tel:+989123456789">NO Different What it is</a>
For this example, the country code is +98
.
Hint: It is so suitable for cellphones, I know tel:
prefix calls FaceTime
on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.
For more information: you can visit the list of URL schemes supported by browsers to know all href
values prefixes.
you need to take out the quotes:
soda = a + b
(You want to refer to the variables a
and b
, not the strings "a" and "b")
local function CountedTable(x)
assert(type(x) == 'table', 'bad parameter #1: must be table')
local new_t = {}
local mt = {}
-- `all` will represent the number of both
local all = 0
for k, v in pairs(x) do
all = all + 1
end
mt.__newindex = function(t, k, v)
if v == nil then
if rawget(x, k) ~= nil then
all = all - 1
end
else
if rawget(x, k) == nil then
all = all + 1
end
end
rawset(x, k, v)
end
mt.__index = function(t, k)
if k == 'totalCount' then return all
else return rawget(x, k) end
end
return setmetatable(new_t, mt)
end
local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }
assert(bar.totalCount == 4)
assert(bar.x == 23)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = 24
bar.x = 25
assert(bar.x == 25)
assert(bar.totalCount == 4)
In Python 2, raw_input()
returns a string, and input()
tries to run the input as a Python expression.
Since getting a string was almost always what you wanted, Python 3 does that with input()
. As Sven says, if you ever want the old behaviour, eval(input())
works.
To add bold, italic and underline, just add the following to the font argument:
font=("Arial", 8, 'normal', 'bold', 'italic', 'underline')
Use toCharArray() method. It splits the string into an array of characters:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29
String str = "aabbab";
char[] chs = str.toCharArray();
There is also CrossBrowserTesting, which supports many browsers, seems to work without installing any plugins on your computer, and also includes a very neat layout comparison tool.
CrossBrowserTesting was advertised from within Browsershots.
The target of the mousemove
DOM event is the top-most DOM element under the cursor when the mouse moves:
(function(){
//Don't fire multiple times in a row for the same element
var prevTarget=null;
document.addEventListener('mousemove', function(e) {
//This will be the top-most DOM element under cursor
var target=e.target;
if(target!==prevTarget){
console.log(target);
prevTarget=target;
}
});
})();
This is similar to @Philip Walton's solution, but doesn't require jQuery or a setInterval.
Simply removing and reinstalling the app worked for me:
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
method will turn a managed type instance into a JSON string.
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
I recommend using the built-in functions from jQuery or lodash/Underscore. They're simpler to use and easier to read.
Either function will handle the case DRAX mentioned... that is, they both check if (A) the variable is a string literal or (B) it's an instance of the String object. In either case, these functions correctly identify the value as being a string.
lodash / Underscore.js
if(_.isString(myVar))
//it's a string
else
//it's something else
jQuery
if($.type(myVar) === "string")
//it's a string
else
//it's something else
See lodash Documentation for _.isString() for more details.
See jQuery Documentation for $.type() for more details.
Update:
Guido van Rossum announced on the mailing list that as of Python 3.7 dict
s in all Python implementations must preserve insertion order.
JLabel is actually capable of displaying some rudimentary HTML, which is why it is not responding to your use of the newline character (unlike, say, System.out).
If you put in the corresponding HTML and used <BR>
, you would get your newlines.
These days listen for oninput
. It feels like onchange
without the need to lose focus on the element. It is HTML5.
It’s supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange
. I use it like this:
const source = document.getElementById('source');_x000D_
const result = document.getElementById('result');_x000D_
_x000D_
const inputHandler = function(e) {_x000D_
result.innerHTML = e.target.value;_x000D_
}_x000D_
_x000D_
source.addEventListener('input', inputHandler);_x000D_
source.addEventListener('propertychange', inputHandler); // for IE8_x000D_
// Firefox/Edge18-/IE9+ don’t fire on <select><option>_x000D_
// source.addEventListener('change', inputHandler);
_x000D_
<input id="source">_x000D_
<div id="result"></div>
_x000D_
All above answers didn't helped,and then I deleted and recreated emulator all worked fine
There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday
provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.
You can use this function like this:
struct timeval tval_before, tval_after, tval_result;
gettimeofday(&tval_before, NULL);
// Some code you want to time, for example:
sleep(1);
gettimeofday(&tval_after, NULL);
timersub(&tval_after, &tval_before, &tval_result);
printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);
This returns Time elapsed: 1.000870
on my machine.
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
Here's one way to do it:
mkdir -p `dirname /path/to/copy/file/to/is/very/deep/there` \
&& cp -r file /path/to/copy/file/to/is/very/deep/there
dirname
will give you the parent of the destination directory or file. mkdir -p `dirname ...` will then create that directory ensuring that when you call cp -r the correct base directory is in place.
The advantage of this over --parents is that it works for the case where the last element in the destination path is a filename.
And it'll work on OS X.
To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:
> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct
Example of Integer:
> x<- 2L
> print(x)
Example of Numeric (kind of like double/float from other programming languages)
> x<-3.4
> print(x)
You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.
Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.
Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.
Something like this - a riff on @maarten-vanlinthout's answer
ip -f inet a show eth0| grep inet| awk '{ print $2}' | cut -d/ -f1
In my case I was using a native DLL in C#. This DLL depended on couple of other DLLs that were missing. Once those other DLLs were added everything worked.
My vision is
Procedural programming
unit is a procedure, in Object oriented programming
unit is a class. Unit is isolated and reflects a developer perspectiveUnit
. User perspective, which describes a feature, use case, story...
components
work together. It can be other application, service, library, database, network etc.
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Nov 13 2017 22:05:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
now = new Date();_x000D_
seconds = (theevent - now) / 1000;_x000D_
seconds = Math.round(seconds);_x000D_
minutes = seconds / 60;_x000D_
minutes = Math.round(minutes);_x000D_
hours = minutes / 60;_x000D_
hours = Math.round(hours);_x000D_
days = hours / 24;_x000D_
days = Math.round(days);_x000D_
document.form1.days.value = days;_x000D_
document.form1.hours.value = hours;_x000D_
document.form1.minutes.value = minutes;_x000D_
document.form1.seconds.value = seconds;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
<p>Days_x000D_
<input type="text" name="days" value="0" size="3">Hours_x000D_
<input type="text" name="hours" value="0" size="4">Minutes_x000D_
<input type="text" name="minutes" value="0" size="7">Seconds_x000D_
<input type="text" name="seconds" value="0" size="7">_x000D_
</p>_x000D_
</form>
_x000D_
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
I just made this little trick :
window.getRunningScript = () => {
return () => {
return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
}
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())
? Works on: Chrome, Firefox, Edge, Opera
Enjoy !
Probably the simplest way is to use the InputBox
method of the Microsoft.VisualBasic.Interaction
class:
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Demographics'
$msg = 'Enter your demographics:'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
A LEFT JOIN
is absolutely not faster than an INNER JOIN
. In fact, it's slower; by definition, an outer join (LEFT JOIN
or RIGHT JOIN
) has to do all the work of an INNER JOIN
plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.
(And even if a LEFT JOIN
were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN
, so you cannot simply go replacing all instances of one with the other!)
Most likely your performance problems lie elsewhere, such as not having a candidate key or foreign key indexed properly. 9 tables is quite a lot to be joining so the slowdown could literally be almost anywhere. If you post your schema, we might be able to provide more details.
Edit:
Reflecting further on this, I could think of one circumstance under which a LEFT JOIN
might be faster than an INNER JOIN
, and that is when:
Consider this example:
CREATE TABLE #Test1
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test1 (ID, Name) VALUES (1, 'One')
INSERT #Test1 (ID, Name) VALUES (2, 'Two')
INSERT #Test1 (ID, Name) VALUES (3, 'Three')
INSERT #Test1 (ID, Name) VALUES (4, 'Four')
INSERT #Test1 (ID, Name) VALUES (5, 'Five')
CREATE TABLE #Test2
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test2 (ID, Name) VALUES (1, 'One')
INSERT #Test2 (ID, Name) VALUES (2, 'Two')
INSERT #Test2 (ID, Name) VALUES (3, 'Three')
INSERT #Test2 (ID, Name) VALUES (4, 'Four')
INSERT #Test2 (ID, Name) VALUES (5, 'Five')
SELECT *
FROM #Test1 t1
INNER JOIN #Test2 t2
ON t2.Name = t1.Name
SELECT *
FROM #Test1 t1
LEFT JOIN #Test2 t2
ON t2.Name = t1.Name
DROP TABLE #Test1
DROP TABLE #Test2
If you run this and view the execution plan, you'll see that the INNER JOIN
query does indeed cost more than the LEFT JOIN
, because it satisfies the two criteria above. It's because SQL Server wants to do a hash match for the INNER JOIN
, but does nested loops for the LEFT JOIN
; the former is normally much faster, but since the number of rows is so tiny and there's no index to use, the hashing operation turns out to be the most expensive part of the query.
You can see the same effect by writing a program in your favourite programming language to perform a large number of lookups on a list with 5 elements, vs. a hash table with 5 elements. Because of the size, the hash table version is actually slower. But increase it to 50 elements, or 5000 elements, and the list version slows to a crawl, because it's O(N) vs. O(1) for the hashtable.
But change this query to be on the ID
column instead of Name
and you'll see a very different story. In that case, it does nested loops for both queries, but the INNER JOIN
version is able to replace one of the clustered index scans with a seek - meaning that this will literally be an order of magnitude faster with a large number of rows.
So the conclusion is more or less what I mentioned several paragraphs above; this is almost certainly an indexing or index coverage problem, possibly combined with one or more very small tables. Those are the only circumstances under which SQL Server might sometimes choose a worse execution plan for an INNER JOIN
than a LEFT JOIN
.
public String appendNewStringToExisting(String exisitingString, String newString, int number) {
StringBuilder builder = new StringBuilder(exisitingString);
for(int iDx = 0; iDx < number; iDx++){
builder.append(newString);
}
return builder.toString();
}
The page.github.com does mention:
Github Pages are hosted free and easily published through our site,
Without ever mentioning access control.
The GitHub page help doesn't mention any ACL either.
They are best managed in a gh-pages branch, and can be managed in their own submodule.
But again, without any restriction in term of visibility once published by GitHub.
You could always do this:
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys on MSDN is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.
I had the same error when was trying to update linked table.
The issue was that linked table had no PRIMARY KEY.
After adding primary key constraint on database side and re linking this table to access problem was solved.
Hope it will help somebody.
In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".
But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.
I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:
XAML:
<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextBox_EnterButtomEvent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height ="0.3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
Input text end press ENTER:
</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
You have entered:
</TextBlock>
<TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>
C# logical part (KeyUp Event handler is attached to a grid element):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
TextBox txtBox = e.Source as TextBox;
if(txtBox != null)
{
this.txtBlock.Text = txtBox.Text;
this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
}
}
}
}
Result:
May I humbly suggest the Rabin-Karp algorithm if the big
list is really big. The link even contains almost-usable code in almost-Python.
Since PHP 5.4.0 you can use getallheaders
function which returns all request headers as an associative array:
var_dump(getallheaders());
// array(8) {
// ["Accept"]=>
// string(63) "text/html[...]"
// ["Accept-Charset"]=>
// string(31) "ISSO-8859-1[...]"
// ["Accept-Encoding"]=>
// string(17) "gzip,deflate,sdch"
// ["Accept-Language"]=>
// string(14) "en-US,en;q=0.8"
// ["Cache-Control"]=>
// string(9) "max-age=0"
// ["Connection"]=>
// string(10) "keep-alive"
// ["Host"]=>
// string(9) "localhost"
// ["User-Agent"]=>
// string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }
Earlier this function worked only when PHP was running as an Apache/NSAPI module.
In my opinion, the easiest way to setup the local locale in python{,3} is:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'de_DE.UTF-8'
Then, locale aware stuff just works, if you're on a decent linux distro, and should work on binary distributions of the other OSes as well (or that's a bug IMHO).
>>> import datetime as dt
>>> print(dt.date.today().strftime("%A %d. %B %Y"))
Sonntag 11. Dezember 2016
If you are using Spring boot, you should add this plugin in your pom.xml
:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Eclipse IDE for Java Developers 'Servers' doesn't exist. Therefore download correct Eclipse IDE. It is Eclipse IDE for Enterprise Java Developers(Eclipse IDE for Java EE Developers). This way is easy.
if you lost a "!" in your code ,like this code below, you'll also get this error.
import UIKit
class MemeDetailViewController : UIViewController {
@IBOutlet weak var memeImage: UIImageView!
var meme:Meme! // lost"!"
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.memeImage!.image = meme.memedImage
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
}
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
Using Float.parseFloat()
?
class Test {
public static void main(String[] args) {
String s = "3.14";
float f = Float.parseFloat(s);
System.out.println(f);
}
}
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
Here's your one-liner, without using any regular expressions, which can get expensive at times:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
returns:
'123453120'
You may want to look into using java's java.math.BigDecimal class if you really need precision math. Here is a good article from Oracle/Sun on the case for BigDecimal. While you can never represent 1/3 as someone mentioned, you can have the power to decide exactly how precise you want the result to be. setScale() is your friend.. :)
Ok, because I have way too much time on my hands at the moment here is a code example that relates to your question:
import java.math.BigDecimal;
/**
* Created by a wonderful programmer known as:
* Vincent Stoessel
* [email protected]
* on Mar 17, 2010 at 11:05:16 PM
*/
public class BigUp {
public static void main(String[] args) {
BigDecimal first, second, result ;
first = new BigDecimal("33.33333333333333") ;
second = new BigDecimal("100") ;
result = first.divide(second);
System.out.println("result is " + result);
//will print : result is 0.3333333333333333
}
}
and to plug my new favorite language, Groovy, here is a neater example of the same thing:
import java.math.BigDecimal
def first = new BigDecimal("33.33333333333333")
def second = new BigDecimal("100")
println "result is " + first/second // will print: result is 0.33333333333333
The Best way is array_splice
array_splice($array, array_search(58, $array ), 1);
Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/
So if you have the following structure now:
C:\Program Files\Java\jre6\bin\
keytool.exe
debug.keystore
then execute:
C:\Program Files\Java\jre6\bin>keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android
May the div with id="content" not be created when this event is attached? You can try live() jquery method.
Else there may be multiple divs with the same id or you just spelled it wrong, it happens...
Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById
is case sensitive. You were passing Div2
when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}
I was stuck on an issue where datepicker() appeared to be doing nothing. It turned out that the issue was that the input was inside a Bootstrap "input-group" div. Simply taking the input out of the input-group resolved the issue.
Use double quotes while using BASH variables.
mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"
BASH doesn't expand variables in single quotes.
Just come across this, the answer is simple, use ISNULL
. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:
WHERE wpp.comment NOT LIKE '%CORE%'
So, you have temporarily substitute a value in the null
(empty) records by using the ISNULL
command, eg
WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'
This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg
WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
If you like Guava, you may use its Ints
class:
For int
? byte[]
, use toByteArray()
:
byte[] byteArray = Ints.toByteArray(0xAABBCCDD);
Result is {0xAA, 0xBB, 0xCC, 0xDD}
.
Its reverse is fromByteArray()
or fromBytes()
:
int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD});
int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);
Result is 0xAABBCCDD
.
If you use private static variables in your class, Static Inner classes in your class can reach your variables. This is perfectly good for context security.
This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.
public class Contact
{
public string Name { get; set; }
}
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:
$.ajax({
type: "POST",
crossdomain: true,
url: "http://localhost:1415/anything",
dataType: "json",
data: JSON.stringify({
anydata1: "any1",
anydata2: "any2",
}),
success: function (result) {
console.log(result)
},
error: function (xhr, status, err) {
console.error(xhr, status, err);
}
});
with this headers on c# server:
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");
Using Nested Scroll View instead of Scroll View solved my problem
<LinearLayout> <!--Main Layout -->
<android.support.v4.widget.NestedScrollView>
<LinearLayout > <!--Nested Scoll View enclosing Layout -->`
<View > <!-- upper content -->
<RecyclerView >
</LinearLayout >
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
If your count(distinct(x))
is significantly slower than count(x)
then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null)
, using triggers. But your write performance will suffer and if you update multiple x
values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.
<?php
require 'db_config.php';
$id = $_POST["id"];
$post = $_POST;
$sql = "UPDATE items SET title = '".$post['title']."'
,description = '".$post['description']."'
WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>
Add the following to package.json
:
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
},
Add the following to .npmrc
(same directory as package.json
):
engine-strict=true
One more solution, that hasn't been posted, yet:
String regex = "\\p{Digit}+"; // uses POSIX character class
The runas /netonly /user:domain\username program.exe
command only worked for me on Windows 10
when running the command batch as regular user I got the wrong password issue mentioned by some users on previous comments.
You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:
<ul>
<li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
....
<span>{{ usersList.length | number }}</span>
If you need examples, see the AngularJs filtered count examples/demos
In terms of MutationObservers
, setting innerHTML
generates a childList
mutation due to the browsers removing the node and then adding a new node with the value of innerHTML
.
If you set innerText
, a characterData
mutation is generated.
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
Not really, you have to assign a variable. So
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
Here is a good article on the matter - "Use references when you can, and pointers when you have to."
UPDATE:
In scikit-learn 0.22, there's a new feature to plot the confusion matrix directly.
See the documentation: sklearn.metrics.plot_confusion_matrix
OLD ANSWER:
I think it's worth mentioning the use of seaborn.heatmap
here.
import seaborn as sns
import matplotlib.pyplot as plt
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);
Use parseJSON
. Look at the doc
var obj = $.parseJSON(data);
Something like this:
$.ajax({
type: "POST",
url: '/admin/systemgoalssystemgoalupdate?format=html',
data: formdata,
success: function (data) {
console.log($.parseJSON(data)); //will log Object
}
});
3.1 didn't matter for me.
It took me a while, but I managed to find the 2.1 release to try that out here: http://www.oracle.com/technetwork/testcontent/index21-ea1-095147.html
1.2 http://www.oracle.com/technetwork/testcontent/index-archive12-101280.html
That doesn't work either though, still no tables so it looks like something with permission.
simply used the +
operator. Javascript concats strings with +
This problem occures when you use your service via other application.If application has config file just add your service config information to this file. In my situation there wasn't any config file so I use this technique and it worked fine.Just store url address in application,read it and using BasicHttpBinding() method send it to service application as parameter.This is simple demonstration how I did it:
Configuration config = new Configuration(dataRowSet[0]["ServiceUrl"].ToString());
var remoteAddress = new System.ServiceModel.EndpointAddress(config.Url);
SimpleService.PayPointSoapClient client =
new SimpleService.PayPointSoapClient(new System.ServiceModel.BasicHttpBinding(),
remoteAddress);
SimpleService.AccountcredResponse response = client.AccountCred(request);
In pure jQuery style:
$(location).attr('href');
The location object also has other properties, like host, hash, protocol, and pathname.
There are several ways to implement it:
For ASP.NET Standard CheckBox:
.tdInputCheckBox
{
position:relative;
top:-2px;
}
<table>
<tr>
<td class="tdInputCheckBox">
<asp:CheckBox ID="chkMale" runat="server" Text="Male" />
<asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
</td>
</tr>
</table>
For DevExpress CheckBox:
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
For RadioButtonList:
<asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
For Required Field Validators:
<asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
If, like me, your goal is get the database host and SID to generate a Oracle JDBC url, as
jdbc:oracle:thin:@<server_host>:1521:<instance_name>
the following commands will help:
Oracle query command to check the SID (or instance name):
select sys_context('userenv','instance_name') from dual;
Oracle query command to check database name (or server host):
select sys_context('userenv', 'server_host') from dual;
Att. Sergio Marcelo
In the function declaration you have to type as
VOID FUN(INT *a[]);
/*HERE YOU CAN TAKE ANY FUNCTION RETURN TYPE HERE I CAN TAKE VOID AS THE FUNCTION RETURN TYPE FOR THE FUNCTION FUN*/
//IN THE FUNCTION HEADER WE CAN WRITE AS FOLLOWS
void fun(int *a[])
//in the function body we can use as
a[i]=var
John C is the closest, but XPath is case sensitive, so the correct XPath would be:
/bla/a[contains(@prop, 'Foo')]
If you need to list all rows where all the column values are NULL
, then i'd use the COLLATE
function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL
, you should get all the rows containing only nulls.
SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL
You shouldn't really have any tables with ALL the columns
null, as this means you don't have a primary key
(not allowed to be null
). Not having a primary key is something to be avoided; this breaks the first normal form.
Note: The snippet would only work if the iframe is with the same origin.
Other answers proposed the load
event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.
Here's a plain JavaScript solution:
function iframeURLChange(iframe, callback) {_x000D_
var unloadHandler = function () {_x000D_
// Timeout needed because the URL changes immediately after_x000D_
// the `unload` event is dispatched._x000D_
setTimeout(function () {_x000D_
callback(iframe.contentWindow.location.href);_x000D_
}, 0);_x000D_
};_x000D_
_x000D_
function attachUnload() {_x000D_
// Remove the unloadHandler in case it was already attached._x000D_
// Otherwise, the change will be dispatched twice._x000D_
iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
}_x000D_
_x000D_
iframe.addEventListener("load", attachUnload);_x000D_
attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
This will successfully track the src
attribute changes, as well as any URL changes made from within the iframe itself.
Tested in all modern browsers.
I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.
<a href="#">Start of page</a>
"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."
There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.
The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.
Try this:
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class currentTime {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println( sdf.format(cal.getTime()) );
}
}
You can format SimpleDateFormat in the way you like. For any additional information you can look in java api:
What worked for me:
worksheet.Cells[0, 0].Style.WrapText = true;
worksheet.Cells[0, 0].Value = yourStringValue.Replace("\\r\\n", "\r\n");
My issue was that the \r\n came escaped.
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="#" title="Buy Sell Rent Everyting">
<img style="max-width:100px; margin-top: -7px;"
src="/img/transparent-white-logo.png">
</a>
</div>
I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone
int sleepTime = 5 * 60; // 5 minutes
for (int secondsRemaining = sleepTime; secondsRemaining > 0; secondsRemaining --)
{
double minutesPrecise = secondsRemaining / 60;
double minutesRounded = Math.Round(minutesPrecise, 0);
int seconds = Convert.ToInt32((minutesRounded * 60) - secondsRemaining);
Console.Write($"\rProcess will resume in {minutesRounded}:{String.Format("{0:D2}", -seconds)} ");
Thread.Sleep(1000);
}
Console.WriteLine("");
dict((k, v) for k, v in points.items() if all(x < 5 for x in v))
You could choose to call .iteritems()
instead of .items()
if you're in Python 2 and points
may have a lot of entries.
all(x < 5 for x in v)
may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and
) but it will work fine;-).
As Brannon says, it's OrderByDescending
and ThenByDescending
:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
is equivalent to:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
Instead of converting the JSON string to an ArrayList or even a Map, you can just create a JSONObject itself. This object has the ability to get string values by key, as you want and also to remove objects.
To create a JSONObject
from a properly formatted JSON string, you simply call the appropriate constructor.
JSONObject json = new JSONObject(jsonString);
Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:
To export selected certificates
- Choose Xcode > Preferences.
- Click Accounts at the top of the window.
- Select the team you want to view, and click View Details.
- Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.
- Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
- Click Save. The file is saved to the location you specified with a .p12 extension.
Source (Apple's documentation)
To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.
This is really a problem within python. The origin of confusion is that people mistakenly takes the relative import as path relative which is not.
For example when you write in faa.py:
from .. import foo
This has a meaning only if faa.py was identified and loaded by python, during execution, as a part of a package. In that case,the module's name for faa.py would be for example some_packagename.faa. If the file was loaded just because it is in the current directory, when python is run, then its name would not refer to any package and eventually relative import would fail.
A simple solution to refer modules in the current directory, is to use this:
if __package__ is None or __package__ == '':
# uses current directory visibility
import foo
else:
# uses current package visibility
from . import foo
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
I did it by putting
export JAVA_HOME=`/usr/libexec/java_home`
(backtics) in my .bashrc. See my comment on Adrian's answer.
The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include
directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.
I am using outerHTML
for elements (the main <html>
container), and XMLSerializer
for anything else including <!DOCTYPE>
, random comments outside the <html>
container, or whatever else might be there. It seems that whitespace isn't preserved outside the <html>
element, so I'm adding newlines by default with sep="\n"
.
function get_document_html(sep="\n") {_x000D_
let html = "";_x000D_
let xml = new XMLSerializer();_x000D_
for (let n of document.childNodes) {_x000D_
if (n.nodeType == Node.ELEMENT_NODE)_x000D_
html += n.outerHTML + sep;_x000D_
else_x000D_
html += xml.serializeToString(n) + sep;_x000D_
}_x000D_
return html;_x000D_
}_x000D_
_x000D_
console.log(get_document_html().slice(0, 200));
_x000D_
Got the same question from a friend. My suggestion which does not require !Important
looks like this: I add a custom class "no-border
" which can be added to the bootstrap table.
.table.no-border tr td, .table.no-border tr th {
border-width: 0;
}
You can see my go at a solution here
I discovered the most curious thing! If you set it to null
using Data Binding:
android:background="@{null}"
Then not only is the background removed, but the view still has the padding that was calculated from the default background. So for some reason the deferred null setting doesn't clear the padding from the previous bg..? The padding on the view is left/top/right 4dp, bottom 13dp (from emulator level 21).
May not have same end result on all API levels, so beware! Someone tell me if you test this and find it reliable. (Also note that that bottom padding sticks out because of that underline that was in the original. So you'll probably want to change it in the XML, or reset it in the code after it's loaded to equal top...
The idea of retrying the query in case of Deadlock exception is good, but it can be terribly slow, since mysql query will keep waiting for locks to be released. And incase of deadlock mysql is trying to find if there is any deadlock, and even after finding out that there is a deadlock, it waits a while before kicking out a thread in order to get out from deadlock situation.
What I did when I faced this situation is to implement locking in your own code, since it is the locking mechanism of mysql is failing due to a bug. So I implemented my own row level locking in my java code:
private HashMap<String, Object> rowIdToRowLockMap = new HashMap<String, Object>();
private final Object hashmapLock = new Object();
public void handleShortCode(Integer rowId)
{
Object lock = null;
synchronized(hashmapLock)
{
lock = rowIdToRowLockMap.get(rowId);
if (lock == null)
{
rowIdToRowLockMap.put(rowId, lock = new Object());
}
}
synchronized (lock)
{
// Execute your queries on row by row id
}
}
array_splice($array, 0, 1);
string text = Console.ReadLine();
bool isNumber = false;
for (int i = 0; i < text.Length; i++)
{
if (char.IsDigit(text[i]))
{
isNumber = true;
break;
}
}
if (isNumber)
{
Console.WriteLine("Text contains number.");
}
else
{
Console.WriteLine("Text doesn't contain number.");
}
Console.ReadKey();
Or Linq:
string text = Console.ReadLine();
bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
Console.ReadKey();
I had the same its because of version incompatibility check for version or remove version if using spring boot
I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:
ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
app.certificateString is a String that contains the Certificate, for example:
static public String certificateString=
"-----BEGIN CERTIFICATE-----\n" +
"MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
"BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
... a bunch of characters...
"5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
"-----END CERTIFICATE-----";
I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.
Rather than changing owners, which might lock out other local users, or –some day– your own ruby server/deployment-things... running under a different user...
I would rather simply extend rights of that particular folder to... well, everybody:
cd /var/lib
sudo chmod -R a+w gems/
(I did encounter your error as well. So this is fairly verified.)
If updating cURL doesn't fix it, updating NSS should do the trick.
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.
Yes, otherwise it wouldn't be called "deprecated"
Unless stated otherwise in docs, it should be the same as before
No, but if there were problems in v1 they aren't about to fix them
A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :
Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))
All credit goes to Guru Brad Schulz's Blog
You simply call
Blog::all();
//example usage.
$posts = Blog::all();
$posts->each(function($post) // foreach($posts as $post) { }
{
//do something
}
from anywhere in your application.
Reading the documentation will help a lot.
Simplest code is DataGridView1.SelectedCells(column_index).Value
As an example, for the first selected cell:
DataGridView1.SelectedCells(0).Value
My own settings (Java 1.7, modify for 1.6):
-vm
C:/Program Files (x86)/Java/jdk1.7.0/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20100628
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-server
-Dosgi.requiredJavaVersion=1.7
-Xmn100m
-Xss1m
-XgcPrio:deterministic
-XpauseTarget:20
-XX:PermSize=400M
-XX:MaxPermSize=500M
-XX:CompileThreshold=10
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UnlockExperimentalVMOptions
-XX:+DoEscapeAnalysis
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-XX:+AggressiveOpts
-Xms512m
-Xmx512m
Most answers here focused on how to check if a collection is Empty or Null which was quite straight forward as demonstrated by them.
Like many people here, I was also wondering why does not Microsoft itself provide such a basic feature which is already provided for String type (String.IsNullOrEmpty()
)? Then I encountered this guideline from Microsoft where it says:
X DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.
The general rule is that null and empty (0 item) collections or arrays should be treated the same.
So, ideally you should never have a collection which is null if you follow this guideline from Microsoft. And that will help you to remove unnecessary null checking which ultimately will make your code more readable. In this case, someone just need to check : myList.Any()
to find out whether there is any element present in the list.
Hope this explanation will help someone who will face same problem in future and wondering why isn't there any such feature to check whether a collection is null or empty.
This answer worked for me:
pipeline {
agent any
stages {
stage("Run unit tests"){
steps {
script {
try {
sh '''
# Run unit tests without capturing stdout or logs, generates cobetura reports
cd ./python
nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
cd ..
'''
} finally {
junit 'nosetests.xml'
}
}
}
}
stage ('Speak') {
steps{
echo "Hello, CONDITIONAL"
}
}
}
}
Fixed it with -no-pie
option in linker stage:
g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...
You need to add an event, before call your handleFunction like this:
function SingInContainer() {
..
..
handleClose = () => {
}
return (
<SnackBar
open={open}
handleClose={() => handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
)
}
Just found out that with the Java NIO (java.nio.file.*
) you can easily write:
List<String> lines=Files.readAllLines(Paths.get("/tmp/test.csv"), StandardCharsets.UTF_8);
for(String line:lines){
System.out.println(line);
}
instead of dealing with FileInputStream
s and BufferedReader
s...
It is now much easier to do this in Eclipse now. Just right click on the package that will contain your new activity. New -> Other -> (Under Android tab) Android Activity.
And that's all. Your new activity is automatically added to the manifest file as well.
With some workaround I could find a simple way to find out whether there are files in a directory. This can extend with more with grep commands to check specifically .xml or .txt files etc. Ex : ls /some/dir | grep xml | wc -l | grep -w "0"
#!/bin/bash
if ([ $(ls /some/dir | wc -l | grep -w "0") ])
then
echo 'No files'
else
echo 'Found files'
fi
You need to group on the grade field. This query should give you what your looking for in pretty much any database.
Select Grade, CountofGrade / sum(CountofGrade) *100
from
(
Select Grade, Count(*) as CountofGrade
From Grades
Group By Grade) as sub
Group by Grade
You should specify the system you're using.
Click on "Tables" in "Connections" window, choose "Import data ...", follow the wizard and you will be asked for name for new table.
I've just encountered this problem and fixed it. I think the root cause of this problem is ng and current version of node.js (10.6.0) and accompanying npm are not in sync. I've installed the LTS version of node.js (8.11.3) and the problem disappeared.
Every printer is different but 0.25" (6.35 mm) is a safe bet.
Nice clean solution:
<?php
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="example.csv"');
header("Content-Length: " . filesize("example.csv"));
$fp = fopen("example.csv", "r");
fpassthru($fp);
fclose($fp);
?>
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
With my T7300 2.0GHz and Kingston V100 64gb SSD the results are
Bitlocker off ? on
Sequential read 243 MB/s ? 140 MB/s
Sequential write 74.5 MB/s ? 51 MB/s
Random read 176 MB/s ? 100 MB/s
Random write, and the 4KB speeds are almost identical.
Clearly the processor is the bottleneck in this case. In real life usage however boot time is about the same, cold launch of Opera 11.5 with 79 tabs remained the same 4 seconds all tabs loaded from cache.
A small build in VS2010 took 2 seconds in both situations. Larger build took 2 seconds vs 5 from before. These are ballpark because I'm looking at my watch hand.
I guess it all depends on the combination of processor, ram, and ssd vs hdd. In my case the processor has no hardware AES so compilation is worst case scenario, needing cycles for both assembly and crypto.
A newer system with Sandy Bridge would probably make better use of a Bitlocker enabled SDD in a development environment.
Personally I'm keeping Bitlocker enabled despite the performance hit because I travel often. It took less than an hour to toggle Bitlocker on/off so maybe you could just turn it on when you are traveling then disable it afterwards.
Thinkpad X61, Windows 7 SP1
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
if you can't see the chrome://flags
because everything is black, and you don't want to revert your graphic driver as @wilfo did, then you can run google-chrome --disable-gpu
from the console.
http://www.linuxquestions.org/questions/debian-26/chromium-doesn%27t-work-after-update-4175522748/
If your are using HTML5 then try following code snippet
<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
</script>
You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items()
. Then you have both directly in variables and don't need a lookup at all:
for key, value in PIX0.items():
NUM = input("What is the Resolution of %s?" % key)
if NUM == value:
You can of course use that both ways then.
Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.
You could simply check for the existence of an empty file, if it doesn't exist, then execute your code and create the file.
e.g.
if(File.Exists("emptyfile"){
//Your code here
File.Create("emptyfile");
}
If you're running Python 3.3 or better, you can use the clear()
method of list
, which is parallel to clear()
of dict
, set
, deque
and other mutable container types:
alist.clear() # removes all items from alist (equivalent to del alist[:])
As per the linked documentation page, the same can also be achieved with alist *= 0
.
To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):
alist.clear() # Python 3.3+
del alist[:]
alist[:] = []
alist *= 0
I made API sending data via form on website to prosperworks based on @Rocket Hazmat, @dbau and @maraca code. I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
Null is used in databases to represent "no record" or "no information". So you might have a bit field that describes "does this user want to be sent e-mails by us", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike.
The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false.
So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing).
Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());
Actually,,i found a simple answer,, Jst adding the object to String Builder instead of String worked ;)
StringBuilder jsonString= new StringBuilder.append("http://www.json-.com/j/cglqaRcMSW?=4");
JSON json= new JSON(jsonString.toString);
Actually got the same problem. For me worked this easy way:
Adding the data to a Datatable
and sort it:
dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();
Steps to resolve this issue 1.Right click on your project 2.Click on validate option
Result :TODO issue resolved
This doesn't seem to have <a> </a>
tags so selenium might not be able to detect it as a link.
You may try and use
driver.findElement(By.xpath("//*[@class='ng-binding']")).click();
if this is the only element in that page with this class .
This error can occur in Rstudio simply because your "Plots" pane is just barely too small. Try zooming your "Files, Plots, Packages, Help, Viewer" and see if it helps!
If you want to use 32-bit references, your heap is limited to 32 GB.
However, if you are willing to use 64-bit references, the size is likely to be limited by your OS, just as it is with 32-bit JVM. e.g. on Windows 32-bit this is 1.2 to 1.5 GB.
Note: you will want your JVM heap to fit into main memory, ideally inside one NUMA region. That's about 1 TB on the bigger machines. If your JVM spans NUMA regions the memory access and the GC in particular will take much longer. If your JVM heap start swapping it might take hours to GC, or even make your machine unusable as it thrashes the swap drive.
Note: You can access large direct memory and memory mapped sizes even if you use 32-bit references in your heap. i.e. use well above 32 GB.
Compressed oops in the Hotspot JVM
Compressed oops represent managed pointers (in many but not all places in the JVM) as 32-bit values which must be scaled by a factor of 8 and added to a 64-bit base address to find the object they refer to. This allows applications to address up to four billion objects (not bytes), or a heap size of up to about 32Gb. At the same time, data structure compactness is competitive with ILP32 mode.
You could try using something like:
sed -n 's/$/:80/' ips.txt > new-ips.txt
Provided that your file format is just as you have described in your question.
The s///
substitution command matches (finds) the end of each line in your file (using the $
character) and then appends (replaces) the :80
to the end of each line. The ips.txt
file is your input file... and new-ips.txt
is your newly-created file (the final result of your changes.)
Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:
sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt
So, for example, if your input file looked something like this (note the :80
):
127.0.0.1
128.0.0.0:80
121.121.33.111
The final result would look something like this:
127.0.0.1:80
128.0.0.0:80
121.121.33.111:80
Should I use JSTL ?
Yes.
You can use <c:if>
and <c:choose>
tags to make conditional rendering in jsp using JSTL.
To simulate if , you can use:
<c:if test="condition"></c:if>
To simulate if...else, you can use:
<c:choose>
<c:when test="${param.enter=='1'}">
pizza.
<br />
</c:when>
<c:otherwise>
pizzas.
<br />
</c:otherwise>
</c:choose>
IE can set username and password proxies, so maybe setting it there and import does work
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d name:port
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyUser /t REG_SZ /d username
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyPass /t REG_SZ /d password
netsh winhttp import proxy source=ie
FWIW this error can happen if you are not carful when adding your service reference to the application that is calling the https service
For example if you deleted your previous service reference that used to be http://example.com/Service.svc and then recreated it so it is now https://example.com/service.svc.
If you are not careful to delete the old client and binding in the web.config before recreating the service reference it will create BasicHttpBinding_IService1 instead of BasicHttpBinding_IService. Then when you deploy the application to the actual server it will say 'https is invalid expected http' because its looking for BasicHttpBinding_IService1 & not BasicHttpBinding_IService any longer.
Meanwhile you are trying all the suggestions above with no result.
Just thought I would throw that out there.
I think you should $_POST[][], i tried it and it work :)), tks
Here is how to get the value of all checked checkboxes as an array:
var values = (function() {
var a = [];
$(".checkboxes:checked").each(function() {
a.push(this.value);
});
return a;
})()
In the interface, you specify the property:
public interface IResourcePolicy
{
string Version { get; set; }
}
In the implementing class, you need to implement it:
public class ResourcePolicy : IResourcePolicy
{
public string Version { get; set; }
}
This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.
In the class, you actually implement them. The shortest way to do this is using this { get; set; }
syntax. The compiler will create a field and generate the getter and setter implementation for it.
You can create a generic style and re-use it on multiple textviews like the one below:
textView.setTextAppearance(this, R.style.MyTextStyle);
Edit: this refers to Context
Below 2 lines of code shows how to use Python List Comprehension to load 'java style' property file.
split_properties=[line.split("=") for line in open('/<path_to_property_file>)]
properties={key: value for key,value in split_properties }
Please have a look at below post for details https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/
64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).
For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.
Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime
I think that most fast way should not taking higher than O(n^2) also in this way you can use just O(1) space :
the way to do that is to swap in pairs because when you transpose a matrix then what you do is: M[i][j]=M[j][i] , so store M[i][j] in temp, then M[i][j]=M[j][i],and the last step : M[j][i]=temp. this could be done by one pass so it should take O(n^2)
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
Killing the process specified in the Dockerfile's CMD
/ ENTRYPOINT
works for me. (The container restarts automatically)
Rebooting was not allowed in my container, so I had to use this workaround.
If you're using system.js, you can use System.import()
at runtime:
export class MyAppComponent {
constructor(){
System.import('path/to/your/module').then(refToLoadedModule => {
refToLoadedModule.someFunction();
}
);
}
If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure
:
export class MyAppComponent {
constructor() {
require.ensure(['path/to/your/module'], require => {
let yourModule = require('path/to/your/module');
yourModule.someFunction();
});
}
}
You can also use a union construct. I'm not sure if CASE is a common SQL construct ...
SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION
SELECT IDParent FROM tabName WHERE IDParent>1
Thank you for posting this issue.
One resolution: open the package in XML form through windows explorer, locate the GUID for the connection manager that cant be found. In my case, it was a bonked EventHandler connection that was corrupted. This same connection manager was used in the control flow but somehow was not corrupted there, so it was not obvious to the user via the UI. Since the XML pointed to an event handler connection manager, I opened the event handler tab in the UI and it immediately displayed the wonderful RED X on the source and targets that were referencing the corrupted connection manager ID. I repointed it to the correct manager, rebuilt the pkg and saved. Good to go.
The key was opening the pkg in XML format and locating the GUID in the code to see where it was failing. If I was not able to find a valid reference to it in the UI, I was going to either rename the XML connection to another known GUID within the XML and then go into the UI and repoint it again, or delete it altogether.
Good luck.
Since this is a popular question, I will point out that java can also validate against "referred to" xsd's, for instance if the .xml file itself specifies XSD's in the header, using xsi:schemaLocation
or xsi:noNamespaceSchemaLocation
(or xsi for particular namespaces) ex:
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
...
or schemaLocation (always a list of namespace to xsd mappings)
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com/my_namespace http://www.example.com/document.xsd">
...
The other answers work here as well, because the .xsd files "map" to the namespaces declared in the .xml file, because they declare a namespace, and if matches up with the namespace in the .xml file, you're good. But sometimes it's convenient to be able to have a custom resolver...
From the javadocs: "If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:"
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema();
and this works for multiple namespaces, etc.
The problem with this approach is that the xmlsns:xsi
is probably a network location, so it'll by default go out and hit the network with each and every validation, not always optimal.
Here's an example that validates an XML file against any XSD's it references (even if it has to pull them from the network):
public static void verifyValidatesInternalXsd(String filename) throws Exception {
InputStream xmlStream = new new FileInputStream(filename);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(xmlStream));
xmlStream.close();
}
public static class RaiseOnErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
public void error(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
public void fatalError(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
}
You can avoid pulling referenced XSD's from the network, even though the xml files reference url's, by specifying the xsd manually (see some other answers here) or by using an "XML catalog" style resolver. Spring apparently also can intercept the URL requests to serve local files for validations. Or you can set your own via setResourceResolver, ex:
Source xmlFile = new StreamSource(xmlFileLocation);
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema();
Validator validator = schema.newValidator();
validator.setResourceResolver(new LSResourceResolver() {
@Override
public LSInput resolveResource(String type, String namespaceURI,
String publicId, String systemId, String baseURI) {
InputSource is = new InputSource(
getClass().getResourceAsStream(
"some_local_file_in_the_jar.xsd"));
// or lookup by URI, etc...
return new Input(is); // for class Input see
// https://stackoverflow.com/a/2342859/32453
}
});
validator.validate(xmlFile);
See also here for another tutorial.
I believe the default is to use DOM parsing, you can do something similar with SAX parser that is validating as well saxReader.setEntityResolver(your_resolver_here);
Unfortunately there is no way to add Tooltips for UDF Arguments.
To extend Remou's reply you can find a fuller but more complex approach to descriptions for the Function Wizard at
http://www.jkp-ads.com/Articles/RegisterUDF00.asp
Try CLPP library. It's simple and flexible library for command line parameters parsing. Header-only and cross-platform. Uses ISO C++ and Boost C++ libraries only. IMHO it is easier than Boost.Program_options.
Library: http://sourceforge.net/projects/clp-parser/
26 October 2010 - new release 2.0rc. Many bugs fixed, full refactoring of the source code, documentation, examples and comments have been corrected.
You can find your created database, named <your-database-name>
in
//data/data/<Your-Application-Package-Name>/databases/<your-database-name>
Pull it out using File explorer and rename it to have .db3 extension to use it in SQLiteExplorer
Use File explorer of DDMS to navigate to emulator directory.
It is wrong to have <input> as a direct child of a <form>
And by the way <input /> may fail on some doctype
Check it with http://validator.w3.org/check
document type does not allow element "INPUT" here; missing one of "P", "H1", "H2", "H3", "H4", "H5", "H6", "PRE", "DIV", "ADDRESS" start-tag
<input type="text" />
The mentioned element is not allowed to appear in the context in which you've placed it; the other mentioned elements are the only ones that are both allowed there and can contain the element mentioned. This might mean that you need a containing element, or possibly that you've forgotten to close a previous element.
One possible cause for this message is that you have attempted to put a block-level element (such as "<p>" or "<table>") inside an inline element (such as "<a>", "<span>", or "<font>").
android studio 4.1.1
applicationVariants.all { variant ->
variant.outputs.all { output ->
def reversion = "118"
def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
def versionName = defaultConfig.versionName
outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
}
}
I was trying to import numpy in python 3.2.1 on windows 7.
Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it
cd numpy-1.6
python setup.py install
but got an error with a statement as below
unable to find vcvarsall.bat
For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.
In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"
Installation went smoothly and now I am able to import numpy without using mingW.
Long story short try using windows installer for numpy, if one is available.
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
Detection ie9+
var userAgent, ieReg, ie;
userAgent = $window.navigator.userAgent;
ieReg = /msie|Trident.*rv[ :]*11\./gi;
ie = ieReg.test(userAgent);
if (ie) {
// js for ie9,10 and 11
}
You can use following :
<p id="p1">Some Text here </p>
#p1{
font-weight: bold;
}
OR
<Strong><p>Some text here </p></strong>
OR
You can use <h1> tag
which is somewhat similar to bold
In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.
Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts
There is also a builtin function execfile(filename) that will do what you want
Key input is a predefined event. You can catch events by attaching event_sequence
(s) to event_handle
(s) by using one or multiple of the existing binding methods(bind
, bind_class
, tag_bind
, bind_all
). In order to do that:
event_handle
methodevent_sequence
) that fits your case from an events listWhen an event happens, all of those binding methods implicitly calls the event_handle
method while passing an Event
object, which includes information about specifics of the event that happened, as the argument.
In order to detect the key input, one could first catch all the '<KeyPress>'
or '<KeyRelease>'
events and then find out the particular key used by making use of event.keysym
attribute.
Below is an example using bind
to catch both '<KeyPress>'
and '<KeyRelease>'
events on a particular widget(root
):
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
Also you can:
IMHO a little bit hidden and cumbersome...
You can use LINQ-to-DataSet
with Enumerable.Any
:
String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));
Another approach is to use DataTable.Select
:
DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}
Q: what if we do not know the columns Headers and we want to find if any cell value
PEPSI
exist in any rows'c columns? I can loop it all to find out but is there a better way? –
Yes, you can use this query:
DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
.Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
Ok, I think I got it to work now. I deleted every Newtonsoft.Json.dll on my machine that wasn't the latest version that I could find, made sure I had the latest version in NuGet, and build it and made sure that was the latest one in the bin folder, and I left the changes in the web.config and the .csproj. Now I'm on to another error, so it must be working..
Basic rule says that :
For Entities with generated identifier :
save() : It returns an entity's identifier immediately in addition to making the object persistent. So an insert query is fired immediately.
persist() : It returns the persistent object. It does not have any compulsion of returning the identifier immediately so it does not guarantee that insert will be fired immediately. It may fire an insert immediately but it is not guaranteed. In some cases, the query may be fired immediately while in others it may be fired at session flush time.
For Entities with assigned identifier :
save(): It returns an entity's identifier immediately. Since the identifier is already assigned to entity before calling save, so insert is not fired immediately. It is fired at session flush time.
persist() : same as save. It also fire insert at flush time.
Suppose we have an entity which uses a generated identifier as follows :
@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
@Column(name = "USER_NAME")
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
save() :
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = new UserDetails();
user.setUserName("Gaurav");
session.save(user); // Query is fired immediately as this statement is executed.
session.getTransaction().commit();
session.close();
persist() :
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = new UserDetails();
user.setUserName("Gaurav");
session.persist(user); // Query is not guaranteed to be fired immediately. It may get fired here.
session.getTransaction().commit(); // If it not executed in last statement then It is fired here.
session.close();
Now suppose we have the same entity defined as follows without the id field having generated annotation i.e. ID will be assigned manually.
@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
@Id
@Column(name = "USER_ID")
private int userId;
@Column(name = "USER_NAME")
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
for save() :
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Gaurav");
session.save(user); // Query is not fired here since id for object being referred by user is already available. No query need to be fired to find it. Data for user now available in first level cache but not in db.
session.getTransaction().commit();// Query will be fired at this point and data for user will now also be available in DB
session.close();
for persist() :
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Gaurav");
session.persist(user); // Query is not fired here.Object is made persistent. Data for user now available in first level cache but not in db.
session.getTransaction().commit();// Query will be fired at this point and data for user will now also be available in DB
session.close();
The above cases were true when the save or persist were called from within a transaction.
The other points of difference between save and persist are :
save() can be called outside a transaction. If assigned identifier is used then since id is already available, so no insert query is immediately fired. The query is only fired when the session is flushed.
If generated identifier is used , then since id need to generated, insert is immediately fired. But it only saves the primary entity. If the entity has some cascaded entities then those will not be saved in db at this point. They will be saved when the session is flushed.
If persist() is outside a transaction then insert is fired only when session is flushed no matter what kind of identifier (generated or assigned) is used.
If save is called over a persistent object, then the entity is saved using update query.
Try this:
Remove the constraint DF_Movies_Rating__48CFD27E before changing your field type.
The constraint is typically created automatically by the DBMS (SQL Server).
To see the constraint associated with the table, expand the table attributes in Object explorer, followed by the category Constraints as shown below:
You must remove the constraint before changing the field type.
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.
As noted in the comments, when you loop over a list with something like for member in my_list
the member
variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:
my_list = [1,2,3]
for member in my_list:
member = 42
print my_list
Output:
[1, 2, 3]
If you want to change a list containing immutable types, you need to do something like:
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
Output:
[43, 44, 45]
If your list contains mutable objects, you can modify the current member
object directly:
class C:
def __init__(self, n):
self.num = n
def __repr__(self):
return str(self.num)
my_list = [C(i) for i in xrange(3)]
for member in my_list:
member.num += 42
print my_list
[42, 43, 44]
Note that you are still not changing the list, simply modifying the objects in the list.
You might benefit from reading Naming and Binding.
There is only so much you can do with rm() and gc(). As suggested by Gavin Simpson, even if you free the actual memory in R, Windows often won't reclaim it until you close R or it is needed because all the apparent Windows memory fills up.
This usually isn't a problem. However, if you are running large loops this can sometimes lead to fragmented memory in the long term, such that even if you free the memory and restart R - the fragmented memory may prevent you allocating large chunks of memory. Especially if other applications were allocated fragmented memory while you were running R. rm() and gc() may delay the inevitable, but more RAM is better.
Your server may read a different my.cnf
than the one you're editing (unless you specified it when starting mysqld).
From the MySQL Certification Study Guide:
The search order includes two general option files,
/etc/my.cnf
and$MYSQL_HOME/my.cnf
. The second file is used only if theMYSQL_HOME
environment variable is set. Typically, you seet it to the MySQL installation directory. (The mysqld_safe script attempts to setMYSQL_HOME
if it is not set before starting the server.) The option file search order also includes~/.my.cnf
(that is the home directory). This isn't an especially suitable location for server options. (Normally, you invoke the server asmysql
, or asroot
with a--user=mysql
option. The user-specific file read by the server would depend on which login account you invoke it from, possibly leading to inconsistent sets of options being used.)
Another possibility is of course, that your sql-mode
option gets overwritten further down in the same file. Multiple options have to be separated by ,
in the same line.
P.S.: And you need the quotes, IIRC. Now that you've tried it without quotes, I'm pretty sure, you're editing the wrong file, since MySQL doesn't start when there's an error in the option file.
P.P.S.: Had a look at my config files again, there it's
[mysqld]
sql_mode = "NO_ENGINE_SUBSTITUTION"
and it's working.
If you set id in your database to be primary key and autoincrement, then this line of code is wrong:
user.setId(1);
Try with this:
public static void main(String[] args){
UserBean user = new UserBean();
user.setUserName("name1");
user.setPassword("passwd1");
em.persist(user);
}
You want to keep the selector, so adding/removing it won't work. Instead of writing a hard and fast CSS selectors (or two), perhaps you can just use the original selector to apply new CSS rule to that element based on some criterion:
$(".test").hover(
if(some evaluation) {
$(this).css('border':0);
}
);
For a []string
, you can use strings.Join()
:
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
TextView
comes with 4 compound drawables, one for each of left, top, right and bottom.
In your case, you do not need the LinearLayout
and ImageView
at all. Just add android:drawableLeft="@drawable/up_count_big"
to your TextView
.
See TextView#setCompoundDrawablesWithIntrinsicBounds for more info.
An unquoted asterisk *
will be interpreted as a pattern (glob) by the shell. The shell will use it in pathname expansion. It will then generate a list of filenames that match the pattern.
A simple asterisk will match all filenames in the PWD (present working directory). A more complex pattern as */
will match all filenames that end in /
. Thus, all directories. That is why the command:
echo */
echo ./*/ ### Avoid misinterpreting filenames like "-e dir"
will be expanded (by the shell) to echo
all directories in the PWD.
To test this: Create a directory (mkdir
) named like test-dir, and cd
into it:
mkdir test-dir; cd test-dir
Create some directories:
mkdir {cs,files,masters,draft,static} # Safe directories.
mkdir {*,-,--,-v\ var,-h,-n,dir\ with\ spaces} # Some a bit less secure.
touch -- 'file with spaces' '-a' '-l' 'filename' # And some files:
The command echo ./*/
will remain reliable even with odd named files:
./--/ ./-/ ./*/ ./cs/ ./dir with spaces/ ./draft/ ./files/ ./-h/
./masters/ ./-n/ ./static/ ./-v var/
But the spaces in filenames make reading a bit confusing.
If instead of echo
, we use ls
. The shell is still what is expanding the list of filenames. The shell is the reason to get a list of directories in the PWD. The -d
option to ls
makes it list the present directory entry instead of the contents of each directory (as presented by default).
ls -d */
However, this command is (somewhat) less reliable. It will fail with the odd named files listed above. It will choke with several names. You need to erase one by one till you find the ones with problems.
The GNU ls
will accept the "end of options" (--
) key.
ls -d ./*/ ### More reliable BSD ls
ls -d -- */ ### More reliable GNU ls
To list each directory in its own line (in one column, similar to ls -1), use:
$ printf "%s\n" */ ### Correct even with "-", spaces or newlines.
And, even better, we could remove the trailing /
:
$ set -- */; printf "%s\n" "${@%/}" ### Correct with spaces and newlines.
An attempt like
$ for i in $(ls -d */); do echo ${i%%/}; done
will fail on:
ls -d */
) as already shown above.IFS
.IFS
).Finally, using the argument list inside a function will not affect the arguments list of the present running shell. Simply
$ listdirs(){ set -- */; printf "%s\n" "${@%/}"; }
$ listdirs
presents this list:
--
-
*
cs
dir with spaces
draft
files
-h
masters
-n
static
-v var
These options are safe with several types of odd filenames.
First thing I should have noticed is that charAt
is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt
method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.
http://sitename.com/virtual_folder_name/filename.fileextension
By the way, this also works with Chrome that otherwise does not accept the file-protocol file://
Hope this helps someone :)
string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274
Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.
Function
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
var data = [1, 2, 3, 4];
print_r(data);
Firebase stores a sequence of values in this format:
"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"
If that is how you have them, you are getting the wrong type. The above structure is represented as a Map
, not as a List
:
mFirebaseRef = new Firebase(FIREBASE_URL);
mFirebaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = td.values();
//notifyDataSetChanged();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
It's quite a common error with a variety of causes: start here with KB 811889