You don't add the css file to the div, you add a class to it then put your import at the top of the HTML page like so:
<link href="../files/external.css" rel="stylesheet" type="text/css" />
Then add a class like the following to your code: 'myStyle'.
Then in the css file do something like:
.myStyle
{
border-style: 1px solid #DBE0E4;
}
<div runat="server">
is mapped to a HtmlGenericControl
.
Try using BtnventCss.Attributes.Add("class", "hom_but_a");
It means that one of the paths has a ".." at the beginning of it that would result in exiting the web site's root folder hierarchy. You need to google "asp.net relative paths" or something like that to help you with your problem.
BTW, a hint to where the problem is is included in the exception page that you saw. It will actually tell you what file it found the problem in.
To head off future occurences of this exception, do a search in the entire solution for this string: "../". If you find any of those in files in the root path of your web site, address them.
I delete that web page that i want to link with master page from web application,add new web page in project then set the master page(Initially I had copied web page from web site into Web application fro coping that aspx page (I was converting website to web application as project))
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
It is important to know not only the types but the mapping of these types to the database types, too:
Source added - Agile Web Development with Rails 4
A List is an ordered Collection of elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:
List<String> names = new ArrayList<String>(3); // 3 because we expect the list
// to have 3 entries. If we didn't know how many entries we expected, we
// could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
System.out.println(name); // prints the names in turn.
}
It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.
Author of the topic asked how to clear the queue "efficiently", so I assume he wants better complexity than linear O(queue size). Methods served by David Rodriguez, anon have the same complexity:
according to STL reference, operator =
has complexity O(queue size).
IMHO it's because each element of queue is reserved separately and it isn't allocated in one big memory block, like in vector. So to clear all memory, we have to delete every element separately. So the straightest way to clear std::queue
is one line:
while(!Q.empty()) Q.pop();
Downgrading the iOS development Target from 12.1
to 12
fix the issue for me as I don't have a dev team configured.
A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.
#!/bin/bash
#
# join "The rest of the story" when the first line of each story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#
PATTERN='*:';
LINEOUT=""
while read line; do
case $line in
$PATTERN)
echo ""
echo $LINEOUT
LINEOUT="$line"
;;
"")
LINEOUT=""
echo ""
;;
*) LINEOUT="$LINEOUT $line"
;;
esac
done
I build the logic without using any built-in methods, please let me know any optimization or modifications. I tested in JS editor it is working fine.
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chirag', place: 'bangalore'},
{name: 'chandan', place: 'mumbai'},
];
var toRemove = [
{name: 'chirag', place: 'bangalore'},
{name: 'deepak', place: 'bangalore'},
/*{name: 'chandan', place: 'mumbai'},*/
/*{name: 'alok', place: 'berhampur'},*/
];
var tempArr = [];
for( var i=0 ; i < myArray.length; i++){
for( var j=0; j<toRemove.length; j++){
var toRemoveObj = toRemove[j];
if(myArray[i] && (myArray[i].name === toRemove[j].name)) {
break;
}else if(myArray[i] && (myArray[i].name !== toRemove[j].name)){
var fnd = isExists(tempArr,myArray[i]);
if(!fnd){
var idx = getIdex(toRemove,myArray[i])
if (idx === -1){
tempArr.push(myArray[i]);
}
}
}
}
}
function isExists(source,item){
var isFound = false;
for( var i=0 ; i < source.length; i++){
var obj = source[i];
if(item && obj && obj.name === item.name){
isFound = true;
break;
}
}
return isFound;
}
function getIdex(toRemove,item){
var idex = -1;
for( var i=0 ; i < toRemove.length; i++){
var rObj =toRemove[i];
if(rObj && item && rObj.name === item.name){
idex=i;
break;
}
}
return idex;
}
I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink
I'm writing an OpenCL 1.2 backend for Tensorflow at https://github.com/hughperkins/tensorflow-cl
This fork of tensorflow for OpenCL has the following characteristics:
This is not the only OpenCL fork of Tensorflow available. There is also a fork being developed by Codeplay https://www.codeplay.com , using Computecpp, https://www.codeplay.com/products/computesuite/computecpp Their fork has stronger requirements than my own, as far as I know, in terms of which specific GPU devices it works on. You would need to check the Platform Support Notes (at the bottom of hte computecpp page), to determine whether your device is supported. The codeplay fork is actually an official Google fork, which is here: https://github.com/benoitsteiner/tensorflow-opencl
Use either
&dquo; <div>&dquo;"+ title +@"&dquo;</div>
or escape the double quote:
\" <div>\""+ title +@"\"</div>
To indent any old JSON, just bind it as Object
, like:
Object json = mapper.readValue(input, Object.class);
and then write it out with indentation:
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
this avoids your having to define actual POJO to map data to.
Or you can use JsonNode
(JSON Tree) as well.
late to the game on this... i too have yet another permutation of JarodPar's answer.
here's Type.IsSubClassOf(Type) courtesy of reflector:
public virtual bool IsSubclassOf(Type c)
{
Type baseType = this;
if (!(baseType == c))
{
while (baseType != null)
{
if (baseType == c)
{
return true;
}
baseType = baseType.BaseType;
}
return false;
}
return false;
}
from that, we see that it's not doing anything too cray cray and is similar to JaredPar's iterative approach. so far, so good. here's my version (disclaimer: not thoroughly tested, so lemme know if you find issues)
public static bool IsExtension(this Type thisType, Type potentialSuperType)
{
//
// protect ya neck
//
if (thisType == null || potentialSuperType == null || thisType == potentialSuperType) return false;
//
// don't need to traverse inheritance for interface extension, so check/do these first
//
if (potentialSuperType.IsInterface)
{
foreach (var interfaceType in thisType.GetInterfaces())
{
var tempType = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
if (tempType == potentialSuperType)
{
return true;
}
}
}
//
// do the concrete type checks, iterating up the inheritance chain, as in orignal
//
while (thisType != null && thisType != typeof(object))
{
var cur = thisType.IsGenericType ? thisType.GetGenericTypeDefinition() : thisType;
if (potentialSuperType == cur)
{
return true;
}
thisType = thisType.BaseType;
}
return false;
}
basically this is just an extension method to System.Type - i did this to intentionally limit the "thisType" Type to concrete Types, as my immediate usage is to LINQ query "where" predicates against Type objects. i'm sure all you smart folks out there could bang it down to an efficient, all-purpose static method if you need to :) the code does a few things the answer's code doesn't
the rest is basically the same as JaredPar's code
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
http://jsfiddle.net/D2tEf/ for an example
Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.
If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:
sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html
See if one of those gives you the "permission denied" error.
Another way of using SQLite database in NET Framework is to use Fluent-NHibernate.
[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]
Here is the brief 'Getting started' description how to do this in C# step by step:
https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started
It includes a source code as an Visual Studio project.
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);
The above method works fine with the firefox and IE , i am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png
but when i try to find the extension of file from googlechrome , i failed.
The issue is caused because of event bubbling. The first part of your code to add .grown
works fine.
The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button
and .clickable
are executed. So it removes and readd the grown
class to the div
.
You can avoid this by using e.stopPropagation()
inside .close_button
click handler to avoid the event from bubbling.
DEMO: http://jsfiddle.net/vL8DP/
Full Code
$(document).on('click', '.clickable', function () {
$(this).addClass('grown').removeClass('spot');
}).on('click', '.close_button', function (e) {
e.stopPropagation();
$(this).closest('.clickable').removeClass('grown').addClass('spot');
});
sed
can perform text transformations on input stream from a file or from a pipeline. Example:
echo 'C:\foo\bar.xml' | sed 's/\\/\//g'
gets
C:/foo/bar.xml
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
To get a list of all model classes, you can use ActiveRecord::Base.subclasses
e.g.
ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }
For non-servers this requires Remote Server Administration Tools for Windows __
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats
:
var stats = {_x000D_
a: 3,_x000D_
b: 6,_x000D_
d: 7,_x000D_
erijgolekngo: 35_x000D_
}_x000D_
/* this is the answer here */_x000D_
for (var key in Object.keys(stats)) {_x000D_
var t = Object.keys(stats)[key];_x000D_
console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
SELECT *
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);
See this blog post.
Here is the recursive way...
function flatten(arr){
let newArray = [];
for(let i=0; i< arr.length; i++){
if(Array.isArray(arr[i])){
newArray = newArray.concat(flatten(arr[i]))
}else{
newArray.push(arr[i])
}
}
return newArray;
}
console.log(flatten([1, 2, 3, [4, 5] ])); // [1, 2, 3, 4, 5]
console.log(flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]])) // [1,2,3]
console.log(flatten([[1],[2],[3]])) // [1,2,3]
Collections.synchronizedMap()
guarantees that each atomic operation you want to run on the map will be synchronized.
Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.
I really don't know why, but no one did it in the most obvious way. Here it's my implementation.
Function:
/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
var num = number+"";
while(num.length < digits){
num='0'+num;
}
return num;
}
Prototype:
Number.prototype.zeroPad=function(digits){
var num=this+"";
while(num.length < digits){
num='0'+num;
}
return(num);
};
Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.
I had to do something similar. Here is a simplified version of what worked for me. If a touch event is detected, remove the click binding.
$thing.on('touchstart click', function(event){
if (event.type == "touchstart")
$(this).off('click');
//your code here
});
In my case the click event was bound to an <a>
element so I had to remove the click binding and rebind a click event which prevented the default action for the <a>
element.
$thing.on('touchstart click', function(event){
if (event.type == "touchstart")
$(this).off('click').on('click', function(e){ e.preventDefault(); });
//your code here
});
Simple solution using a dictionary.
def frequency(l):
d = {}
for i in l:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
for k, v in d.iteritems():
if v ==max (d.values()):
return k,d.keys()
print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.
To find rows where col is NULL
, empty string or whitespace (spaces, tabs):
SELECT *
FROM table
WHERE ISNULL(LTRIM(RTRIM(col)),'')=''
To find rows where col is NOT NULL
, empty string or whitespace (spaces, tabs):
SELECT *
FROM table
WHERE ISNULL(LTRIM(RTRIM(col)),'')<>''
You can do it in a few ways.All the ways are technically the same but using Lambda would simplify some of the code. Lets say we initialize a List first with String, call it persons.
List<String> persons = new ArrayList<String>(){{add("a"); add("b"); add("c");}};
Stream<String> stream = persons.stream();
Now you can use either of the following ways.
Using the Lambda Expresiion to create a new StringArray with defined size.
String[] stringArray = stream.toArray(size->new String[size]);
Using the method reference directly.
String[] stringArray = stream.toArray(String[]::new);
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
git checkout .
will works otherwise it won't workHow to change multiple "dogsss" to "dollsss":
$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});
String
is present in package java.lang
which is imported by default in all java programs.
An alternative to using LINQ:
var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;
I have found using HashSet<T>
is quicker for lists of up to ~ 6,000 integers compared with:
var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;
I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.
If provider & "" <> "" Then
url = url & "&provider=" & provider
End if
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
You can do :
try :
string_integer = int(string)
except ValueError :
print("This string doesn't contain an integer")
The error occurs when:
$a = array();
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';
Then
echo $a['text1']['text2']; //Error!!
Solution
$b = $a['text1'];
echo $b['text2']; // prints: sometext
..
Named parameters are not supported by JPA in native queries, only for JPQL. You must use positional parameters.
Named parameters follow the rules for identifiers defined in Section 4.4.1. The use of named parameters applies to the Java Persistence query language, and is not defined for native queries. Only positional parameter binding may be portably used for native queries.
So, use this
Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");
While JPA specification doesn't support named parameters in native queries, some JPA implementations (like Hibernate) may support it
Native SQL queries support positional as well as named parameters
However, this couples your application to specific JPA implementation, and thus makes it unportable.
From a cmd:
&
is escaped like this: ^&
(based on @Wael Dalloul's answer)%
does not need to be escapedAn example:
start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8
From a batch file
&
is escaped like this: ^&
(based on @Wael Dalloul's answer)%
is escaped like this: %%
(based on the OPs update)An example:
start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8
After doing a lot of things, I upgraded pip
, setuptools
and virtualenv
.
python -m pip install -U pip
pip install -U setuptools
pip install -U virtualenv
I did steps 1, 2 in my virtual environment as well as globally.
Next, I installed the package through pip
and it worked.
In my case i found better to use "string.search".
var str = "Some very very very long string";
var n = str.search("very");
In case it would be helpful for someone.
Here is a PHP function that will insert a row only if all the specified columns values don't already exist in the table.
If one of the columns differ, the row will be added.
If the table is empty, the row will be added.
If a row exists where all the specified columns have the specified values, the row won't be added.
function insert_unique($table, $vars)
{
if (count($vars)) {
$table = mysql_real_escape_string($table);
$vars = array_map('mysql_real_escape_string', $vars);
$req = "INSERT INTO `$table` (`". join('`, `', array_keys($vars)) ."`) ";
$req .= "SELECT '". join("', '", $vars) ."' FROM DUAL ";
$req .= "WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
foreach ($vars AS $col => $val)
$req .= "`$col`='$val' AND ";
$req = substr($req, 0, -5) . ") LIMIT 1";
$res = mysql_query($req) OR die();
return mysql_insert_id();
}
return False;
}
Example usage :
<?php
insert_unique('mytable', array(
'mycolumn1' => 'myvalue1',
'mycolumn2' => 'myvalue2',
'mycolumn3' => 'myvalue3'
)
);
?>
Make your array a variable and use implode.
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
If you want to filter y active accounts add this to Harvey's code:
UserPrincipal userPrin = new UserPrincipal(context);
userPrin.Enabled = true;
after the first using. Then add
searcher.QueryFilter = userPrin;
before the find all. And that should get you the active ones.
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
Polymorphism
1. Static binding/Compile-Time binding/Early binding/Method overloading.(in same class)
2. Dynamic binding/Run-Time binding/Late binding/Method overriding.(in different classes)
class Calculation {
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]) {
Calculation obj=new Calculation();
obj.sum(10,10,10); // 30
obj.sum(20,20); //40
}
}
class Animal {
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();//output: Animals can move
b.move();//output:Dogs can walk and run
}
}
Use Predefined Character Ranges
echo $words= preg_replace('/[[:digit:]]/','', $words);
To build on Louis's helpful answer...
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)
The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:
driver.execute_script("return navigator.userAgent")
So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.
See type assertions here:
http://golang.org/ref/spec#Type_assertions
I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.
An alternative way would be:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
Saw it here
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
I'm sure it is a late response, but maybe is useful for somebody else.
You can put all your <li>
element content into <a>
tag and add the following css:
li a {
display: block;
/* and you can use padding for additional space if needs, as a clickable area / or other styling */
padding: 5px 20px;
}
I had the same problem, but this worked for me:
<a ng-href="javascript:void(0);#tagId"></a>
As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.
In fact any question on subprocess will be a good read
You can use the below code to print all column names; You can also modify the code to print other details in whichever format u like
declare @Result varchar(max)='
'
select @Result=@Result+''+ColumnName+'
'
from
(
select
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id('tblPracticeTestSections')
) t
order by ColumnId
print @Result
Output
column1
column2
column3
column4
To use the same code to print the table and its column name as C# class use the below code:
declare @TableName sysname = '<EnterTableName>'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'
select @Result = @Result + '
public static string ' + ColumnName + ' { get { return "'+ColumnName+'"; } }
'
from
(
select
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id(@TableName)
) t
order by ColumnId
set @Result = @Result + '
}'
print @Result
Output:
public class tblPracticeTestSections
{
public static string column1 { get { return "column1"; } }
public static string column2{ get { return "column2"; } }
public static string column3{ get { return "column3"; } }
public static string column4{ get { return "column4"; } }
}
So, similar to other solutions here is mine:
// For example you have this relation defined with "user()" method
public function user()
{
return $this->belongsTo('User');
}
// Just make another one defined with "user_frontend()" method
public function user_frontend()
{
return $this->belongsTo('User')->select(array('id', 'username'));
}
// Then use it later like this
$thing = new Thing();
$thing->with('user_frontend');
// This way, you get only id and username,
// and if you want all fields you can do this
$thing = new Thing();
$thing->with('user');
A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.
Or in code:
interface Named { Named(String name); }
interface HasList { HasList(List list); }
class A implements Named, HasList {
/** implements Named constructor.
* This constructor should not be used from outside,
* because List parameter is missing
*/
public A(String name) {
...
}
/** implements HasList constructor.
* This constructor should not be used from outside,
* because String parameter is missing
*/
public A(List list) {
...
}
/** This is the constructor that we would actually
* need to satisfy both interfaces at the same time
*/
public A(String name, List list) {
this(name);
// the next line is illegal; you can only call one other super constructor
this(list);
}
}
You could also set between two dates:
Delete From tblAudit
WHERE Date_dat < DATEADD(day, -360, GETDATE())
GO
Delete From tblAudit
WHERE Date_dat > DATEADD(day, -60, GETDATE())
GO
This article on CodeProject details a technique. Is basically boils down to:
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
This essentially does exactly the same as grabbing the title bar of a window, from the window manager's point of view.
This is what I did on the controller
var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive
I ended up formatting the date to my desired pattern on the directive as follows.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dates');
data.addColumn('number', 'Upper Normal');
data.addColumn('number', 'Result');
data.addColumn('number', 'Lower Normal');
data.addRows(scope.rows);
var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}
//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
chart.draw(data, options);
This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.
C++17, cross-platform: Using std::filesystem::exists
and std::filesystem::is_regular_file
.
#include <filesystem> // C++17
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
bool CreateFile(const fs::path& filePath, const std::string& content)
{
try
{
if (fs::exists(filePath))
{
std::cout << filePath << " already exists.";
return false;
}
if (!fs::is_regular_file(filePath))
{
std::cout << filePath << " is not a regular file.";
return false;
}
}
catch (std::exception& e)
{
std::cerr << __func__ << ": An error occurred: " << e.what();
return false;
}
std::ofstream file(filePath);
file << content;
return true;
}
int main()
{
if (CreateFile("path/to/the/file.ext", "Content of the file"))
{
// Your business logic.
}
}
I have found a pretty big difference in timing when testing in my browser.
I used the following script:
WARNING: running this will freeze your browser a bit, might even crash it.
var n = 10000000, i;_x000D_
i = n;_x000D_
console.time('selector');_x000D_
while (i --> 0){_x000D_
$("body");_x000D_
}_x000D_
_x000D_
console.timeEnd('selector');_x000D_
_x000D_
i = n;_x000D_
console.time('element');_x000D_
while (i --> 0){_x000D_
$(document.body);_x000D_
}_x000D_
_x000D_
console.timeEnd('element');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I did 10 million interactions, and those were the results (Chrome 65):
selector: 19591.97509765625ms
element: 4947.8759765625ms
Passing the element directly is around 4 times faster than passing the selector.
Like Daniel said you can run python commands directly from Matlab using the py. command. To run any of the libraries you just have to make sure Malab is running the python environment where you installed the libraries:
On a Mac:
Open a new terminal window;
type: which python (to find out where the default version of python is installed);
Restart Matlab;
For example:
py.sys.version;
py.sklearn.cluster.dbscan
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101
Just before your "Content of the letter" line, add \thispagestyle{fancy}
and it should show the headers you defined. (It worked for me.)
Here's the full document that I used to test:
\documentclass[12pt]{letter}
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
% page counting, header/footer
\usepackage{fancyhdr}
\usepackage{lastpage}
\pagestyle{fancy}
\lhead{\footnotesize \parbox{11cm}{Draft 1} }
\lfoot{\footnotesize \parbox{11cm}{\textit{2}}}
\cfoot{}
\rhead{\footnotesize 3}
\rfoot{\footnotesize Page \thepage\ of \pageref{LastPage}}
\renewcommand{\headheight}{24pt}
\renewcommand{\footrulewidth}{0.4pt}
\usepackage{lipsum}% provides filler text
\begin{document}
\name{ Joe Laroo }
\signature{ Joe Laroo }
\begin{letter}{ To-Address }
\renewcommand{\today}{ February 16, 2009 }
\opening{ Opening }
\thispagestyle{fancy}% sets the current page style to 'fancy' -- must occur *after* \opening
\lipsum[1-10]% just dumps ten paragraphs of filler text
\closing{ Yours truly, }
\end{letter}
\end{document}
The \opening
command sets the page style to firstpage
or empty
, so you have to use \thispagestyle
after that command.
or //div[@id='id-74385'][@class='guest clearfix']
git add .
git reset
git add .
will stage ALL the files telling git that you have resolved the conflict
git reset
will unstage ALL the staged files without creating a commit
Define the range between the numbers:
r = range(1,10)
Then use it:
if num in r:
print("All right!")
Sending a docker image to a remote server can be done in 3 simple steps:
docker save -o <path for created tar file> <image name>
Locally, use scp to transfer .tar to remote
On remote server, load image into docker:
docker load -i <path to docker image tar file>
You can specify the latest version of ruby by looking at https://www.ruby-lang.org/en/downloads/
Fetch the latest version:
curl -sSL https://get.rvm.io | bash -s stable --ruby
Install it:
rvm install 2.2
Use it as default:
rvm use 2.2 --default
Or run the latest command from ruby:
rvm install ruby --latest
rvm use 2.2 --default
Use $evalAsync if you want your callback (i.e., test()) to be executed after the DOM is constructed, but before the browser renders. This will prevent flicker -- ref.
if (scope.$last) {
scope.$evalAsync(attr.onFinishRender);
}
If you really want to call your callback after rendering, use $timeout:
if (scope.$last) {
$timeout(function() {
scope.$eval(attr.onFinishRender);
});
}
I prefer $eval instead of an event. With an event, we need to know the name of the event and add code to our controller for that event. With $eval, there is less coupling between the controller and the directive.
See ?assign
.
> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
[1] 5
'use strict';
does not suddenly make your code better.The JavaScript strict mode is a feature in ECMAScript 5. You can enable the strict mode by declaring this in the top of your script/function.
'use strict';
When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected (which is the reasoning behind the strict mode).
Consider this example:
var a = 365;
var b = 030;
In their obsession to line up the numeric literals, the developer has inadvertently initialized variable b
with an octal literal. Non-strict mode will interpret this as a numeric literal with value 24
(in base 10). However, strict mode will throw an error.
For a non-exhaustive list of specialties in strict mode, see this answer.
'use strict';
?In my new JavaScript application: Absolutely! Strict mode can be used as a whistleblower when you are doing something stupid with your code.
In my existing JavaScript code: Probably not! If your existing JavaScript code has statements that are prohibited in strict-mode, the application will simply break. If you want strict mode, you should be prepared to debug and correct your existing code. This is why using 'use strict';
does not suddenly make your code better.
Insert a 'use strict';
statement on top of your script:
// File: myscript.js
'use strict';
var a = 2;
....
Note that everything in the file myscript.js
will be interpreted in strict mode.
Or, insert a 'use strict';
statement on top of your function body:
function doSomething() {
'use strict';
...
}
Everything in the lexical scope of function doSomething
will be interpreted in strict mode. The word lexical scope is important here. For example, if your strict code calls a function of a library that is not strict, only your code is executed in strict mode, and not the called function. See this answer for a better explanation.
I found a nice article describing several things that are prohibited in strict mode (note that this is not an exclusive list):
Scope
Historically, JavaScript has been confused about how functions are scoped. Sometimes they seem to be statically scoped, but some features make them behave like they are dynamically scoped. This is confusing, making programs difficult to read and understand. Misunderstanding causes bugs. It also is a problem for performance. Static scoping would permit variable binding to happen at compile time, but the requirement for dynamic scope means the binding must be deferred to runtime, which comes with a significant performance penalty.
Strict mode requires that all variable binding be done statically. That means that the features that previously required dynamic binding must be eliminated or modified. Specifically, the with statement is eliminated, and the eval function’s ability to tamper with the environment of its caller is severely restricted.
One of the benefits of strict code is that tools like YUI Compressor can do a better job when processing it.
Implied Global Variables
JavaScript has implied global variables. If you do not explicitly declare a variable, a global variable is implicitly declared for you. This makes programming easier for beginners because they can neglect some of their basic housekeeping chores. But it makes the management of larger programs much more difficult and it significantly degrades reliability. So in strict mode, implied global variables are no longer created. You should explicitly declare all of your variables.
Global Leakage
There are a number of situations that could cause
this
to be bound to the global object. For example, if you forget to provide thenew
prefix when calling a constructor function, the constructor'sthis
will be bound unexpectedly to the global object, so instead of initializing a new object, it will instead be silently tampering with global variables. In these situations, strict mode will instead bindthis
toundefined
, which will cause the constructor to throw an exception instead, allowing the error to be detected much sooner.Noisy Failure
JavaScript has always had read-only properties, but you could not create them yourself until ES5’s
Object.createProperty
function exposed that capability. If you attempted to assign a value to a read-only property, it would fail silently. The assignment would not change the property’s value, but your program would proceed as though it had. This is an integrity hazard that can cause programs to go into an inconsistent state. In strict mode, attempting to change a read-only property will throw an exception.Octal
The octal (or base 8) representation of numbers was extremely useful when doing machine-level programming on machines whose word sizes were a multiple of 3. You needed octal when working with the CDC 6600 mainframe, which had a word size of 60 bits. If you could read octal, you could look at a word as 20 digits. Two digits represented the op code, and one digit identified one of 8 registers. During the slow transition from machine codes to high level languages, it was thought to be useful to provide octal forms in programming languages.
In C, an extremely unfortunate representation of octalness was selected: Leading zero. So in C,
0100
means 64, not 100, and08
is an error, not 8. Even more unfortunately, this anachronism has been copied into nearly all modern languages, including JavaScript, where it is only used to create errors. It has no other purpose. So in strict mode, octal forms are no longer allowed.Et cetera
The arguments pseudo array becomes a little bit more array-like in ES5. In strict mode, it loses its
callee
andcaller
properties. This makes it possible to pass yourarguments
to untrusted code without giving up a lot of confidential context. Also, thearguments
property of functions is eliminated.In strict mode, duplicate keys in a function literal will produce a syntax error. A function can’t have two parameters with the same name. A function can’t have a variable with the same name as one of its parameters. A function can’t
delete
its own variables. An attempt todelete
a non-configurable property now throws an exception. Primitive values are not implicitly wrapped.
ECMAScript 5 adds a list of reserved words. If you use them as variables or arguments, strict mode will throw an error. The reserved words are:
implements
,interface
,let
,package
,private
,protected
,public
,static
, andyield
For me the following worked on Jenkins 2.190.1 and was much simpler than some of the other workarounds:
matcher = manager.getLogMatcher('^.*Text we want comes next: (.*)$');
if (matcher.matches()) {
def myVar = matcher.group(1);
def envVar = new EnvVars([MY_ENV_VAR: myVar]);
def newEnv = Environment.create(envVar);
manager.build.environments.add(0, newEnv);
// now the matched text from the LogMatcher is passed to an
// env var we can access at $MY_ENV_VAR in post build steps
}
This was using the Groovy Script plugin with no additional changes to Jenkins.
First you have to copy, from AdapterArrayList to tempsearchnewArrayList ( Add ListView items into tempsearchnewArrayList ) , because then only you can compare whether search text is appears in Arraylist or not.
After creating temporary arraylist, add below code.
searchEditTextBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String txt = charSequence.toString().trim();
int txtlength = txt.length();
if (txtlength > 0) {
AdapterArrayList = new ArrayList<HashMap<String, String>>();
for (int j = 0; j< tempsearchnewArrayList.size(); j++) {
if (tempsearchnewArrayList.get(j).get("type").toLowerCase().contains(txt)) {
AdapterArrayList.add(tempsearchnewArrayList.get(j));
}
}
} else {
AdapterArrayList = new ArrayList<HashMap<String, String>>();
AdapterArrayList.addAll(tempsearchnewArrayList);
}
adapter1.notifyDataSetChanged();
if (AdapterArrayList.size() > 0) {
mainactivitylistview.setAdapter(adapter1);
} else {
mainactivitylistview.setAdapter(null);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
On Windows CE derived platforms, there are no iostream
s by default. The way to go there is preferaby with the _itoa<>
family, usually _itow<>
(since most string stuff are Unicode there anyway).
This should give you a list of all the tables in your database
SELECT Distinct TABLE_NAME FROM information_schema.TABLES
So you can use it similar to your database check.
If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
--CREATE TABLE Your_Table
END
GO
For replace you can use vbCrLf
:
Replace(string, vbCrLf, "")
You can also use chr(13)+chr(10)
.
I seem to remember in some odd cases that chr(10)
comes before chr(13)
.
Set the trigger
option of the popover to hover
instead of click
, which is the default one.
This can be done using either data-*
attributes in the markup:
<a id="popover" data-trigger="hover">Popover</a>
Or with an initialization option:
$("#popover").popover({ trigger: "hover" });
Here's a DEMO.
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
Arduino sketches are written in C++.
Here is a typical construct you'll encounter:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");
That's C++, not C.
Hence do yourself a favor and learn C++. There are plenty of books and online resources available.
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="imgAbt">_x000D_
<img width="220" height="220" src="img/me.jpg" />_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or, if you wish the text to closely wrap the image, change your markup to:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>
_x000D_
I thought JSON.parse(myObject)
would work. But depending on the browsers, it might be worth using eval('('+myObject+')')
. The only issue I can recommend watching out for is the multi-level list in JSON.
If you don't have it, the JFrame will just be disposed. The frame will close, but the app will continue to run.
Your Problem were the slice declarations in your data structs
(except for Track
, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.
The code below parsed the json successfully. If you've further questions, let me know.
package main
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Tracks struct {
Toptracks Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr Attr_info `json: "@attr"`
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable Streamable_info
Artist Artist_info
Attr Track_attr_info `json: "@attr"`
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string `json: "#text"`
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func perror(err error) {
if err != nil {
panic(err)
}
}
func get_content() {
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
perror(err)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var data Tracks
err = decoder.Decode(&data)
if err != nil {
fmt.Printf("%T\n%s\n%#v\n",err, err, err)
switch v := err.(type){
case *json.SyntaxError:
fmt.Println(string(body[v.Offset-40:v.Offset]))
}
}
for i, track := range data.Toptracks.Track{
fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
}
}
func main() {
get_content()
}
If you want to include jQuery code from another JS file, this should do the trick:
I had the following in my HTML file:
<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
I created a separate my_jquery.js file with the following:
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
$(this).hide("slow");
});
});
Create a file called MoveFiles.bat with the syntax
move c:\Sourcefoldernam\*.* e:\destinationFolder
then schedule a task to run that MoveFiles.bat every 10 hours.
just one line code to get simple Date format :
SimpleDateFormat.getDateInstance().format(Date())
output : 18-May-2020
SimpleDateFormat.getDateTimeInstance().format(Date())
output : 18-May-2020 11:00:39 AM
SimpleDateFormat.getTimeInstance().format(Date())
output : 11:00:39 AM
Hope this answer is enough to get this Date and Time Format ... :)
jQuery('#main').css('opacity') = '0.6';
should be
jQuery('#main').css('opacity', '0.6');
Update:
http://jsfiddle.net/GegMk/ if you type in the text box. Click away, the opacity changes.
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__
you can do simplify things a bit.
Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
INSERT
INTO first_table f
SELECT *
FROM second_table s
ON DUPLICATE KEY
UPDATE
s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
I would not suggest to use sll
or srl
with std_logic_vector.
During simulation sll
gave me 'U' value for those bits, where I expected 0's.
Use shift_left()
, shift_right()
functions.
For example:
OP1 : in std_logic_vector(7 downto 0);
signal accum: std_logic_vector(7 downto 0);
accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1))));
accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));
import static com.googlecode.catchexception.apis.BDDCatchException.*;
@Test
public void testFooThrowsIndexOutOfBoundsException() {
when(() -> foo.doStuff());
then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);
}
eu.codearte.catch-exception:catch-exception:2.0
Installing the mysql gem on OSX
in a terminal.. First do a ‘locate mysql_config’ and then replace the path in the following command with where that file is.
$ sudo gem install mysql -- —–with-mysql-config=/usr/local/mysql/bin/mysql_config
Building native extensions. This could take a while…
Successfully installed mysql-2.7
1 gem installed
Just take 2 steps and problem would be more likely to get solved:
Step 1: Clean your project by clicking Project -> Clean.
Step 2: Rebuild your project by clicking Project -> Build All.
Also make sure that your layout xml files are syntax error free and you don't have any image which has non-acceptable names (such as a "-" between image name).
Also I request you to have a look at problems window and let me know what errors are being shown there.
<?php
session_start();
if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}
else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>
If you want to clear all the headers as well as the data, for example if you are switching between 2 totally different databases with different fields, therefore different columns and column headers, I found the following to work. Otherwise when you switch you have the columns/ fields from both databases showing in the grid.
dataTable.Dispose();//get rid of existing datatable
dataTable = new DataTable();//create new datatable
datagrid.DataSource = dataTable;//clears out the datagrid with empty datatable
//datagrid.Refresh(); This does not seem to be neccesary
dataadapter.Fill(dataTable); //assumming you set the adapter with new data
datagrid.DataSource = dataTable;
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win
window
is an instance of DOMWindow
, and by setting something to window.alert
, the correct implementation is being "shadowed", i.e. when accessing alert
it is first looking for it on the window
object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert
property to window
it finds it straight away and does not need to go up the prototype chain. Using delete window.alert
you can remove the window own property and again expose the prototype implementation of alert
. This may help explain:
window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false
I was receiving this notice for doing this:
$var = reset($myClass->my_magic_property);
This fixed it:
$tmp = $myClass->my_magic_property;
$var = reset($tmp);
Your way can't work for two reasons.
You need to use set /p text=
for setting the variable with user input.
The other problem is the pipe.
A pipe starts two asynchronous cmd.exe instances and after finishing the job both instances are closed.
That's the cause why it seems that the variables are not set, but a small example shows that they are set but the result is lost later.
set myVar=origin
echo Hello | (set /p myVar= & set myVar)
set myVar
Outputs
Hello
origin
Alternatives: You can use the FOR loop to get values into variables or also temp files.
for /f "delims=" %%A in ('echo hello') do set "var=%%A"
echo %var%
or
>output.tmp echo Hello
>>output.tmp echo world
<output.tmp (
set /p line1=
set /p line2=
)
echo %line1%
echo %line2%
Alternative with a macro:
You can use a batch macro, this is a bit like the bash equivalent
@echo off
REM *** Get version string
%$set% versionString="ver"
echo The version is %versionString[0]%
REM *** Get all drive letters
`%$set% driveLetters="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveLetters
The definition of the macro can be found at
SO:Assign output of a program to a variable using a MS batch file
Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.
CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.
I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.
If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.
Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.
Primatives:
boolean
character
byte
short
integer
long
float
double
Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types
Take a look at incredible Bluetooth Serial class that has onResume()
ability that helped me so much.
I hope this helps ;)
You cannot create a method inside another method, move private boolean checkInternetConnection() {
method out of onCreate
Given a dataset
df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'),
occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )
you can subset rows
df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts
etc.
If you want to get number of rows, just call the function nrow
such as
nrow(df[df$sex == 'M',])
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
Declare your function pointer like this:
bool (*f)();
f = A;
f();
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:
http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html
It takes multiple comma separated matrices and data.frames as input :) You just need to
install.packages("gdata", dependencies=TRUE)
and then
library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)
To call the function you have to add ()
{this.renderIcon()}
This is how you can send the id_data to a modal :
<input
href="#"
data-some-id="uid0123456789"
data-toggle="modal"
data-target="#my_modal"
value="SHOW MODAL"
type="submit"
class="btn modal-btn"/>
<div class="col-md-5">
<div class="modal fade" id="my_modal">
<div class="modal-body modal-content">
<h2 name="hiddenValue" id="hiddenValue" />
</div>
<div class="modal-footer" />
</div>
And the javascript :
$(function () {
$(".modal-btn").click(function (){
var data_var = $(this).data('some-id');
$(".modal-body h2").text(data_var);
})
});
list_of_tuples = [('1', '2', '3', '4'),
('2', '3', '4', '5'),
('3', '4', '5', '6'),
('4', '5', '6', '7')]
def mod_tuples(list_of_tuples):
for i in range(0, len(list_of_tuples)):
addition = ''
for x in list_of_tuples[i]:
addition = addition + x
list_of_tuples[i] = list_of_tuples[i] + (addition,)
return list_of_tuples
# check:
print mod_tuples(list_of_tuples)
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.
Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:
/pages/en/faqs/faq-page1.html
Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them
index.html
is:
/pages/en/faqs/index.html
if called from /pages/en/faqs/faq-page1.html
/pages/index.html
if called from /pages/example.html
There are also two special directory names: .
and ..
:
.
means "current directory"..
means "parent directory"You can use them to build relative paths:
../index.html
is /pages/en/index.html
if called from /pages/en/faqs/faq-page1.html
../../index.html
is /pages/index.html
if called from /pages/en/faqs/faq-page1.html
Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:
You can use the moment libraries local data functions.
Code:
moment.localeData().ordinal(1)
//1st
Having html collection of selects you can check if every select has option with specific value and filter those which don't match condition:
//get select collection:
let selects = $('select')
//reduce if select hasn't at least one option with value 1
.filter(function () { return [...this.children].some(el => el.value == 1) });
Another way to do this:
git push origin --delete <branch_name>
)yourNode.Toggle();
//use that function on your node, it toggles it
Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.
#region SyncContextCancel
private SynchronizationContext _syncContextCancel;
/// <summary>
/// Gets the synchronization context used for UI-related operations.
/// </summary>
/// <value>The synchronization context.</value>
protected SynchronizationContext SyncContextCancel
{
get { return _syncContextCancel; }
}
#endregion //SyncContextCancel
public void CancelCurrentDbCommand()
{
_syncContextCancel = SynchronizationContext.Current;
//ThreadPool.QueueUserWorkItem(CancelWork, null);
Thread worker = new Thread(new ThreadStart(CancelWork));
worker.Priority = ThreadPriority.Highest;
worker.Start();
}
SQLiteConnection _connection;
private void CancelWork()//object state
{
bool success = false;
try
{
if (_connection != null)
{
log.Debug("call cancel");
_connection.Cancel();
log.Debug("cancel complete");
_connection.Close();
log.Debug("close complete");
success = true;
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
SyncContextCancel.Send(CancelCompleted, new object[] { success });
}
public void CancelCompleted(object state)
{
object[] args = (object[])state;
bool success = (bool)args[0];
if (success)
{
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
the easy way is the "values" property df.iloc[:,1:].values
a=df.iloc[:,1:]
b=df.iloc[:,1:].values
print(type(df))
print(type(a))
print(type(b))
so, you can get type
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>
Basically indexOf()
is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
var pos = time.indexOf('.');_x000D_
var hrs = time.substr(1, pos - 1);_x000D_
var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
if (hrs > 11) {_x000D_
hrs = (hrs - 12) + ":" + min + " PM";_x000D_
} else {_x000D_
hrs += ":" + min + " AM";_x000D_
}_x000D_
return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
And it is good to do the string conversion inside your function definition,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
So that the code flow won't break at times when devs forget to pass a string into this function.
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
Run ASSOC and FTYPE to see what your py files are associated to. (These commands are internal to cmd.exe so if you use a different command processor ymmv.)
C:> assoc .py
.py=Python.File
C:> ftype Python.File
Python.File="C:\Python26.w64\python.exe" "%1" %*
C:> assoc .pyw
.pyw=Python.NoConFile
C:> ftype Python.NoConFile
Python.NoConFile="C:\Python26.w64\pythonw.exe" "%1" %*
(I have both 32- and 64-bit installs of Python, hence my local directory name.)
I have a ListView
comprised of EditText
views. The scenario says that after editing text in one or more row(s) we should click on a button called "finish". I used onFocusChanged
on the EditText
view inside of listView
but after clicking on finish the data is not being saved. The problem was solved by adding
listView.clearFocus();
inside the onClickListener
for the "finish" button and the data was saved successfully.
I recently had to do this for Textboxes and Checkboxes but using JavaScript ...
How to reset textbox and checkbox controls in an ASP.net document
Here is the code ...
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ResetForm() {
//get the all the Input type elements in the document
var AllInputsElements = document.getElementsByTagName('input');
var TotalInputs = AllInputsElements.length;
//we have to find the checkboxes and uncheck them
//note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
for(var i=0;i< TotalInputs ; i++ )
{
if(AllInputsElements[i].type =='checkbox')
{
AllInputsElements[i].checked = false;
}
}
//reset all textbox controls
$('input[type=text], textarea').val('');
Page_ClientValidateReset();
return false;
}
//This function resets all the validation controls so that they don't "fire" up
//during a post-back.
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
</script>
And call it with a button or any other method ...
<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>
If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();
I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.
While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable))
. Using the example from @X.X:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> data.frame(rbind(freq_t))
X3 X4 X5
4 1 8 2
6 2 4 1
8 12 0 2
If the column names do not start with numbers, the X
won't get added to the front of them.
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
I have to offer this as a better approach - you don't always have the luxury of an identity field:
UPDATE m
SET [status]=10
FROM (
Select TOP (10) *
FROM messages
WHERE [status]=0
ORDER BY [priority] DESC
) m
You can also make the sub-query as complicated as you want - joining multiple tables, etc...
Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages
table. It can be used to update the top N rows from any table, even if that table has no unique key at all.
You can use apache's commons-text library (instead of commons-lang):
Example code:
org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);
Dependency:
compile 'org.apache.commons:commons-text:1.8'
OR
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
// Java 8
System.out.println(LocalDateTime.now().getYear()); // 2015
System.out.println(LocalDateTime.now().getMonth()); // SEPTEMBER
System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 36
System.out.println(LocalDateTime.now().getSecond()); // 51
System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100
// Calendar
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); // 2015
System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1); // 9
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 35
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND)); // 481
// Joda Time
System.out.println(new DateTime().getYear()); // 2015
System.out.println(new DateTime().getMonthOfYear()); // 9
System.out.println(new DateTime().getDayOfMonth()); // 29
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 19
System.out.println(new DateTime().getSecondOfMinute()); // 16
System.out.println(new DateTime().getMillisOfSecond()); // 174
// Formatted
// 2015-09-28 17:50:25.756
System.out.println(new Timestamp(System.currentTimeMillis()));
// 2015-09-28T17:50:25.772
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));
// Java 8
// 2015-09-28T17:50:25.810
System.out.println(LocalDateTime.now());
// joda time
// 2015-09-28 17:50:25.839
System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double
, and then round the double
back to 15 decimal places you'll get the same number. To uniquely represent a double
you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double
) which is why 17 places are showing up, but not all 17-decimal numbers map to different double
values (like in the examples in the other answers).
in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.
<table id="tabel_data">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>heading 1</th>_x000D_
<th>heading 2</th>_x000D_
<th>heading 3</th>_x000D_
<th>heading 4</th>_x000D_
<th>heading 5</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>data-1</td>_x000D_
<td>data-2</td>_x000D_
<td>data-3</td>_x000D_
<td>data-4</td>_x000D_
<td>data-5</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<table id="tabel_data">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>heading 1</th>_x000D_
<th>heading 2</th>_x000D_
<th>heading 3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>data-1</td>_x000D_
<td>data-2</td>_x000D_
<td>data-3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor
In general, a condition in the WHERE
clause of an SQL query can reference only a single row. The context of a WHERE
clause is evaluated before any order has been defined by an ORDER BY
clause, and there is no implicit order to an RDBMS table.
You can use a derived table to join each row to the group of rows with a lesser id
value, and produce the sum of each sum group. Then test where the sum meets your criterion.
CREATE TABLE MyTable ( id INT PRIMARY KEY, cash INT );
INSERT INTO MyTable (id, cash) VALUES
(1, 200), (2, 301), (3, 101), (4, 700);
SELECT s.*
FROM (
SELECT t.id, SUM(prev.cash) AS cash_sum
FROM MyTable t JOIN MyTable prev ON (t.id > prev.id)
GROUP BY t.id) AS s
WHERE s.cash_sum >= 500
ORDER BY s.id
LIMIT 1;
Output:
+----+----------+
| id | cash_sum |
+----+----------+
| 3 | 501 |
+----+----------+
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial
You can make this.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )
IF @@ROWCOUNT = 0 SET @ERRFLAG = 200
SET NOCOUNT OFF
declare @cnt bigint
set @cnt = 1
while @cnt*100<10000000
begin
UPDATE top(100) [Imp].[dbo].[tablename]
SET [col1] = xxxx
WHERE[col1] is null
print '@cnt: '+convert(varchar,@cnt)
set @cnt=@cnt+1
end
From the C++0x draft Standard.
$5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"
Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.
As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.
This is what happens when you store your dates and times in a non-standard format. Working with them become problematic.
$datetime = DateTime::createFromFormat('YmdHi', '201308131830');
echo $datetime->format('D');
If you've got PowerShell on your system, you can just execute this command:
powershell -command "Start-Sleep -s 5"
Edit: people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:
powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"
This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).
<script type="text/javascript">
if(screen.width <= 699){
<?php $screen = 'mobile';?>
}else{
<?php $screen = 'default';?>
}
</script>
<?php echo $screen; ?>
I found this worked for me.
$username = 'user'
$password = 'password'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process Notepad.exe -Credential $credential
Updated: changed to using single quotes to avoid special character issues noted by Paddy.
The examples contained in this blog post do the trick.
Yes if you are using Python 3.3+. You can use the built-in unittest.mock
to assert method called. For Python 2.6+ use the rolling backport Mock
, which is the same thing.
Here is a quick example in your case:
from unittest.mock import MagicMock
aw = aps.Request("nv1")
aw.Clear = MagicMock()
aw2 = aps.Request("nv2", aw)
assert aw.Clear.called
Set the Screen orientation to portrait in Manifest file under the activity Tag.
Just go to php.ini then find short_open_tag= Off
set to short_open_tag= On
Apart from the accepted answer, other problems can cause the exception too. For me it was that the certificate was not trusted (i.e., self-signed cert and not in the trust store).
If the certificate file does not exists, or could not be loaded (e.g., typo in path) can---in certain circumstances---cause the same exception.
Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!
But how to add this flag by default for all C++ projects? Anybody?
Use the boolean()
XPath function
The boolean function converts its argument to a boolean as follows:
a number is true if and only if it is neither positive or negative zero nor NaN
a node-set is true if and only if it is non-empty
a string is true if and only if its length is non-zero
an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type
If there is an AttachedXml in the CreditReport of primary Consumer, then it will return true()
.
boolean(/mc:Consumers
/mc:Consumer[@subjectIdentifier='Primary']
//mc:CreditReport/mc:AttachedXml)
Another way to do this without jQuery would be to use Greensock's TweenLite JS library.
Demo http://codepen.io/anon/pen/yNWwEJ
var display = document.getElementById("display");
var number = {param:0};
var duration = 1;
function count() {
TweenLite.to(number, duration, {param:"+=20", roundProps:"param",
onUpdate:update, onComplete:complete, ease:Linear.easeNone});
}
function update() {
display.innerHTML = number.param;
}
function complete() {
//alert("Complete");
}
count();
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("\\|");
for (String string : value_split) {
System.out.println(string);
}
nanoid achieves exactly the same thing that you want.
Example usage:
const { nanoid } = require("nanoid")
console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"
The right syntax of the php_flag command is
php_flag session.cookie_httponly On
And be aware, just first answer from server set the cookie and here (for example You can see the "HttpOnly" directive. So for testing delete cookies from browser after every testing request.
(For completeness) If you want to remove columns by name, you can do this:
cols.dont.want <- "genome"
cols.dont.want <- c("genome", "region") # if you want to remove multiple columns
data <- data[, ! names(data) %in% cols.dont.want, drop = F]
Including drop = F
ensures that the result will still be a data.frame
even if only one column remains.
For JPA 2.1 the javax.persistence package can be found in here:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions
The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
The FLAG_ACTIVITY_NO_ANIMATION
flag works fine for disabling the animation when starting activities.
To disable the similar animation that is triggered when calling finish()
on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0)
after calling finish()
and the next animation will be excluded.
This also works on the in-animation if you call overridePendingTransition(0, 0)
after calling startActivity(...)
.
Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.
Here is an example on how to parse a JSON string into a dynamic object:
string source = "{\r\n \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\", \r\n \"first_name\": \"Jerard\", \r\n \"last_name\": \"Jones\", \r\n \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n \"username\": \"Jerard.Jones\", \r\n \"gender\": \"female\", \r\n \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);
Happy coding!
To avoid including a large framework, I think a simple homemade class can do the trick.
Example of class to handle named parameters:
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String sql) throws SQLException {
int pos;
while((pos = sql.indexOf(":")) != -1) {
int end = sql.substring(pos).indexOf(" ");
if (end == -1)
end = sql.length();
else
end += pos;
fields.add(sql.substring(pos+1,end));
sql = sql.substring(0, pos) + "?" + sql.substring(end);
}
prepStmt = conn.prepareStatement(sql);
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setInt(String name, int value) throws SQLException {
prepStmt.setInt(getIndex(name), value);
}
private int getIndex(String name) {
return fields.indexOf(name)+1;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}
Example of calling the class:
String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();
Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.
You could do the following, without needing CSS...
<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>
Example: https://jsfiddle.net/jord8on/k1zsfqyk/
This solution was PERFECT for my needs! I found this solution here.
Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.
what you want is:
MY_FIELD=
case
when (selectField1 = 1) then Field1
else Field2
end,
in the select
However, y don't you just not show that column in your program?
If you don't mind using jQuery, then you can use offset()
function. Refer to documentation if you want to read up more about this function.
You can use the start
command to do much the same thing as ShellExecute
. For example
start "" http://www.stackoverflow.com
This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.
You would want and
instead of &&
.
You could also use Joe Blau's gitignore.io
Either through the web interfase https://www.gitignore.io/
Or by installing the CLI tool, it's very easy an fast, just type the following on your terminal:
Linux:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bashrc && source ~/.bashrc
OSX:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bash_profile && source ~/.bash_profile
And then you can just type gi
followd by the all the platform/environment elements you need gitignore criteria for.
Example!
Lets say you're working on a node project that includes grunt and you're using webstorm on linux, then you may want to type:
gi linux,webstorm,node,grunt > .gitignore
( to make a brand new file)
or
gi linux,webstorm,node,grunt >> .gitignore
( to append/add the new rules to an existing file)
bam, you're good to go
Swift 3 :
tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.
My GOPATH workspace is c:\work\go
and under that I have
/src/pg/main.go (package main)
/src/pg/dbtypes.go (pakage dbtypes)
in main.go
I import "/pg/dbtypes"
Read public key from pem (PK or Cert). Depends on Bouncycastle.
private static PublicKey getPublicKeyFromPEM(Reader reader) throws IOException {
PublicKey key;
try (PEMParser pem = new PEMParser(reader)) {
JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
Object pemContent = pem.readObject();
if (pemContent instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
key = keyPair.getPublic();
} else if (pemContent instanceof SubjectPublicKeyInfo) {
SubjectPublicKeyInfo keyInfo = (SubjectPublicKeyInfo) pemContent;
key = jcaPEMKeyConverter.getPublicKey(keyInfo);
} else if (pemContent instanceof X509CertificateHolder) {
X509CertificateHolder cert = (X509CertificateHolder) pemContent;
key = jcaPEMKeyConverter.getPublicKey(cert.getSubjectPublicKeyInfo());
} else {
throw new IllegalArgumentException("Unsupported public key format '" +
pemContent.getClass().getSimpleName() + '"');
}
}
return key;
}
Read private key from PEM:
private static PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException {
PrivateKey key;
try (PEMParser pem = new PEMParser(reader)) {
JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
Object pemContent = pem.readObject();
if (pemContent instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
key = keyPair.getPrivate();
} else if (pemContent instanceof PrivateKeyInfo) {
PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
} else {
throw new IllegalArgumentException("Unsupported private key format '" +
pemContent.getClass().getSimpleName() + '"');
}
}
return key;
}
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
This appears to be a bug in Bundler not recognizing the default gems installed along with ruby 2.x. I still experienced the problem even with the latest version of bundler (1.5.3).
One solution is to simply delete json-1.8.1.gemspec from the default gemspec directory.
rm ~/.rubies/ruby-2.1.0/lib/ruby/gems/2.1.0/specifications/default/json-1.8.1.gemspec
After doing this, bundler should have no problem locating the gem. Note that I am using chruby. If you're using some other ruby manager, you'll have to update your path accordingly.
On my system (Win 10, JRE 1.8.0, Android Studio 3.1.2, Gradle 4.1) there is no tools.jar
in the JRE directory (C:\Program Files\Java\jre1.8.0_171
).
However, I found it in C:\Program Files\Android\Android Studio\jre\lib
and tried setting JAVA_HOME=C:\Program Files\Android\Android Studio\jre
That works (for me)!
With string type columns like character(2)
(as you mentioned later), the displayed concatenation just works because, quoting the manual:
[...] the string concatenation operator (
||
) accepts non-string input, so long as at least one input is of a string type, as shown in Table 9.8. For other cases, insert an explicit coercion totext
[...]
Bold emphasis mine. The 2nd example (select a||', '||b from foo
) works for any data types since the untyped string literal ', '
defaults to type text
making the whole expression valid in any case.
For non-string data types, you can "fix" the 1st statement by casting at least one argument to text
. (Any type can be cast to text
):
SELECT a::text || b AS ab FROM foo;
Judging from your own answer, "does not work" was supposed to mean "returns NULL". The result of anything concatenated to NULL is NULL. If NULL values can be involved and the result shall not be NULL, use concat_ws()
to concatenate any number of values (Postgres 9.1 or later):
SELECT concat_ws(', ', a, b) AS ab FROM foo;
Or concat()
if you don't need separators:
SELECT concat(a, b) AS ab FROM foo;
No need for type casts here since both functions take "any"
input and work with text representations.
More details (and why COALESCE
is a poor substitute) in this related answer:
+
is not a valid operator for string concatenation in Postgres (or standard SQL). It's a private idea of Microsoft to add this to their products.
There is hardly any good reason to use (synonym: character(n)
). Use char(n)
text
or varchar
. Details:
There are two different ways to change a background image CSS with jQuery.
$('selector').css('backgroundImage','url(images/example.jpg)');
$('selector').css({'background-image':'url(images/example.jpg)'});
Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.
This is actually pretty easy to do. All you have to do is change the css.
Here's a fiddle with a very simple fade animation: http://jsfiddle.net/elthrasher/sNpjH/
To make it into a sliding animation, I first had to put my element in a box (that's the slide-container), then I added another element to replace the one that was leaving, just because I thought it would look nice. Take it out and the example will still work.
I changed the animation css from 'fade' to 'slide' but please note that these are the names I gave it. I could have written slide animation css named 'fade' or anything else for that matter.
The important part is what's in the css. Here's the original 'fade' css:
.fade-hide, .fade-show {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.fade-hide {
opacity:1;
}
.fade-hide.fade-hide-active {
opacity:0;
}
.fade-show {
opacity:0;
}
.fade-show.fade-show-active {
opacity:1;
}
This code changes the opacity of the element from 0 (completely transparent) to 1 (completely opaque) and back again. The solution is to leave opacity alone and instead change the top (or left, if you want to move left-right).
.slide-hide, .slide-show {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
}
.slide-hide {
position: relative;
top: 0;
}
.slide-hide.slide-hide-active {
position: absolute;
top: -100px;
}
.slide-show {
position: absolute;
top: 100px;
}
.slide-show.slide-show-active {
position: relative;
top: 0px;
}
I'm also changing from relative to absolute positioning so only one of the elements takes up space in the container at a time.
Here's the finished product: http://jsfiddle.net/elthrasher/Uz2Dk/. Hope this helps!
An even simpler way to share the data between controllers is using nested data structures. Instead of, for example
$scope.customer = {};
we can use
$scope.data = { customer: {} };
The data
property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.
Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.
It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).
Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
Dont forget the "BUTTON" element wich can handle some more HTML inside...
Beware: leaving calls to console in your production code will cause your site to break in Internet Explorer. Never keep it unwrapped. See: https://web.archive.org/web/20150908041020/blog.patspam.com/2009/the-curse-of-consolelog
When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.
Properties files from where? Your main jar? Dependencies?
In the former case, putting resources under src/test/resources
as suggested is probably the most straight forward and simplest option.
In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude
in the unpackOptions
.