tul,
.getClass().getResource(fileName)
it considers the
location of the fileName is the same location of the of the calling
class..getClass().getClassLoader().getResource(fileName)
it
considers the location of the fileName is the root - in other words
bin
folder.Source :
package Sound;
public class ResourceTest {
public static void main(String[] args) {
String fileName = "Kalimba.mp3";
System.out.println(fileName);
System.out.println(new ResourceTest().getClass().getResource(fileName));
System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
}
}
Output :
Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3
for unhashable lists. It is faster as it does not iterate about already checked entries.
def purge_dublicates(X):
unique_X = []
for i, row in enumerate(X):
if row not in X[i + 1:]:
unique_X.append(row)
return unique_X
If you want to hide the keyboard at the start of the activity. Then mention
android:windowSoftInputMode="stateHidden"
To that activity in the manifest file. Problem gets solved.
Cheers.
try
double myPrice = 123.0;
String.Format(((Math.Round(myPrice) == myPrice) ? "{0:0}" : "{0:0.00}"), myPrice);
If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.
If you are executing using gradle wrapper, you can run the command with JDK path like following
./gradlew -Dorg.gradle.java.home=/jdk_path_directory
The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.
Yes, Object.create
builds an object that inherits directly from the one passed as its first argument.
With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:
var o = new SomeConstructor();
In the above example, o
inherits directly from SomeConstructor.prototype
.
There's a difference here, with Object.create
you can create an object that doesn't inherit from anything, Object.create(null);
, on the other hand, if you set SomeConstructor.prototype = null;
the newly created object will inherit from Object.prototype
.
You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.
Well, you can create closures, e.g. using property descriptors argument:
var o = Object.create({inherited: 1}, {
foo: {
get: (function () { // a closure
var closured = 'foo';
return function () {
return closured+'bar';
};
})()
}
});
o.foo; // "foobar"
Note that I'm talking about the ECMAScript 5th Edition Object.create
method, not the Crockford's shim.
The method is starting to be natively implemented on latest browsers, check this compatibility table.
Ping can be used with a variety of protocols. The protocol value can be appletalk, clns, ip (the default), novell, apollo, vines, decnet, or xns. Some protocols require another Cisco router at the remote end to answer ping packets. ... (Cisco field manual: router configuration, By Dave Hucaby, Steve McQuerry. Page 64)
... For IP. ping uses ICMP type 8 requests and ICMP type 0 replies. The traceroute (by using UDP) command can be used to discover the routers along the path that packets are taking to a destination. ... (Page 63)
Following solution could have problems with clustered indexes involved as mentioned here. Thanks to Martin for pointing this out.
The answer is kept to educate those (like me) who don't know all side-effects or ins and outs of SQL Server.
Expanding on the answer gaven by Quassnoi in your link, following works
DECLARE @Test TABLE (Number INTEGER, AText VARCHAR(2), ID INTEGER)
DECLARE @Number INT
INSERT INTO @Test VALUES (1, 'A', 1)
INSERT INTO @Test VALUES (2, 'B', 2)
INSERT INTO @Test VALUES (1, 'E', 5)
INSERT INTO @Test VALUES (3, 'C', 3)
INSERT INTO @Test VALUES (2, 'D', 4)
SET @Number = 0
;WITH q AS (
SELECT TOP 1000000 *
FROM @Test
ORDER BY
ID
)
UPDATE q
SET @Number = Number = @Number + 1
check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.
Possibly an easier way?
Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.
justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5
Use sort.
justPrices.sort();
It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.
justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9
You can then easily grab by the first index.
justPrices[0]
I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp
var dataArray = [];
var obj = jQuery.parseJSON(yourInput);
$.each(obj, function (index, value) {
dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});
this helps me a lot :-)
It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.
In swift 4
let Totalname = "10.0" //Now it is in string
let floatVal = (Totalname as NSString).floatValue //Now converted to float
If you only want the image of your figure to appear larger without changing the general appearance of your figure increase the figure resolution. Changing the figure size as suggested in most other answers will change the appearance since font sizes do not scale accordingly.
import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200
Click File > Preferences > Keyboard Shortcuts:
Search for copyLinesDownAction
or copyLinesUpAction
in your keyboard shortcuts
Usually it is SHIFT+ALT + ?
Update for Ubuntu:
It seems that Ubuntu is hiding that shortcut from being seen by VSCode (i.e. it uses it probably by its own). There is an issue about that on GitHub.
In order to work in Ubuntu you will have to define your own shortcut, e.g. to copy the line using ctrl+shift+alt+j and CTRL +SHIFT + ALT + k you could use a keybindings.json
like this:
[
{ "key": "ctrl+shift+alt+j", "command": "editor.action.copyLinesDownAction",
"when": "editorTextFocus && !editorReadonly" },
{ "key": "ctrl+shift+alt+k", "command": "editor.action.copyLinesUpAction",
"when": "editorTextFocus && !editorReadonly" }
]
Thanks to the talk with Sarfraz we could figure out the solution.
The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities
table and filter correct entries).
So, instead of:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex]
};
it should be:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex].value
};
Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
If you're using IIS Express, it creates a new configuration for each site that you run, and it's bound to the url (host/port). However, when it opens a new project using the same port it doesn't refresh the configuration.
This means that if you have a project using CLR 2.0 (.NET Framework 2.0 to 3.5) running on some port and then later you open another project in the same port using CLR 4 (.NET Framework 4.x+) the new project will try to run using CLR 2, which fails - and in case it doesn't even recognize the "targetFramework" attribute.
One solution is cleaning IIS Express sites, but the easiest method is changing the port so that IIS Express will create a new site (using CLR 4) for your project.
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".
Use This function to set all Type of margins
public void setViewMargins(Context con, ViewGroup.LayoutParams params,
int left, int top , int right, int bottom, View view) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel_left = (int) (left * scale + 0.5f);
int pixel_top = (int) (top * scale + 0.5f);
int pixel_right = (int) (right * scale + 0.5f);
int pixel_bottom = (int) (bottom * scale + 0.5f);
ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);
view.setLayoutParams(params);
}
If you want to have a completely locked down area of your webapplication which can only be accessed by administrators from your company, then SSL authorization maybe for you. It will insure that no one can make a connection to the server instance unless they have an authorized certificate installed in their browser. Last week I wrote an article on how to setup the server: Article
This is one of the most secure setups you will find as there are no username/passwords involved so no one can gain access unless one of your users hands the key files to a potential hacker.
I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.
It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.
Here's an example to show the usage for encrypting strings:
NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user
NSLog( @"Original String: %@", plainString );
NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );
NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );
Get the full source code here:
Thanks for all the helpful hints!
-- Michael
# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
By putting an assignment of list on a variable first
myVar <- list()
it opens the possibility of hiearchial assignments by
myVar[[1]] <- list()
myVar[[2]] <- list()
and so on... so now it's possible to do
myVar[[1]][[1]] <- c(...)
myVar[[1]][[2]] <- c(...)
myVar[[1]][['subVar']] <- c(...)
and so on
it is also possible to assign directly names (instead of $)
myVar[['nameofsubvar]] <- list()
and then
myVar[['nameofsubvar]][['nameofsubsubvar']] <- c('...')
important to remember is to always use double brackets to make the system work
then to get information is simple
myVar$nameofsubvar$nameofsubsubvar
and so on...
example:
a <-list()
a[['test']] <-list()
a[['test']][['subtest']] <- c(1,2,3)
a
$test
$test$subtest
[1] 1 2 3
a[['test']][['sub2test']] <- c(3,4,5)
a
$test
$test$subtest
[1] 1 2 3
$test$sub2test
[1] 3 4 5
a nice feature of the R language in it's hiearchial definition...
I used it for a complex implementation (with more than two levels) and it works!
table tr td:nth-child(2) {
background: #ccc;
}
Working example: http://jsfiddle.net/gqr3J/
Maven is one of the tools where you need to actually decide up front that you like it and want to use it, since you will spend quite some time learning it, and having made said decision once and for all will allow you to skip all kinds of doubt while learning (because you like it and want to use it)!
The strong conventions help in many places - like Hudson that can do wonders with Maven projects - but it may be hard to see initially.
edit: As of 2016 Maven is the only Java build tool where all three major IDEs can use the sources out of the box. In other words, using maven makes your build IDE-agnostic. This allows for e.g. using Netbeans profiling even if you normally work In eclipse
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
Try something like this:
<div id="LoadingImage" style="display: none">
<img src="" />
</div>
<script>
function ajaxCall(){
$("#LoadingImage").show();
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
$("#LoadingImage").hide();
alert("Success");
},
error: function (xhr, status) {
$("#LoadingImage").hide();
alert('Unknown error ' + status);
}
});
}
</script>
To add to all the wonderful answers here
First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.
For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.
So, basically we want to know how much accurately can the number be stored and is what we call precision.
Quoting @Alessandro here
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part
So, float can store double the amount of fractional part. That is why Double is called double the float
SUPER-SHIFT-p > File: Revert File
is the only way
(where SUPER
is Command
on Mac and Ctrl
on PC)
return Deal::with(["redeem" => function($q){
$q->where('user_id', '=', 1);
}])->get();
this worked for me
You don't need regex to split a string on whitespace:
In [1]: text = '''WYATT - Ranked # 855 with 0.006 %
...: XAVIER - Ranked # 587 with 0.013 %
...: YONG - Ranked # 921 with 0.006 %
...: YOUNG - Ranked # 807 with 0.007 %'''
In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
Have you tried just using the mysql
command line client directly?
mysql -u username -p -h hostname databasename < dump.sql
If you can't do that, there are any number of utilities you can find by Googling that help you import a large dump into MySQL, like BigDump
You asked for differences, but you can’t quite compare those two.
Note that <meta http-equiv="content-language" content="es">
is obsolete and removed in HTML5. It was used to specify “a document-wide default language”, with its http-equiv
attribute making it a pragma directive (which simulates an HTTP response header like Content-Language
that hasn’t been sent from the server, since it cannot override a real one).
Regarding <meta name="language" content="Spanish">
, you hardly find any reliable information. It’s non-standard and was probably invented as a SEO makeshift.
However, the HTML5 W3C Recommendation encourages authors to use the lang
attribute on html
root elements (attribute values must be valid BCP 47 language tags):
<!DOCTYPE html>
<html lang="es-ES">
<head>
…
Anyway, if you want to specify the content language to instruct search engine robots, you should consider this quote from Google Search Console Help on multilingual sites:
Google uses only the visible content of your page to determine its language. We don’t use any code-level language information such as
lang
attributes.
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Hope it helps.
Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn't ask for this.
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
Much confusion stems from the existence of at least three major libraries named bootstrap-datepicker:
If you're starting a new project - or heck, even if you're taking over an old project using the eyecon version - I recommend that you use eternicode's version, not eyecon's. The original eyecon version is outright inferior in terms of both functionality and documentation, and this is unlikely to change - it has not been updated since March 2013.
You can see most of the capabilities of the eternicode datepicker on the demo page which lets you play with the datepicker's configuration and observe the results. For more detail, see the succinct but comprehensive documentation, which you can probably consume in its entirety in under an hour.
In case you're impatient, though, here's a very short step-by-step guide to the simplest and most common use case for the datepicker.
Put an input
element on your page somewhere, e.g.
<input id="my-date-input">
With jQuery, select your input and call the .datepicker()
method:
jQuery('#my-date-input').datepicker();
Load your page and click on or tab into your input
element. A datepicker will appear:
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
Came across this and thought I would point out that for MVC 5 all you need to do is set the value on the model. For Example:
Model:
public class ExampleModel
{
public PackingListInputModel()
{
RadioButtonField = "One";
}
public string RadioButtonField { get; set; }
}
View :
@model ExampleModel
@using (Html.BeginForm)
{
@Html.RadioButtonFor(m => m.RadioButtonField , "One")
@Html.RadioButtonFor(m => m.RadioButtonField , "Two")
}
The state of the first radio button ("One") will be set as active because the value matches what was set in the model.
for HTML5
The value must be unique amongst all the IDs in the element’s home subtree and must contain at least one character. The value must not contain any space characters.
At least one character, no spaces.
This opens the door for valid use cases such as using accented characters. It also gives us plenty of more ammo to shoot ourselves in the foot with, since you can now use id values that will cause problems with both CSS and JavaScript unless you’re really careful.
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...
Per manual, you don't necessary want to use -password
option.
Let's say mykey.key
has a password and your want to protect iphone-dev.p12
with another password, this is what you'd use:
pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev
Have fun scripting!!
You can read multiple variables from file like this:
for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H
where param.txt:
PARAM1=value1
PARAM2=value2
...
grep -R "string" /directory/
-R follows also symlinks when -r does not.
Happened to me once, when I had unchecked "Run > Build automatically" and forgot to re-check it.
Just as an addition: This way you can access properties with names that would be otherwise unusable
$x = new StdClass;$prop = 'a b'; $x->$prop = 1; $x->{'x y'} = 2; var_dump($x);
object(stdClass)#1 (2) { ["a b"]=> int(1) ["x y"]=> int(2) }(not that you should, but in case you have to).
You can make a text align to the right inside of any element, including labels.
Html:
<label>Text</label>
Css:
label {display:block; width:x; height:y; text-align:right;}
This way, you give a width and height to your label and make any text inside of it align to the right.
This doesn't really justify your text but
android:gravity="center_horizontal"
is the best choice you have.
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
A PHP Based Solution for search entire table ! Search string is $string . This is generic and will work with all the tables with any number of fields
$sql="SELECT * from client_wireless";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' OR ";
}
// start the search in all the fields and when a match is found, go on printing it .
$sql="SELECT * from client_wireless ".$logicStr;
//echo $sql;
$query=mysql_query($sql);
You are all trying to overcomplicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,
var IE_version=(-1/*@cc_on,@_jscript_version@*/);
Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it
Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:
var IE_version=(-1/*@cc_on,@_jscript_version@*/);_x000D_
if (IE_version!==-1){_x000D_
document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");_x000D_
} else {_x000D_
document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");_x000D_
}
_x000D_
I think this should help you. I have written the below program in C.
# include <stdio.h>
int main()
{
int i, j;
printf("\nEnter Two Integers i and j...");
scanf("%d %d", &i, &j);
int Round_Off=i+j-i%j;
printf("The Rounded Off Integer Is...%d\n", Round_Off);
return 0;
}
This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.
var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
Arguments = Path.GetFileName(path),
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(path),
FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
Verb = "OPEN"
};
Process.Start(pi)
Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.
Here is how I would do it using vanilla JS
<form id="myform" method="POST" action="xxx">
<!-- your stuff here -->
<a href="javascript:void()" onclick="document.getElementById('myform').submit();>Ponies await!</a>
</form>
You can play with the return false
s and href="#"
vs void and whatever you need to but this method worked for me in Chrome 18, IE 9 and Firefox 14 and the rest depends on your javascript mostly.
You didn't mention what output format you need but reportlab is good at creating charts both in pdf and bitmap (e.g. png) format.
Here is a simple example of a barchart in png and pdf format:
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
d = Drawing(300, 200)
chart = VerticalBarChart()
chart.width = 260
chart.height = 160
chart.x = 20
chart.y = 20
chart.data = [[1,2], [3,4]]
chart.categoryAxis.categoryNames = ['foo', 'bar']
chart.valueAxis.valueMin = 0
d.add(chart)
d.save(fnRoot='test', formats=['png', 'pdf'])
alt text http://i40.tinypic.com/2j677tl.jpg
Note: the image has been converted to jpg by the image host.
I got this error too. I figured out that my version of PHP didn't have openssl compiled in, so simply adding the extension directive to php.ini wasn't enough. I don't know how you have to solve this in your particular case, but for me, I use macports, and the command was just:
sudo port install php5-openssl
You can try as follows it works for me.
Start server:
sudo service mysql start
Now, Go to sock folder:
cd /var/run
Back up the sock:
sudo cp -rp ./mysqld ./mysqld.bak
Stop server:
sudo service mysql stop
Restore the sock:
sudo mv ./mysqld.bak ./mysqld
Start mysqld_safe:
sudo mysqld_safe --skip-grant-tables --skip-networking &
Init mysql shell:
mysql -u root
Change password:
Hence, First choose the database
mysql> use mysql;
Now enter below two queries:
mysql> update user set authentication_string=password('123456') where user='root';
mysql> update user set plugin="mysql_native_password" where User='root';
Now, everything will be ok.
mysql> flush privileges;
mysql> quit;
For checking:
mysql -u root -p
done!
N.B, After login please change the password again from phpmyadmin
Now check hostname/phpmyadmin
Username: root
Password: 123456
For more details please check How to reset forgotten password phpmyadmin in Ubuntu
Mostly 301 vs 302 is important for indexing in search engines, as their crawlers take this into account and transfer PageRank when using 301.
See Peter Lee's answer for more details.
When you include jQuery the first time:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
The second script plugs itself into jQuery, and "adds" $(...).datepicker
.
But then you are including jQuery once again:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
It undoes the plugging in and therefore $(...).datepicker
becomes undefined.
Although the first $(document).ready
block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...)
(window.$
to be precise) is referring to the most recently loaded jQuery.
You would not run into this if you called $('.dateinput').datepicker
immediately rather than in $(document).ready
callback, but then you'd need to make sure that the target element (with class dateinput
) is already in the document before the script, and it's generally advised to use the ready
callback.
If you want to use datepicker
from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.
Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.
Use this as a template
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS
<@Table_Variable_Name, sysname, @Table_Var> TABLE
(
-- Add the column definitions for the TABLE variable here
<Column_1, sysname, c1> <Data_Type_For_Column1, , int>,
<Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
RETURN
END
GO
That will define your function. Then you would just use it as any other table:
Select * from MyFunction(Param1, Param2, etc.)
vim
!)for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items
to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems
.
In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems'
error. Use items()
instead of iteritems()
here.
Refer to this post.
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
Use SharedPreferences, http://developer.android.com/reference/android/content/SharedPreferences.html
Here's a sample: http://developer.android.com/guide/topics/data/data-storage.html#pref
If the data structure is more complex or the data is large, use an Sqlite database; but for small amount of data and with a very simple data structure, I'd say, SharedPrefs will do and a DB might be overhead.
You can add custom colors using bootstrap theming in your config file for example variables.scss
and make sure you import that file before bootstrap when compiling.
$theme-colors: (
"whatever": #900
);
Now you can do .btn-whatever
Copy/Paste what is below into your code:
SqlConnection cnTrupp = new SqlConnection("Initial Catalog = Database;Data Source = localhost;Persist Security Info=True;Integrated Security = True;");
Keep in mind that this solution uses your windows account to log in.
As John and Adam have said, this has to do with how you are logging in (or not logging in). Look at the link John provided to get a better explanation.
public class QueueUsingStacks<T>
{
private LinkedListStack<T> stack1;
private LinkedListStack<T> stack2;
public QueueUsingStacks()
{
stack1=new LinkedListStack<T>();
stack2 = new LinkedListStack<T>();
}
public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )
{
while(source.Head!=null)
{
dest.Push(source.Head.Data);
source.Head = source.Head.Next;
}
}
public void Enqueue(T entry)
{
stack1.Push(entry);
}
public T Dequeue()
{
T obj;
if (stack2 != null)
{
Copy(stack1, stack2);
obj = stack2.Pop();
Copy(stack2, stack1);
}
else
{
throw new Exception("Stack is empty");
}
return obj;
}
public void Display()
{
stack1.Display();
}
}
For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack
Python itself comes with an editor that you can access from the IDLE File > New File menu option.
Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.
Note: it's just been the easiest and most straightforward way for me so far.
With Lodash you can create a template and you can do that following way:
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table id="tblEntAttributes" class="table">
<tbody>
<tr>
<td>
chkboxId
</td>
<td>
chkboxValue
</td>
<td>
displayName
</td>
<td>
logicalName
</td>
<td>
dataType
</td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" id="test">appendTo</button>
</div>
</div>
</div>
And here goes the javascript:
var count = 1;
window.addEventListener('load', function () {
var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
document.getElementById('test').addEventListener('click', function (e) {
var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
var tableRowData = compiledRow(ajaxData);
$("#tblEntAttributes tbody").append(tableRowData);
count++;
});
});
Here it is in jsbin
A Simple solution :
Create a drawable file as edittext_stroke.xml in drawable folder. Add the below code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line"
>
<stroke
android:width="1dp"
android:color="@android:color/white" >
</stroke>
</shape>
In layout file , add the drawable to edittext as
android:drawableBottom="@drawable/edittext_stroke"
<EditText
android:textColor="@android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableBottom="@drawable/edittext_stroke"
/>
When importing a GWT project in Eclipse without installing "Google Plugin for Eclipse", this will occur. After installing "Google Plugin for Eclipse", this error will disappear.
This algorithm is not optimal for winning the game, but it is fairly optimal in terms of performance and amount of code needed:
if(can move neither right, up or down)
direction = left
else
{
do
{
direction = random from (right, down, up)
}
while(can not move in "direction")
}
I fixed it in Github Desktop Application by pushing my changes.
( SELECT * FROM table1
EXCEPT
SELECT * FROM table2)
UNION ALL
( SELECT * FROM table2
EXCEPT
SELECT * FROM table1)
Functionally, they are equivalent.
Performance-wise map[key] = value
would be quicker, as you are only making single lookup instead of two.
Style-wise, the shorter the better :)
The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.
There are already useful answers to this question above, however there is one more possibility which I don't see being addressed here.
We should consider that the java is installed correctly (that's why eclipse could have been launched in the first place), and the JDK is also added correctly to the eclipse. So the issue might be for some reason (e.g. migration of eclipse to another OS) the path for javadoc is not right which you can easily check and modify in the javadoc wizard page. Here is detailed instructions:
Project->Generate Javadoc...
javadoc command
path is correct as illustrated in below screenshot:I just use
git remote update
git status
The latter then reports how many commits behind my local is (if any).
Then
git pull origin master
to bring my local up to date :)
Yes, a static class
for storing constants would be just fine, except for constants that are related to specific types.
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
You can try Context.getApplicationInfo().dataDir
if you want the package's persistent data folder.
getFilesDir()
returns a subroot of this.
do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as
Use get_text(), it returns all the text in a document or beneath a tag, as a single Unicode string.
For instance, remove all different script tags from the following text:
<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>
The expected result is:
Signal et Communication
Ingénierie Réseaux et Télécommunications
Here is the source code:
#!/usr/bin/env python3
from bs4 import BeautifulSoup
text = '''
<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>
'''
soup = BeautifulSoup(text)
print(soup.get_text())
Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.
If you don't believe me look at the String.Concat
definition using reflector.
The last lines are...
int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;
As you can see the FastAllocateString
returns an empty but allocated string and then it is modified by FillStringChecked
Actually the FastAllocateString
is an extern method and the FillStringChecked
is unsafe so it uses pointers to copy the bytes.
Maybe there are better examples but this is the one I have found so far.
the command: sudo update-alternatives --config java
will find the complete path of all installed Java versions
I don't agree with the accepted answer that the lack of electron prevents VSC on Android.
Electron is really the desktop equivelent of projects like Apache Cordova or Adobe PhoneGap (but Electron is much less efficient and will presumably give way to solutions much closer to Cordova/PhoneGap when possible - it is already being worked on eg. here.)
API's would need to be mapped from their electron equivelents, and many of the plug-ins will have their own issues (but Android is reasonably flexible about allowing stuff like Python compared to iOS) so it is doable.
On the other hand, the demand for an Android version of VSC probably comes from people using the new Chromebooks that support Android, and there is already a solution for ChromeOS using crouton, available here.
Without a real example, it is difficult to make a recommendation. However, I've never needed to use that many WHERE clauses in a query and it may indicate a problem with the structure of your data.
It may be helpful for you to learn about data normalization: http://en.wikipedia.org/wiki/Third_normal_form
And for my fellow Europeans, try using this:
timestamp=$(date +%d-%m-%Y_%H-%M-%S)
will give a format of the format: "15-02-2020_19-21-58"
You call the variable and get the string representation like this
$timestamp
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
An absolute xpath in HTML DOM starts with /html e.g.
/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.
.//*[@id='answers']/h2[1]/a[1]
You can use firepath (firebug) for generating both types of xpaths
It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)
Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element
I would query the information_schema - this has views that are much more readable than the underlying tables.
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%create%'
For Windows and MacOS, Simply install it with pip
pip install -U wxPython
Reference: Official site
I use this script. If you change your XML Comments to display as black text on a yellow background you get the effect of highlighting the text you're looking for in the xml column of the results. (Tools -> Options -> Environment -> Fonts and Colors [Display items: XML Comment]
---------------------------------------------
-------------- Start FINDTEXT ----------
---------------------------------------------
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
GO
DECLARE @SearchString VARCHAR(MAX)
SET @SearchString = 'the text you''re looking for'
DECLARE @OverrideSearchStringWith VARCHAR(MAX)
--#############################################################################
-- Use Escape chars in Brackets [] like [%] to find percent char.
--#############################################################################
DECLARE @ReturnLen INT
SET @ReturnLen = 50;
with lastrun
as (select DEPS.OBJECT_ID
,MAX(last_execution_time) as LastRun
from sys.dm_exec_procedure_stats DEPS
group by deps.object_id
)
SELECT OL.Type
,OBJECT_NAME(OL.Obj_ID) AS 'Name'
,LTRIM(RTRIM(REPLACE(SUBSTRING(REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), ''), CHARINDEX(@SearchString, OBJECT_DEFINITION(OL.Obj_ID)) - @ReturnLen, @ReturnLen * 2), @SearchString, ' ***-->>' + @SearchString + '<<--*** '))) AS SourceLine
,CAST(REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(MAX), REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), '')), '&', '(A M P)'), '<', '(L T)'), '>', '(G T)'), @SearchString, '<!-->' + @SearchString + '<-->') AS XML) AS 'Hilight Search'
,(SELECT [processing-instruction(A)] = REPLACE(OBJECT_DEFINITION(OL.Obj_ID), NCHAR(0x001F), '')
FOR
XML PATH('')
,TYPE
) AS 'code'
,Modded AS Modified
,LastRun as LastRun
FROM (SELECT CASE P.type
WHEN 'P' THEN 'Proc'
WHEN 'V' THEN 'View'
WHEN 'TR' THEN 'Trig'
ELSE 'Func'
END AS 'Type'
,P.OBJECT_ID AS OBJ_id
,P.modify_Date AS modded
,LastRun.LastRun
FROM sys.Objects P WITH (NOLOCK)
LEFT join lastrun on P.object_id = lastrun.object_id
WHERE OBJECT_DEFINITION(p.OBJECT_ID) LIKE '%' + @SearchString + '%'
AND type IN ('P', 'V', 'TR', 'FN', 'IF', 'TF')
-- AND lastrun.LastRun IS NOT null
) OL
OPTION (FAST 10)
---------------------------------------------
---------------- END -----------------
---------------------------------------------
---------------------------------------------
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
If you would like to perform it dynamically try this:
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;
namespace ExampleConsoleApplication
{
enum DebugLevel : int
{
Fatal_Msgs = 0 ,
Fatal_Error_Msgs = 1 ,
Fatal_Error_Warn_Msgs = 2 ,
Fatal_Error_Warn_Info_Msgs = 3 ,
Fatal_Error_Warn_Info_Debug_Msgs = 4
}
class TestClass
{
private static readonly ILog logger = LogManager.GetLogger(typeof(TestClass));
static void Main ( string[] args )
{
TestClass objTestClass = new TestClass ();
Console.WriteLine ( " START " );
int shouldLog = 4; //CHANGE THIS FROM 0 TO 4 integer to check the functionality of the example
//0 -- prints only FATAL messages
//1 -- prints FATAL and ERROR messages
//2 -- prints FATAL , ERROR and WARN messages
//3 -- prints FATAL , ERROR , WARN and INFO messages
//4 -- prints FATAL , ERROR , WARN , INFO and DEBUG messages
string srtLogLevel = String.Empty;
switch (shouldLog)
{
case (int)DebugLevel.Fatal_Msgs :
srtLogLevel = "FATAL";
break;
case (int)DebugLevel.Fatal_Error_Msgs:
srtLogLevel = "ERROR";
break;
case (int)DebugLevel.Fatal_Error_Warn_Msgs :
srtLogLevel = "WARN";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Msgs :
srtLogLevel = "INFO";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs :
srtLogLevel = "DEBUG" ;
break ;
default:
srtLogLevel = "FATAL";
break;
}
objTestClass.SetLogingLevel ( srtLogLevel );
objTestClass.LogSomething ();
Console.WriteLine ( " END HIT A KEY TO EXIT " );
Console.ReadLine ();
} //eof method
/// <summary>
/// Activates debug level
/// </summary>
/// <sourceurl>http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx</sourceurl>
private void SetLogingLevel ( string strLogLevel )
{
string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL" ;
if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false)
throw new Exception ( " The strLogLevel should be set to WARN , INFO , DEBUG ," );
log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories ();
//Configure all loggers to be at the debug level.
foreach (log4net.Repository.ILoggerRepository repository in repositories)
{
repository.Threshold = repository.LevelMap[ strLogLevel ];
log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;
log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers ();
foreach (log4net.Core.ILogger logger in loggers)
{
( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[ strLogLevel ];
}
}
//Configure the root logger.
log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository ();
log4net.Repository.Hierarchy.Logger rootLogger = h.Root;
rootLogger.Level = h.LevelMap[ strLogLevel ];
}
private void LogSomething ()
{
#region LoggerUsage
DOMConfigurator.Configure (); //tis configures the logger
logger.Debug ( "Here is a debug log." );
logger.Info ( "... and an Info log." );
logger.Warn ( "... and a warning." );
logger.Error ( "... and an error." );
logger.Fatal ( "... and a fatal error." );
#endregion LoggerUsage
}
} //eof class
} //eof namespace
The app config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="LogTest2.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] \r\n" />
<param name="Footer" value="[Footer] \r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
<commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%thread" />
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%logger" />
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout" value="%messag2e" />
</parameter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="ColoredConsoleAppender" />
</root>
</log4net>
</configuration>
The references in the csproj file:
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
In Visual Studio Code, the default shortcut for this is Ctrl + P.
Directly to svg fill css will not work you can use as below
<style>
svg path {
fill: red;
}
</style>
<svg xmlns="http://www.w3.org/2000/svg" width="20.666" height="59.084" viewBox="0 0 20.666 59.084"><g transform="translate(-639.749 -3139)"><path d="M648.536,3173.876c0-2.875-1.725-3.8-3.471-3.8-1.683,0-3.49.9-3.49,3.8,0,3,1.786,3.8,3.49,3.8C646.811,3177.676,648.536,3176.769,648.536,3173.876Zm-3.471,2.341c-.883,0-1.437-.513-1.437-2.341,0-1.971.615-2.381,1.437-2.381.862,0,1.438.349,1.438,2.381,0,1.907-.616,2.339-1.438,2.339Z" fill="#142312"/><path d="M653.471,3170.076a1.565,1.565,0,0,0-1.416.9l-6.558,13.888h1.2a1.565,1.565,0,0,0,1.416-.9l6.559-13.887Z" fill="#142312"/><path d="M655.107,3177.263c-1.684,0-3.471.9-3.471,3.8,0,3,1.766,3.8,3.471,3.8,1.745,0,3.49-.9,3.49-3.8C658.6,3178.186,656.851,3177.263,655.107,3177.263Zm0,6.139c-.884,0-1.438-.514-1.438-2.34,0-1.972.617-2.381,1.438-2.381.862,0,1.437.349,1.437,2.381,0,1.909-.616,2.34-1.437,2.34Z" fill="#142312"/><path d="M656.263,3159.023l-1.49-14.063a1.35,1.35,0,0,0,.329-.293,1.319,1.319,0,0,0,.268-1.123l-.753-3.49a1.328,1.328,0,0,0-1.306-1.054h-6.448a1.336,1.336,0,0,0-1.311,1.068l-.71,3.493a1.344,1.344,0,0,0,.276,1.112,1.532,1.532,0,0,0,.283.262l-1.489,14.087c-1.7,1.727-4.153,4.871-4.153,8.638v28.924a1.339,1.339,0,0,0,1.168,1.49,1.357,1.357,0,0,0,.17.01h17.981a1.366,1.366,0,0,0,1.337-1.366v-29.059C660.414,3163.893,657.963,3160.749,656.263,3159.023Zm-8.307-17.349h4.274l.176.815H647.79Zm9.785,43.634v10.1H642.434v-17.253a4.728,4.728,0,0,1-2.028-4.284,4.661,4.661,0,0,1,2.028-4.215v-2c0-3.162,2.581-5.986,3.687-7.059a1.356,1.356,0,0,0,.4-.819l1.542-14.614H652.1l1.545,14.618a1.362,1.362,0,0,0,.4.819c1.109,1.072,3.688,3.9,3.688,7.059v9.153a5.457,5.457,0,0,1,0,8.5Z" fill="#142312"/></g></svg>
This worked for me
You can also use:
File imgFile = new File(“filepath”);
if(imgFile.exists())
{
ImageView myImage = new ImageView(this);
myImage.setImageURI(Uri.fromFile(imgFile));
}
This does the bitmap decoding implicit for you.
They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:
public class ConsoleTest {
public static void main(String[] args) {
System.out.println("Console is: " + System.console());
}
}
results in:
$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null
The reason Console
exists is to provide features that are useful in the specific case that you're being run from an interactive command line:
Console
will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).Notice above that redirecting even one of the streams results in System.console()
returning null
; another irritation is that there's often no Console
object available when spawned from another program such as Eclipse or Maven.
This should work (from a few alterations to your code above).
function tableCreate() {_x000D_
var body = document.getElementsByTagName('body')[0];_x000D_
var tbl = document.createElement('table');_x000D_
tbl.style.width = '100%';_x000D_
tbl.setAttribute('border', '1');_x000D_
var tbdy = document.createElement('tbody');_x000D_
for (var i = 0; i < 3; i++) {_x000D_
var tr = document.createElement('tr');_x000D_
for (var j = 0; j < 2; j++) {_x000D_
if (i == 2 && j == 1) {_x000D_
break_x000D_
} else {_x000D_
var td = document.createElement('td');_x000D_
td.appendChild(document.createTextNode('\u0020'))_x000D_
i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;_x000D_
tr.appendChild(td)_x000D_
}_x000D_
}_x000D_
tbdy.appendChild(tr);_x000D_
}_x000D_
tbl.appendChild(tbdy);_x000D_
body.appendChild(tbl)_x000D_
}_x000D_
tableCreate();
_x000D_
It depends what you mean by empty.
To check if there is no text (this allows child elements that are empty themselves):
if ($('#leftmenu').text() == '')
To check if there are no child elements or text:
if ($('#leftmenu').contents().length == 0)
Or,
if ($('#leftmenu').html() == '')
The problem is that once the page is served up, the content is going to be in the encoding described in the content-type meta tag. The content in "wrong" encoding is already garbled.
You're best to do this on the server before serving up the page. Or as I have been know to say: UTF-8 end-to-end or die.
Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/
That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.
$('.bwWrapper').BlackAndWhite({
hoverEffect : true, // default true
// set the path to BnWWorker.js for a superfast implementation
webworkerPath : false,
// to invert the hover effect
invertHoverEffect: false,
// this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
intensity:1,
speed: { //this property could also be just speed: value for both fadeIn and fadeOut
fadeIn: 200, // 200ms for fadeIn animations
fadeOut: 800 // 800ms for fadeOut animations
},
onImageReady:function(img) {
// this callback gets executed anytime an image is converted
}
});
It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.
If anyone else is stuck on this,
nothing of the above worked for me. I had to remove
implementation group: "ch.qos.logback", name: "logback-classic", version: "1.2.3"
implementation group: 'com.typesafe.scala-logging', name: "scala-logging_$scalaVersion", version: '3.9.2'
from my build.gradle for the logs to disappear. TLDR: Don't import any other logging frameworks, you should be fine just using org.apache.log4j.Logger
function test(){_x000D_
var sel1 = document.getElementById("select_id");_x000D_
var strUser1 = sel1.options[sel1.selectedIndex].value;_x000D_
console.log(strUser1);_x000D_
alert(strUser1);_x000D_
// Inorder to get the Test as value i.e "Communication"_x000D_
var sel2 = document.getElementById("select_id");_x000D_
var strUser2 = sel2.options[sel2.selectedIndex].text;_x000D_
console.log(strUser2);_x000D_
alert(strUser2);_x000D_
}
_x000D_
<select onchange="test()" id="select_id">_x000D_
<option value="0">-Select-</option>_x000D_
<option value="1">Communication</option>_x000D_
</select>
_x000D_
Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:
Unix Excel Mac Excel Human Date Human Time
Excel Epoch -2209075200 -1462 0 1900/01/00* 00:00:00 (local)
Excel = 2011 Mac† -2082758400 0 1462 1904/12/31 00:00:00 (local)
Unix Epoch 0 24107 25569 1970/01/01 00:00:00 UTC
Example Below 1234567890 38395.6 39857.6 2009/02/13 23:31:30 UTC
Signed Int Max 2147483648 51886 50424 2038/01/19 03:14:08 UTC
One Second 1 0.0000115740… — 00:00:01
One Hour 3600 0.0416666666… - 01:00:00
One Day 86400 1 1 - 24:00:00
* “Jan Zero, 1900” is 1899/12/31; see the Bug section below. † Excel 2011 for Mac (and older) use the 1904 date system.
As I often use awk
to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:
echo 1234567890 |awk '{
# tries GNU date, tries BSD date on failure
cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
cmd |getline tz # read in time-specific offset
hours = substr(tz, 2, 2) + substr(tz, 4) / 60 # hours + minutes (hi, India)
if (tz ~ /^-/) hours *= -1 # offset direction (east/west)
excel = $1/86400 + hours/24 + 25569 # as days, plus offset
printf "%.9f\n", excel
}'
I used echo
for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,
) is a UNIX epoch. Alter $1
to represent your desired column/cell number or use a variable instead.
This makes a system call to date
. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z
and the second , $1
. Given how common GNU is, I wouldn't recommend assuming BSD's version.
The getline
reads the time zone offset outputted by date +%z
into tz
, which is then translated into hours
. The format will be like -0700
(PDT) or +0530
(IST), so the first substring extracted is 07
or 05
, the second is 00
or 30
(then divided by 60 to be expressed in hours), and the third use of tz
sees whether our offset is negative and alters hours
if needed.
The formula given in all of the other answers on this page is used to set excel
, with the addition of the daylight-savings-aware time zone adjustment as hours/24
.
If you're on an older version of Excel for Mac, you'll need to use 24107
in place of 25569
(see the mapping above).
To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:
echo "last thursday" |awk '{
cmd = sprintf("date -d \"%s\" +\"%%s %%z\"", $0)
cmd |getline
hours = substr($2, 2, 2) + substr($2, 4) / 60
if ($2 ~ /^-/) hours *= -1
excel = $1/86400 + hours/24 + 25569
printf "%.9f\n", excel
}'
This is basically the same code, but the date -d
no longer has an @
to represent unix epoch (given how capable the string parser is, I'm actually surprised the @
is mandatory; what other date format has 9-10 digits?) and it's now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890
as an input.
Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3's mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.
Any date before 1900/03/01 could be as much as a day off:
Day Excel LibreOffice
-1 -1 1899/12/29
0 1900/01/00* 1899/12/30
1 1900/01/01 1899/12/31
2 1900/01/02 1900/01/01
…
59 1900/02/28 1900/02/27
60 1900/02/29(!) 1900/02/28
61 1900/03/01 1900/03/01
Excel doesn't acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they're just numbers after all), but it displays them as numbers since it doesn't know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.
If you use MVC 3 and .NET 4, you can use the new Display
attribute in the System.ComponentModel.DataAnnotations
namespace. This attribute replaces the DisplayName
attribute and provides much more functionality, including localization support.
In your case, you would use it like this:
public class MyModel
{
[Required]
[Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
public string name{ get; set; }
}
As a side note, this attribute will not work with resources inside App_GlobalResources
or App_LocalResources
. This has to do with the custom tool (GlobalResourceProxyGenerator
) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.
(As a further side note, you shouldn't be using App_GlobalResources
or App_LocalResources
with MVC. You can read more about why this is the case here)
You can also use:
Range( RangeName ).end(xlDown).row
to find the last row with data in it starting at your named range.
#!/bin/sed -f
1,/^#include/ {
/^#include/i\
#include "newfile.h"
}
How this script works: For lines between 1 and the first #include
(after line 1), if the line starts with #include
, then prepend the specified line.
However, if the first #include
is in line 1, then both line 1 and the next subsequent #include
will have the line prepended. If you are using GNU sed
, it has an extension where 0,/^#include/
(instead of 1,
) will do the right thing.
In the context of AngularJS, the $
prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:
Angular Namespaces
$
and$$
To prevent accidental name collisions with your code, Angular prefixes names of public objects with
$
and names of private objects with$$
. Please do not use the$
or$$
prefix in your code.
Source: https://docs.angularjs.org/api
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
I need a solution that has no hard coded values in the js file; using selectedIndex
. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)
$("#selectBox").get(0).selectedIndex = 1;
Five problems:
"$(...)"
to get the output of a command as text.[
is a command. Put a space between it and the arguments.echo
.rm "$folderToBeMoved"
The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.
In fact, image, ntext, and text are all deprecated.
ntext, text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).
To check if the value exists:
[#if userName??]
Hi ${userName}, How are you?
[/#if]
Or with the standard freemarker syntax:
<#if userName??>
Hi ${userName}, How are you?
</#if>
To check if the value exists and is not empty:
<#if userName?has_content>
Hi ${userName}, How are you?
</#if>
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
To test for div
elements explicitly:
if( $('div.mydivclass').length ){...}
Dependency Injection for 5 year olds.
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might be even looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
You do that by inserting into position 0:
List myList = new List();
myList.Insert(0, "test");
No CSS required. This should look fine on your page. You can set col-md-*
as per your needs
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<form class="form-inline" role="form">_x000D_
<div class="col">_x000D_
<div class="form-group">_x000D_
<label for="inputEmail" class="col-sm-3">Email</label>_x000D_
<input type="email" class="form-control col-sm-7" id="inputEmail" placeholder="Email">_x000D_
</div>_x000D_
</div>_x000D_
<div class="col">_x000D_
<div class="form-group">_x000D_
<label for="inputPassword" class="col-sm-3">Email</label>_x000D_
<input type="password" class="form-control col-sm-7" id="inputPassword" placeholder="Email">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button class="btn btn-primary">Button 1</button>_x000D_
_x000D_
<button class="btn btn-primary">Button 2</button>_x000D_
</form>_x000D_
</div>_x000D_
</div>
_x000D_
This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.
Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.
You can save the variables in the network using
saver = tf.train.Saver()
saver.save(sess, 'path of save/fileName.ckpt')
To restore the network for reuse later or in another script, use:
saver = tf.train.Saver()
saver.restore(sess, tf.train.latest_checkpoint('path of save/')
sess.run(....)
Important points:
sess
must be same between first and later runs (coherent structure). saver.restore
needs the path of the folder of the saved files, not an individual file path. Material please go through this Link And also try this
ArrayList<Class> myArray= new ArrayList<Class>();
Here is my understanding. Every time we set a seed value, a "label" or " reference" is generated. The next random.function call is attached to this "label", so next time you call the same seed value and random.function, it will give you the same result.
np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186
np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755
np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948
Are you sure you've connected to the db? (I ask because I don't see a port specified)
try:
mongoose.connection.on("open", function(){
console.log("mongodb is connected!!");
});
Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?
From the look of your connection string, you should see the record in the "test" db.
Hope it helps!
Please Try the following steps:
then press "Windows key + R" write "services.msc", run as admin
start MySQL service.
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
I had this happen after updating gcc and eclipse on ArchLinux. What solved it for me was Project -> C/C++ Index -> Rebuild
.
Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10
all children parent_id's of 10 will also be updated to 20
If you don't update the field the foreign key refers to, this setting is not needed
Can't think of any other use.
You can't do that as the foreign key constraint would fail.
Try this:
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = DataGridView1.Rows.Add();
DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
if ((bool)item["productstatus"])
{
DataGridView1.Rows[n].Cells[3].Value = "Active";
}
else
{
DataGridView1.Rows[n].Cells[3].Value = "Deactive";
}
git fetch origin master:master
pulls the latest version of master without needing to check it out.
So all you need is:
git fetch origin master:master && git rebase master
Seems the most foolproof way to start with a UTC date is to create a new Date
object and use the setUTC…
methods to set it to the date/time you want.
Then the various toLocale…String
methods will provide localized output.
// This would come from the server._x000D_
// Also, this whole block could probably be made into an mktime function._x000D_
// All very bare here for quick grasping._x000D_
d = new Date();_x000D_
d.setUTCFullYear(2004);_x000D_
d.setUTCMonth(1);_x000D_
d.setUTCDate(29);_x000D_
d.setUTCHours(2);_x000D_
d.setUTCMinutes(45);_x000D_
d.setUTCSeconds(26);_x000D_
_x000D_
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)_x000D_
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004_x000D_
console.log(d.toLocaleDateString()); // -> 02/28/2004_x000D_
console.log(d.toLocaleTimeString()); // -> 23:45:26
_x000D_
foreach($test_package_data as $key=>$data ) {
$category_detail_arr = $test_package_data[$key]['category_detail'];
foreach( $category_detail_arr as $i=>$value ) {
$test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
}
}
In addition to the other suggestions, make sure to change the existingResponse
attribute of the httpErrors
node to Auto
from Replace
, or to remove that property entirely.
<httpErrors existingResponse="Replace" />
^^^^^^^ not going to work with this here
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.
@Craig:
A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.
This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
I'm learning from udemy. I followed every step that my instructor show me to do. In spring mvc crud section while setting up the devlopment environment i had the same error for:
<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />
then i just replaced
http://www.springframework.org/schema/mvc/spring-mvc.xsd
with
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
and
http://www.springframework.org/schema/tx/spring-tx.xsd
with
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
actually i visited these two sites http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/ and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd and spring-tx-4.2.xsd
So, i suggest to try this. Hope this helps. Thank you.
You need to be careful though, You need to setup the EDMX file exactly as it was before deleting it (if you choose the delete/regenerate route), otherwise, you'll have a naming mismatch between your code and the EF generated model (especialy for pluralization and singularization)
Hope this will prevent you some headaches =)
You are looking for the static method Math.Pow()
.
Based on this comment from the OP, "I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment", I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell's alignment property directly, only that cell is affected.
There are three options shown in this tutorial. In case the link breaks I'll leave the main steps here.
1 Revert the full commit
git revert dd61ab23
2 Delete the last commit
git push <<remote>> +dd61ab23^:<<BRANCH_NAME_HERE>>
or, if the branch is available locally
git reset HEAD^ --hard
git push <<remote>> -f
where +dd61... is your commit hash and git interprets x^ as the parent of x, and + as a forced non-fastforwared push.
3 Delete the commit from a list
git rebase -i dd61ab23^
This will open and editor showing a list of all commits. Delete the one you want to get rid off. Finish the rebase and push force to repo.
git rebase --continue
git push <remote_repo> <remote_branch> -f
You probably have an alias somewhere, mapping cp
to cp -i
; because with the default settings, cp
won't ask to overwrite. Check your .bashrc
, your .profile
etc.
See cp manpage: Only when -i
parameter is specified will cp
actually prompt before overwriting.
You can check this via the alias
command:
$ alias
alias cp='cp -i'
alias diff='diff -u'
....
To undefine the alias, use:
$ unalias cp
Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever
will initially match up with those on the repo you cloned-from:
git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...
makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/
.
Depending on how long you go before you git fetch
or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch
(or git pull
which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name>
entries as needed. It's that moment of fetch
ing that makes everything match up (well, that, and the initial clone, and some cases of push
ing too—basically whenever Git gets a chance to check—but see caveat below).
Git normally has you refer to your own refs/heads/<name>
as just <name>
, and the remote ones as origin/<name>
, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master
is "where master was over there last time I checked", and master
is "where master is over here based on what I have been doing". Run git fetch
to update Git on "where master is over there" as needed.
Caveat: in versions of Git older than 1.8.4, git fetch
has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin
, or git fetch --all
, or even just git fetch
, does update. Running git fetch origin master
doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull
. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)
1Well, there is one thing that is called a "remote". But that's also local! The name origin
is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin
in origin/master
comes from. The name origin/master
is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.
I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.
cmd /k mybatchfile.cmd
if you want the command window to stay (on desktop) after batch script have finished.If it is in a Docker container, you can just restart your container. Let's assume the container name is jenkins
, so you can do:
docker restart jenkins
Or
docker stop jenkins
docker start jenkins
I am the original poster and I accepted the above answer by DGH without having first used it in the code.
Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).
I thought it was worth posting the tweak here for the benefit of others:
try:
a = Application("abcdef", "")
except pySourceAidExceptions.PathIsNotAValidOne:
pass
except:
self.assertTrue(False)
What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.
I believe that using the above code (based heavily on DGH's answer) will do that.
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList
constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
Just check JSON option from the drop down next to binary; when you click raw. This should do
Alternatively, style the tbody with a predetermined size (via height:20em
, for example) and use overflow-y:scroll;
Then, you can have a huge tbody, which will scroll independently of the rest of the page.
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
This works for me.
$('#password').replaceWith($('#password').clone().attr('type', 'text'));
Removing any alignment like android:layout_alignParentStart="true" and adding centerInParent worked for me. If the "align" stays in, the centerInParent doesn't work
Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.
In terms of API and standard library everything is implemented in terms of strings and not char[], but there are still lots of functions from the libc that receive char[] so you may need to use it for those, apart from that I would always use std::string.
In terms of efficiency of course a raw buffer of unmanaged memory will almost always be faster for lots of things, but take in account comparing strings for example, std::string has always the size to check it first, while with char[] you need to compare character by character.
You should include <string.h>
(or its C++ equivalent, <cstring>
).
This is another late answer but i figured out a fairly simple way of placing the "bar" text in between the four squares. Here are the changes i made; In the bar section i wrapped the "bar" text within a center and div tags.
<header><center><div class="bar">bar</div></center></header>
And in the CSS section i created a "bar" class which is used in the div tag above. After adding this the bar text was centered between the four colored blocks.
.bar{
position: relative;
}
you can download bjam for OSX (or any other OS) here
This is an updated solution for HTML 5 if anyone is interested & not fond of "floating".
Table works great in this case as you can set the fixed width to the table & table-cell.
.content-container{
display: table;
width: 300px;
}
.content .right{
display: table-cell;
background-color:green;
width: 100px;
}
http://jsfiddle.net/EAEKc/596/ original source code from @merkuro
From the spec:
All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F
Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007
.
Here is the missing example
library(rjson)
url <- 'http://someurl/data.json'
document <- fromJSON(file=url, method='C')
if (date1.getTime() > date2.getTime()) {
alert("The first date is after the second date!");
}
Refering to the answer given by @scottndecker to the following question, chrome now provides a 'disable JavaScript' option under Developer Tools:
...
in upper rightGood thing is you can stop and rerun again just by checking/unchecking it.
I was not satisfied with swagger-codegen
when I was looking for a tool to do this, so I wrote my own. Have a look at bootprint-swagger
The main goal compared to swagger-codegen
is to provide an easy setup (though you'll need nodejs).
And it should be easy to adapt styling and templates to your own needs, which is a core functionality of the bootprint-project
For sudo you can do this too:
sudo -S <<< "password" command
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
Just right click on the Project Solution A window pops up. Expand the common Properties. Select Start Up Project
In there on right hand side Select radio button with Single Startup Project Select your Project in there and apply.
That's it. Now save and build your project. Run the project to see the output.
_Sarath@F1
If you have import android.support.v7.app.ActionBarActivity;
and your class extends ActionBarActivity
then use this in your OnCreate
:
android.support.v7.app.ActionBar AB=getSupportActionBar();
AB.hide();
In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.
It is going to write the value of your property model.Destination
This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.
I had the exact same problem and couldn't find a solution, so after thinking and looking for a while I figured that my PHP.INI apparently didn't look in the correct directory for my PHP Extensions, so I went under:
"Directory in which the loadable extensions (modules) reside." And found the following:
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
;extension_dir = "ext"
And simply removed the ; infront of "extension_dir = "ext", note this is only for Windows, remove the semicolon in front of the first extension_dir if you are running a different operating system.
I have no idea why mine wasn't already unmarked, but it's just something to look for if you are having problems.
There is no way to configure an exclusion to the proxy settings, but a colleague of mine had an create solution for that particular problem. He installed a local proxy server called cntlm. That server supports ntlm authentication and exclusions to the general proxy settings. A perfect match.
select left(col, charindex(' ', col) - 1)
Run this adding DatabaseName in where condition.
SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber'
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_CATALOG = 'DatabaseName'
or remove where condition adding use.
use DataBaseName
SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber'
FROM INFORMATION_SCHEMA.VIEWS
Just add this after jQuery loads and before your code.
$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
console.log('data: ' + data);
console.log('textStatus: ' + textStatus);
console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });
You can list the commits by:
git cherry -v
And then compare with the following command where the number of ^ equals to the number of commits (in the example its 2 commits):
git diff HEAD^^
Here is a solution using boxplot.stats
# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]
# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)
Make the header looks like this for HttpClient in NG5:
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'apikey': this.apikey,
'appkey': this.appkey,
}),
params: new HttpParams().set('program_id', this.program_id)
};
You will be able to make api call with your localhost url, it works for me ..
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf
as well, I prefer includes
display:none
means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags.
visibility:hidden
means that unlike display:none
, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.
For example:
test | <span style="[style-tag-value]">Appropriate style in this tag</span> | test
Replacing [style-tag-value]
with display:none
results in:
test | | test
Replacing [style-tag-value]
with visibility:hidden
results in:
test | | test
In order to link the issue number to your commit message, you should add:
#issue_number
in your git commit message.
Example Commit Message from Udacity Git Commit Message Style Guide
feat: Summarize changes in around 50 characters or less
More detailed explanatory text, if necessary. Wrap it to about 72
characters or so. In some contexts, the first line is treated as the
subject of the commit and the rest of the text as the body. The
blank line separating the summary from the body is critical (unless
you omit the body entirely); various tools like `log`, `shortlog`
and `rebase` can get confused if you run the two together.
Explain the problem that this commit is solving. Focus on why you
are making this change as opposed to how (the code explains that).
Are there side effects or other unintuitive consequenses of this
change? Here's the place to explain them.
Further paragraphs come after blank lines.
- Bullet points are okay, too
- Typically a hyphen or asterisk is used for the bullet, preceded
by a single space, with blank lines in between, but conventions
vary here
If you use an issue tracker, put references to them at the bottom,
like this:
Resolves: #123
See also: #456, #789
You can also reference the repositories:
githubuser/repository#issue_number
First see your code:
dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);
Here you set both visibility to same field so that's the problem. I give one sample for that sample demo
Here is how to create a DataFrame where each series is a row.
For a single Series (resulting in a single-row DataFrame):
series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])
For multiple series with identical indices:
cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)
For multiple series with possibly different indices:
list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()
To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose()
. However, the latter approach is inefficient if the columns have different data types.
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
These are mine, based on pure SVG and CSS animations. Don't pay attention to JS code in the snippet bellow, it's just for demoing purposes. Feel free to make your custom ones basing on mine, it's super easy.
var svg = d3.select("svg"),_x000D_
columnsCount = 3;_x000D_
_x000D_
['basic', 'basic2', 'basic3', 'basic4', 'loading', 'loading2', 'spin', 'chrome', 'chrome2', 'flower', 'flower2', 'backstreet_boys'].forEach(function(animation, i){_x000D_
var x = (i%columnsCount+1) * 200-100,_x000D_
y = 20 + (Math.floor(i/columnsCount) * 200);_x000D_
_x000D_
_x000D_
svg.append("text")_x000D_
.attr('text-anchor', 'middle')_x000D_
.attr("x", x)_x000D_
.attr("y", y)_x000D_
.text((i+1)+". "+animation);_x000D_
_x000D_
svg.append("circle")_x000D_
.attr("class", animation)_x000D_
.attr("cx", x)_x000D_
.attr("cy", y+40)_x000D_
.attr("r", 16)_x000D_
});
_x000D_
circle {_x000D_
fill: none;_x000D_
stroke: #bbb;_x000D_
stroke-width: 4_x000D_
}_x000D_
_x000D_
.basic {_x000D_
animation: basic 0.5s linear infinite;_x000D_
stroke-dasharray: 20 80;_x000D_
}_x000D_
_x000D_
@keyframes basic {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic2 {_x000D_
animation: basic2 0.5s linear infinite;_x000D_
stroke-dasharray: 80 20;_x000D_
}_x000D_
_x000D_
@keyframes basic2 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic3 {_x000D_
animation: basic3 0.5s linear infinite;_x000D_
stroke-dasharray: 20 30;_x000D_
}_x000D_
_x000D_
@keyframes basic3 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic4 {_x000D_
animation: basic4 0.5s linear infinite;_x000D_
stroke-dasharray: 10 23.3;_x000D_
}_x000D_
_x000D_
@keyframes basic4 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.loading {_x000D_
animation: loading 1s linear infinite;_x000D_
stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes loading {_x000D_
0% {stroke-dashoffset: 0; stroke-dasharray: 50 0; }_x000D_
50% {stroke-dashoffset: -100; stroke-dasharray: 0 50;}_x000D_
100% { stroke-dashoffset: -200;stroke-dasharray: 50 0;}_x000D_
}_x000D_
_x000D_
.loading2 {_x000D_
animation: loading2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes loading2 {_x000D_
0% {stroke-dasharray: 5 28.3; stroke-dashoffset: 75;}_x000D_
50% {stroke-dasharray: 45 5; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -125; }_x000D_
}_x000D_
_x000D_
.spin {_x000D_
animation: spin 1s linear infinite;_x000D_
stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
0% {stroke-dashoffset: 0; stroke-dasharray: 33.3 0; }_x000D_
50% {stroke-dashoffset: -100; stroke-dasharray: 0 33.3;}_x000D_
100% { stroke-dashoffset: -200;stroke-dasharray: 33.3 0;}_x000D_
}_x000D_
_x000D_
.chrome {_x000D_
animation: chrome 2s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome {_x000D_
0% {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
25% {stroke-dasharray: 75 25; stroke-dashoffset: 0;}_x000D_
50% {stroke-dasharray: 0 100; stroke-dashoffset: -125;}_x000D_
75% {stroke-dasharray: 75 25; stroke-dashoffset: -150;}_x000D_
100% {stroke-dasharray: 0 100; stroke-dashoffset: -275;}_x000D_
}_x000D_
_x000D_
.chrome2 {_x000D_
animation: chrome2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome2 {_x000D_
0% {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
25% {stroke-dasharray: 50 50; stroke-dashoffset: 0;}_x000D_
50% {stroke-dasharray: 0 100; stroke-dashoffset: -50;}_x000D_
75% {stroke-dasharray: 50 50; stroke-dashoffset: -125;}_x000D_
100% {stroke-dasharray: 0 100; stroke-dashoffset: -175;}_x000D_
}_x000D_
_x000D_
.flower {_x000D_
animation: flower 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower {_x000D_
0% {stroke-dasharray: 0 20; stroke-dashoffset: 25;}_x000D_
50% {stroke-dasharray: 20 0; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 0 20; stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.flower2 {_x000D_
animation: flower2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower2 {_x000D_
0% {stroke-dasharray: 5 20; stroke-dashoffset: 25;}_x000D_
50% {stroke-dasharray: 20 5; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 5 20; stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.backstreet_boys {_x000D_
animation: backstreet_boys 3s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes backstreet_boys {_x000D_
0% {stroke-dasharray: 5 28.3; stroke-dashoffset: -225;}_x000D_
15% {stroke-dasharray: 5 28.3; stroke-dashoffset: -300;}_x000D_
30% {stroke-dasharray: 5 20; stroke-dashoffset: -300;}_x000D_
45% {stroke-dasharray: 5 20; stroke-dashoffset: -375;}_x000D_
60% {stroke-dasharray: 5 15; stroke-dashoffset: -375;}_x000D_
75% {stroke-dasharray: 5 15; stroke-dashoffset: -450;}_x000D_
90% {stroke-dasharray: 5 15; stroke-dashoffset: -525;}_x000D_
100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -925;}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>_x000D_
<svg width="600px" height="700px"></svg>
_x000D_
Also available on CodePen: https://codepen.io/anon/pen/PeRazr
Use the exp1 if cond else exp2
syntax.
rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)
Note you don't use return
in lambda expressions.
Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface
File | Settings | Editor --> Use soft wraps in editor
: to turn them on for all files by default.
File | Settings | Code Style | General --> Wrap when typing reaches right margin
.. but that's different (it will make new line).
The split
method will create an array. So you need to access the third element in your case..
(arrays are 0-indexed) You need to access result[2]
to get the url
var result = $(row).text().split('|');
alert( result[2] );
You do not give us enough information to know what row
is, exactly.. So depending on how you acquire the variable row
you might need to do one of the following.
row
is a string then row.split('|');
$(row).text().split('|');
input
element then $(row).val().split('|');
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
This may work for you:
Scenario 1: primitive types
string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};
if(!dictToUpdate.ContainsKey(keyToMatchInDict))
dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;
Scenario 2: The approach I used for a List as Value
int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...
if(!dictToUpdate.ContainsKey(keyToMatch))
dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
dictToUpdate[keyToMatch] = objInValueListToAdd;
Hope it's useful for someone in need of help.
I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:
$.ajax({
url: YOUR_XML_FILE
aync: false,
success: function (data) {
// Store data into a variable
},
dataType: YOUR_DATA_TYPE,
complete: ON_COMPLETE_FUNCTION_CALL
});
you could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
You are missing the @Id
entity property, and that's why Hibernate is throwing that exception.
Any JPA entity must have an identifier property, that is marked with the Id
annotation.
There are two types of identifiers:
An assigned identifier looks as follows:
@Id
private Long id;
Notice that we are using a wrapper (e.g.,
Long
,Integer
) instead of a primitive type (e.g.,long
,int
). Using a wrapper type is a better choice when using Hibernate because, by checking if theid
isnull
or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).
The assigned identifier must be set manually by the application prior to calling persist:
Post post = new Post();
post.setId(1L);
entityManager.persist(post);
An auto-generated identifier requires the @GeneratedValue
annotation besides the @Id
:
@Id
@GeneratedValue
private int id;
There are 3 strategies Hibernate can use to auto-generate the entity identifier:
IDENTITY
SEQUENCE
TABLE
The IDENTITY
strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.
The problem with
IDENTITY
is that automatic Hibernate batch inserts are disabled for this strategy.
The SEQUENCE
strategy is the best choice unless you are using MySQL. For the SEQUENCE
strategy, you also want to use the pooled
optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.
The TABLE
generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE
by default and switch to IDENTITY
for MySQL only.