log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
If anyone is looking out for using it to apply on the react then you can follow the code pattern given below. You have to add extra property which is rel.
<a href="mysite.com" target="_blank" rel="noopener noreferrer" >Click me to open in new Window</a>
Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you
I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:
<parent>
<child >
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</child>
<child >
<child4> value 4 </child4>
<child5> value 5</child5>
<child6> value 6 </child6>
</child>
</parent>
JAVA CODE:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class saxParser {
static Map<String,String> tmpAtrb=null;
static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {
/**
* We can pass the class name of the XML parser
* to the SAXParserFactory.newInstance().
*/
//SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
SAXParserFactory saxDoc = SAXParserFactory.newInstance();
SAXParser saxParser = saxDoc.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
String tmpElementName = null;
String tmpElementValue = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tmpElementValue = "";
tmpElementName = qName;
tmpAtrb=new HashMap();
//System.out.println("Start Element :" + qName);
/**
* Store attributes in HashMap
*/
for (int i=0; i<attributes.getLength(); i++) {
String aname = attributes.getLocalName(i);
String value = attributes.getValue(i);
tmpAtrb.put(aname, value);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(tmpElementName.equals(qName)){
System.out.println("Element Name :"+tmpElementName);
/**
* Retrive attributes from HashMap
*/ for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
}
System.out.println("Element Value :"+tmpElementValue);
xmlVal.put(tmpElementName, tmpElementValue);
System.out.println(xmlVal);
//Fetching The Values From The Map
String getKeyValues=xmlVal.get(tmpElementName);
System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
tmpElementValue = new String(ch, start, length) ;
}
};
/**
* Below two line used if we use SAX 2.0
* Then last line not needed.
*/
//saxParser.setContentHandler(handler);
//saxParser.parse(new InputSource("c:/file.xml"));
saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
}
}
OUTPUT:
Element Name :child1
Element Value : value 1
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1
Element Name :child2
Element Value : value 2
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2
Element Name :child3
Element Value : value 3
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3
Element Name :child4
Element Value : value 4
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }
"a" is an integer, when divided with integer it gives you an integer. Then it is assigned to "b" as an integer and becomes a float.
You should do it like this
b = a / 350.0;
Instead of using the conditions
syntax from Rails 2, use Rails 4's where
method instead:
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
.page(page)
.per_page(5)
end
NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
.page(page)
.per_page(5)
end
NOTE: using ILIKE
for the name - postgres case insensitive version of LIKE
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
In one line, answer is as below;
[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]
A short and essential definition might be this: Linq Aggregate extension method allows to declare a sort of recursive function applied on the elements of a list, the operands of whom are two: the elements in the order in which they are present into the list, one element at a time, and the result of the previous recursive iteration or nothing if not yet recursion.
In this way you can compute the factorial of numbers, or concatenate strings.
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
Or how about this?
with some_birthdays as
(
select date '1968-06-09' d from dual union all
select date '1970-06-10' from dual union all
select date '1972-06-11' from dual union all
select date '1974-12-11' from dual union all
select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
My solution, also quite simple..
$array = [...];
$last = count($array) - 1;
foreach($array as $index => $value)
{
if($index == $last)
// this is last array
else
// this is not last array
}
Uninstall composer
To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:
sudo apt-get remove composer
Uninstall composer and it's dependent packages
To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.
sudo apt-get remove --auto-remove composer
Purging composer
If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:
sudo apt-get purge composer
To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:
sudo apt-get purge --auto-remove composer
https://www.howtoinstall.co/en/ubuntu/xenial/composer?action=remove
It would be easier to make suggestions if you provided example code and data.
Accessing the dictionary is unlikely to be a problem as that operation is O(1) on average, and O(N) amortized worst case. It's possible that the built-in hashing functions are experiencing collisions for your data. If you're having problems with has the built-in hashing function, you can provide your own.
Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function. Such a hash function takes the information in a key object and uses it to produce an integer, called a hash value. This hash value is then used to determine which "bucket" this (key, value) pair should be placed into.
You can overwrite the __hash__ method in your class to implement a custom hash function like this:
def __hash__(self):
return hash(str(self))
Depending on what your data actually looks like, you might be able to come up with a faster hash function that has fewer collisions than the standard function. However, this is unlikely. See the Python Wiki page on Dictionary Keys for more information.
<script type="text/javascript">
$(document).ready(function(){
$("#test").keypress(function(e){
if (e.which == 103)
{
alert('g');
};
});
});
</script>
<input type="text" id="test" />
this site says 71 = g but the jQuery code above thought otherwise
Capital G = 71, lowercase is 103
Update December 2012 (19 months later):
The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":
The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.
Update July 2012 (14 months later):
With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":
If you want to play with it, you only need to write a plug-in, create a CSS file and use the
org.eclipse.e4.ui.css.swt.theme
extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.
Original answer: August 2011
With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.
Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".
As of Java 1.7 createTempDirectory(prefix, attrs)
and createTempDirectory(dir, prefix, attrs)
are included in java.nio.file.Files
Example:
File tempDir = Files.createTempDirectory("foobar").toFile();
thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !
and guess what i did find the problem .
var title = $("em").attr("title");
$("div").text(title);
this is what i add to my script and the blew codes to my html part :
<td> <em title=\"$weight\">$weight</em></td>
and found each row $weight value
thanks again to Jim Petkus
Why not just pass the window as a command parameter?
C#:
private void Cancel( Window window )
{
window.Close();
}
private ICommand _cancelCommand;
public ICommand CancelCommand
{
get
{
return _cancelCommand ?? ( _cancelCommand = new Command.RelayCommand<Window>(
( window ) => Cancel( window ),
( window ) => ( true ) ) );
}
}
XAML:
<Window x:Class="WPFRunApp.MainWindow"
x:Name="_runWindow"
...
<Button Content="Cancel"
Command="{Binding Path=CancelCommand}"
CommandParameter="{Binding ElementName=_runWindow}" />
When you want to direct download any image or pdf file from browser instead on opening it in new tab then in javascript you should set value to download attribute of create dynamic link
var path= "your file path will be here";
var save = document.createElement('a');
save.href = filePath;
save.download = "Your file name here";
save.target = '_blank';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
For new Chrome update some time event is not working. for that following code will be use
var path= "your file path will be here";
var save = document.createElement('a');
save.href = filePath;
save.download = "Your file name here";
save.target = '_blank';
document.body.appendChild(save);
save.click();
document.body.removeChild(save);
Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child
There are three ways to fetch multiple rows returned by PDO statement.
The simplest one is just to iterate over PDOStatement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
another one is to fetch rows using fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
or, if you need to preprocess some data first, use the while loop and collect the data into array manually
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
and then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:
git rebase -i origin/master
This will bring up your text editor (-i
is for "interactive") with a file that looks like this:
pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done
Change all the pick
to squash
(or s
) except the first one:
pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done
Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.
Voila! Googling "git squashing" will give you explanations of all the other options available.
I had problems because my version of PHP (7.3) was expecting icu4c 63 and brew would only install 64.
https://stackoverflow.com/a/55828190/2000947 helped me install 63.
>
itself is very wonderful arrow! Just prepend a div with it and style it.
div{_x000D_
font-size:50px;_x000D_
}_x000D_
div::before{_x000D_
content:">";_x000D_
font: 50px 'Consolas';_x000D_
font-weight:900;_x000D_
}
_x000D_
<div class="arrowed">Hatz!</div>
_x000D_
This question is a bit tricky before Jan 2013 and matplotlib 1.3.1 (Aug 2013), which is the oldest stable version you can find on matpplotlib website. But after that it is quite trivial.
Because present version of matplotlib.pylab.scatter
support assigning: array of colour name string, array of float number with colour map, array of RGB or RGBA.
this answer is dedicate to @Oxinabox's endless passion for correcting the 2013 version of myself in 2015.
you have two option of using scatter command with multiple colour in a single call.
as pylab.scatter
command support use RGBA array to do whatever colour you want;
back in early 2013, there is no way to do so, since the command only support single colour for the whole scatter point collection. When I was doing my 10000-line project I figure out a general solution to bypass it. so it is very tacky, but I can do it in whatever shape, colour, size and transparent. this trick also could be apply to draw path collection, line collection....
the code is also inspired by the source code of pyplot.scatter
, I just duplicated what scatter does without trigger it to draw.
the command pyplot.scatter
return a PatchCollection
Object, in the file "matplotlib/collections.py" a private variable _facecolors
in Collection
class and a method set_facecolors
.
so whenever you have a scatter points to draw you can do this:
# rgbaArr is a N*4 array of float numbers you know what I mean
# X is a N*2 array of coordinates
# axx is the axes object that current draw, you get it from
# axx = fig.gca()
# also import these, to recreate the within env of scatter command
import matplotlib.markers as mmarkers
import matplotlib.transforms as mtransforms
from matplotlib.collections import PatchCollection
import matplotlib.markers as mmarkers
import matplotlib.patches as mpatches
# define this function
# m is a string of scatter marker, it could be 'o', 's' etc..
# s is the size of the point, use 1.0
# dpi, get it from axx.figure.dpi
def addPatch_point(m, s, dpi):
marker_obj = mmarkers.MarkerStyle(m)
path = marker_obj.get_path()
trans = mtransforms.Affine2D().scale(np.sqrt(s*5)*dpi/72.0)
ptch = mpatches.PathPatch(path, fill = True, transform = trans)
return ptch
patches = []
# markerArr is an array of maker string, ['o', 's'. 'o'...]
# sizeArr is an array of size float, [1.0, 1.0. 0.5...]
for m, s in zip(markerArr, sizeArr):
patches.append(addPatch_point(m, s, axx.figure.dpi))
pclt = PatchCollection(
patches,
offsets = zip(X[:,0], X[:,1]),
transOffset = axx.transData)
pclt.set_transform(mtransforms.IdentityTransform())
pclt.set_edgecolors('none') # it's up to you
pclt._facecolors = rgbaArr
# in the end, when you decide to draw
axx.add_collection(pclt)
# and call axx's parent to draw_idle()
Very interesting discussion thread, i also faced the same problem may be worse one because
So read the threads here and implemented my version, which helped me in pushing up my contents in iPad in landscape mode. Here is code ( this is not fool proof and all, but it fixed my issue) First u need to have a delegate in your custom cell class, which on editing begins, sends the textfield to ur viewcontroller and set the activefield = theTextField there
// IMPLEMENTED TO HANDLE LANDSCAPE MODE ONLY
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect aRect = myTable.frame;
CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
aRect.size.height -= kbSize.height+50;
// This will the exact rect in which your textfield is present
CGRect rect = [myTable convertRect:activeField.bounds fromView:activeField];
// Scroll up only if required
if (!CGRectContainsPoint(aRect, rect.origin) ) {
[myTable setContentOffset:CGPointMake(0.0, rect.origin.y) animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillHide:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
myTable.contentInset = contentInsets;
myTable.scrollIndicatorInsets = contentInsets;
NSDictionary* info = [aNotification userInfo];
CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
CGRect bkgndRect = activeField.superview.frame;
bkgndRect.size.height += kbSize.height;
[activeField.superview setFrame:bkgndRect];
[myTable setContentOffset:CGPointMake(0.0, 10.0) animated:YES];
}
-anoop4real
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view. Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
This is the problem with your $PATH:
/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin
.
$PATH
is where the shell searches for command files. Folders to search in need to be separated with a colon. And so you want /usr/local/mysql/bin/
in your path but instead it searches in /usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin
, which probably doesn't exist.
Instead you want ${PATH}:/usr/local/mysql/bin
.
So do export PATH=${PATH}:/usr/local/mysql/bin
.
If you want this to be run every time you open terminal put it in the file .bash_profile
, which is run when Terminal opens.
function doosomething ()
{
//Doo something
}
$(function () {
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
I know that there exists a command line option, -vm
, to specify the path to the executable of the Java runtime. This may be the same as in eclipse.ini.
Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.
That's the code I use:
<?php
$path="C:/foopath/";
$file="foofile.txt";
//read file contents
$content="
<h2>$file</h2>
<code>
<pre>".htmlspecialchars(file_get_contents("$path/$file"))."</pre>
</code>";
//display
echo $content;
?>
Keep in mind that if the user can modify $path or $file (for example via $_GET or $_POST), he/she will be able to see all your source files (danger!)
In the Html
<div id="AssignUniqueId" runat="server">.....BLAH......<div/>
In the code
public void Page_Load(object source, Event Args e)
{
if(Session["Something"] == "ShowDiv")
AssignUniqueId.Visible = true;
else
AssignUniqueID.Visible = false;
}
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
See javadoc
out = some stream ...
try
{
}
catch ( Exception cause )
{
cause . printStrackTrace ( new PrintStream ( out ) ) ;
}
You can use dd to extract arbitrary chunks of bytes.
For example,
dd skip=1234 count=5 bs=1
would copy bytes 1235 to 1239 from its input to its output, and discard the rest.
To just get the first five bytes from standard input, do:
dd count=5 bs=1
Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:
dd count=5 bs=1 if=filename
Note also that dd verbosely announces what it did, so to toss that away, do:
dd count=5 bs=1 2>&-
or
dd count=5 bs=1 2>/dev/null
You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:
var list = ["one", "two", "three", "four"];
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('List Test'),
),
body: new Center(
child: new Column( // Or Row or whatever :)
children: createChildrenTexts(),
),
),
));
}
List<Text> createChildrenTexts() {
/// Method 1
// List<Text> childrenTexts = List<Text>();
// for (String name in list) {
// childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
// }
// return childrenTexts;
/// Method 2
return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
}
Here's a potential solution that will set the width of the bookType column (i.e. format of the bookTypes value) based on the longest bookTypes value.
public class Test {
public static void main(String[] args) {
String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };
// Find length of longest bookTypes value.
int maxLengthItem = 0;
boolean firstValue = true;
for (String bookType : bookTypes) {
maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
firstValue = false;
}
// Display rows of data
for (int i = 0; i < bookTypes.length; i++) {
// Use %6.2 instead of %.2 so that decimals line up, assuming max
// book cost of $999.99. Change 6 to a different number if max cost
// is different
String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
System.out.printf(format, i + 1, bookTypes[i], costs[i]);
}
}
}
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype()
does) definitely check out the link.
It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.
IUser user = new User();
Just to spell out what has already been said in brief. I wanted to create an executable JAR file that included my dependencies along with my code. This worked for me:
(1) In the pom, under <build><plugins>, I included:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
<configuration>
<archive>
<manifest>
<mainClass>dk.certifikat.oces2.some.package.MyMainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
(2) Running mvn compile assembly:assembly produced the desired my-project-0.1-SNAPSHOT-jar-with-dependencies.jar in the project's target directory.
(3) I ran the JAR with java -jar my-project-0.1-SNAPSHOT-jar-with-dependencies.jar
You can remove unwanted menu items in Page_Load, like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Roles.IsUserInRole("Admin"))
{
MenuItemCollection menuItems = mTopMenu.Items;
MenuItem adminItem = new MenuItem();
foreach (MenuItem menuItem in menuItems)
{
if (menuItem.Text == "Roles")
adminItem = menuItem;
}
menuItems.Remove(adminItem);
}
}
I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.
#register a:link
{
color:#fffff;
}
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
Capture the image and resize it.
Bitmap image2 = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(image2);
String incident_ID = IncidentFormActivity.incident_id;
imagepath="/sdcard/RDMS/"+incident_ID+ x + ".PNG";
File file = new File(imagepath);
try {
double xFactor = 0;
double width = Double.valueOf(image2.getWidth());
Log.v("WIDTH", String.valueOf(width));
double height = Double.valueOf(image2.getHeight());
Log.v("height", String.valueOf(height));
if(width>height){
xFactor = 841/width;
}
else{
xFactor = 595/width;
}
Log.v("Nheight", String.valueOf(width*xFactor));
Log.v("Nweight", String.valueOf(height*xFactor));
int Nheight = (int) ((xFactor*height));
int NWidth =(int) (xFactor * width) ;
bm = Bitmap.createScaledBitmap( image2,NWidth, Nheight, true);
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bm.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
Note that this problem usually occure for two reasons:
1-Port 80 is busy.
2-Port 443 is busy.
For number one as the others said, you can kill Skype and SQL Serever Reporter from
Windows Task Manager>"Services" Tab>"Services..." Button.
But if it dosen't worked, it's probably because of port 443, so try this one:
If you use VMware, go to
Windows Task Manager>"Services" Tab>"Services..." Button, and find "VMware Workstation Server" service, double click on it and press "Stop" button.
There is no need to stop other VMware's services.
Then again try to run Apache
Try using the QueryDefs. Create the query with parameters. Then use something like this:
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")
qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
Yes you can! Just tested this and it works great, this is awesome! It still doesn't work with html, but it does with svg.
In my index.html I have:
<div id="test" style="content: url(test.svg); width: 200px; height: 200px;"></div>
And my test.svg looks like this:
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
<polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3"/>
</svg>
If you are using Java, you could just replace the x00 characters before the insert like following:
myValue.replaceAll("\u0000", "")
The solution was provided and explained by Csaba in following post:
https://www.postgresql.org/message-id/1171970019.3101.328.camel%40coppola.muc.ecircle.de
Respectively:
in Java you can actually have a "0x0" character in your string, and that's valid unicode. So that's translated to the character 0x0 in UTF8, which in turn is not accepted because the server uses null terminated strings... so the only way is to make sure your strings don't contain the character '\u0000'.
As such, it is desirable to split the dataset into train and test sets in a way that preserves the same proportions of examples in each class as observed in the original dataset.
This is called a stratified train-test split.
We can achieve this by setting the “stratify” argument to the y component of the original dataset. This will be used by the train_test_split() function to ensure that both the train and test sets have the proportion of examples in each class that is present in the provided “y” array.
You want:
answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer == "y" or answer == "Y":
print("this will do the calculation")
else:
exit()
Or
answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer in ["y","Y"]:
print("this will do the calculation")
else:
exit()
Note:
input
evals the input."a" or "b"
evaluates to "a"
, whereas 0 or "b"
evaluates to "b"
. See The Peculiar Nature of and and or.Use
$ java -XshowSettings
Property settings:
java.home = /home/nisar/javadev/javasuncom/jdk1.7.0_17/jre
java.io.tmpdir = /tmp
Simply \newpage
or \pagebreak
will work, e.g.
hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```
This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">
. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.
This shows you how to
DOM
Nodes
with XPath
Nodes
. We will call the code with the following statement
processFilteredXml(xmlIn, xpathExpr,(node) -> {/*Do something...*/;});
In our case we want to print some creatorNames
from a book.xml
using "//book/creators/creator/creatorName"
as xpath to perform a printNode
action on each Node that matches the XPath
.
Full code
@Test
public void printXml() {
try (InputStream in = readFile("book.xml")) {
processFilteredXml(in, "//book/creators/creator/creatorName", (node) -> {
printNode(node, System.out);
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private InputStream readFile(String yourSampleFile) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(yourSampleFile);
}
private void processFilteredXml(InputStream in, String xpath, Consumer<Node> process) {
Document doc = readXml(in);
NodeList list = filterNodesByXPath(doc, xpath);
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
process.accept(node);
}
}
public Document readXml(InputStream xmlin) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(xmlin);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NodeList filterNodesByXPath(Document doc, String xpathExpr) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object eval = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) eval;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void printNode(Node node, PrintStream out) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
out.println(xmlString);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Prints
<creatorName>Fosmire, Michael</creatorName>
<creatorName>Wertz, Ruth</creatorName>
<creatorName>Purzer, Senay</creatorName>
For book.xml
<book>
<creators>
<creator>
<creatorName>Fosmire, Michael</creatorName>
<givenName>Michael</givenName>
<familyName>Fosmire</familyName>
</creator>
<creator>
<creatorName>Wertz, Ruth</creatorName>
<givenName>Ruth</givenName>
<familyName>Wertz</familyName>
</creator>
<creator>
<creatorName>Purzer, Senay</creatorName>
<givenName>Senay</givenName>
<familyName>Purzer</familyName>
</creator>
</creators>
<titles>
<title>Critical Engineering Literacy Test (CELT)</title>
</titles>
</book>
If the previous answers fail, make sure you use @Service stereotype for the class where you call the update method on your repository. I originally used @Component instead and it was not working, the simple change to @Service made it work.
You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
.Range("A1") = "Acctdate"
.Range("B1") = "Ledger"
.Range("C1") = "CY"
.Range("D1") = "BusinessUnit"
.Range("E1") = "OperatingUnit"
.Range("F1") = "LOB"
.Range("G1") = "Account"
.Range("H1") = "TreatyCode"
.Range("I1") = "Amount"
.Range("J1") = "TransactionCurrency"
.Range("K1") = "USDEquivalentAmount"
.Range("L1") = "KeyCol"
.Range("A2", "A50000").Value = Me.TextBox3.Value
.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub
The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml
with you since these settings are user specific.
If you need to configure a proxy, have a look at the section about Proxies.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> ... <proxies> <proxy> <id>myproxy</id> <active>true</active> <protocol>http</protocol> <host>proxy.somewhere.com</host> <port>8080</port> <username>proxyuser</username> <password>somepassword</password> <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts> </proxy> </proxies> ... </settings>
id
: The unique identifier for this proxy. This is used to differentiate between proxy elements.active
: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.protocol, host, port
: The protocol://host:port of the proxy, seperated into discrete elements.username, password
: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.nonProxyHosts
: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common
<video autoplay muted="muted" loop id="myVideo">
<source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4">
</video>
Something like this
I have seen systems that use Reflection and attributes on Properties or fields to maps DataReaders to objects. (A bit like what LinqToSql does.) They save a bit of typing and may reduce the number of errors when coding for DBNull etc. Once you cache the generated code they can be faster then most hand written code as well, so do consider the “high road” if you are doing this a lot.
See "A Defense of Reflection in .NET" for one example of this.
You can then write code like
class CustomerDTO
{
[Field("id")]
public int? CustomerId;
[Field("name")]
public string CustomerName;
}
...
using (DataReader reader = ...)
{
List<CustomerDTO> customers = reader.AutoMap<CustomerDTO>()
.ToList();
}
(AutoMap(), is an extension method)
@Stilgar, thanks for a great comment
If are able to you are likely to be better of using NHibernate, EF or Linq to Sql, etc However on old project (or for other (sometimes valid) reasons, e.g. “not invented here”, “love of stored procs” etc) It is not always possible to use a ORM, so a lighter weight system can be useful to have “up your sleeves”
If you every needed too write lots of IDataReader loops, you will see the benefit of reducing the coding (and errors) without having to change the architecture of the system you are working on. That is not to say it’s a good architecture to start with..
I am assuming that CustomerDTO will not get out of the data access layer and composite objects etc will be built up by the data access layer using the DTO objects.
A few years after I wrote this answer Dapper entered the world of .NET, it is likely to be a very good starting point for writing your onw AutoMapper, maybe it will completely remove the need for you to do so.
Assuming self
is a UIViewController
:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
I think that you'll probably have to use $.ajax()
if you want to change the encoding, see the contentType
param below (the success
and error
callbacks assume you have <div id="success"></div>
and <div id="error"></div>
in the html):
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
I actually just had to do this about an hour ago, what a coincidence!
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
as per requested, here is the comment I gave earlier:
have a look at this:
this link should help you if you want to use monodevelop on a MacOSX
Good luck and happy coding.
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.
You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick
with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.
You can try of the following type :
#!/bin/bash
declare -a arr
i=0
j=0
for dir in $(find /home/rmajeti/programs -type d)
do
arr[i]=$dir
i=$((i+1))
done
while [ $j -lt $i ]
do
echo ${arr[$j]}
j=$((j+1))
done
There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:
rsync -av --exclude '*.svn' user@server:/my/dir .
(this line copy rsync from distant folder to current one)
Recent versions of rsync tunnel over an ssh connection automatically by default.
An alternative to numpy.correlate is available in statsmodels.tsa.stattools.acf(). This yields a continuously decreasing autocorrelation function like the one described by OP. Implementing it is fairly simple:
from statsmodels.tsa import stattools
# x = 1-D array
# Yield normalized autocorrelation function of number lags
autocorr = stattools.acf( x )
# Get autocorrelation coefficient at lag = 1
autocorr_coeff = autocorr[1]
The default behavior is to stop at 40 nlags, but this can be adjusted with the nlag=
option for your specific application. There is a citation at the bottom of the page for the statistics behind the function.
I was searching for how to do this on a much newer version of xcode than the original question and while the answers here got me where I needed to go, they aren't quite accurate for location anymore. Xcode 11.3.1, you need to go into Preferences -> Components, then select the desired Simulators. You can also select tvOS and watchOS similators from the same window.
I prefer using pip in case you are using virtualenv:
apt install libpython2.7 libpython2.7-dev
pip install psycopg2
I don't know if there's a way to get a clean build via the UI, but it's easy to do from the commandline using gradle wrapper. From the root directory of your project:
./gradlew clean
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
None of those worked for me, so I had three commits to revert (the last three commits), so I did:
git revert HEAD
git revert HEAD~2
git revert HEAD~4
git rebase -i HEAD~3 # pick, squash, squash
Worked like a charm :)
Key differences:
C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.
Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.
one-liner bash script to help facility Chris's answer above, as I had painted myself in a corner as well using Vundle updates to my .vim scripts. DEST
is the path to the directory containing your submodules. Do this after doing git rm -r $DEST
DEST='path'; for file in `ls ${DEST}`; do git submodule add `grep url ${DEST}/${file}/.git/config|awk -F= '{print $2}'` ${DEST}/${file}; done
cheers
import re
sentence = ' hello apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub(' ',' ',sentence) #hello world (remove double spaces)
As David pointed out, I would go with KB in most cases.
php_value post_max_size 2K
Note: my form is simple, just a few text boxes, not long text.
(PHP shorthand for KB is K, as outlined here.)
You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:
I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
Below's a pure python implementation of the desired functionality that handles any numeric series (int or float) with positive, negative, or mixed values and allows for the user to specify the desired step size:
import math
def computeTicks (x, step = 5):
"""
Computes domain with given step encompassing series x
@ params
x - Required - A list-like object of integers or floats
step - Optional - Tick frequency
"""
xMax, xMin = math.ceil(max(x)), math.floor(min(x))
dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
return range(dMin, dMax, step)
# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))
[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))
[-30, -25, -20, -15, -10, -5, 0]
# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))
[15, 20, 25, 30]
# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))
[0, 5, 10, 15, 20, 25]
# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))
[100, 200, 300, 400, 500, 600, 700, 800]
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()
Notice the x-axis has integer values all evenly spaced by 5, whereas the y-axis has a different interval (the matplotlib
default behavior, because the ticks weren't specified).
I'm using 7.1, and this worked for me:
Change the = to : to
fix the error.
var makeRequest = function(message) {<br>
var options = {<br>
host: 'localhost',<br>
port : 8080,<br>
path : '/',<br>
method: 'POST'<br>
}
Setting the CurrentCell
and then calling BeginEdit(true)
works well for me.
The following code shows an eventHandler for the KeyDown
event that sets a cell to be editable.
My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
{
e.Handled = true;
DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
dataGridView1.CurrentCell = cell;
dataGridView1.BeginEdit(true);
}
}
If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.
If you want to check for authenticated users in your template then:
{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}
With ECMAScript since 2015 you can use Spread Syntax ( …three dots):
let people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};
It's allow you to add sub objects:
people = { ...people, city: { state: 'California' }};
the result would be:
{
"id": 4,
"firstName": "John",
"secondName": "Forget",
"city": {
"state": "California"
}
}
You also can merge objects:
var mergedObj = { ...obj1, ...obj2 };
FUNCTION GETUNIQUEID_2 RETURN VARCHAR2
AS
v_curr_id NUMBER;
v_inc NUMBER;
v_next_val NUMBER;
pragma autonomous_transaction;
begin
CREATE SEQUENCE sequnce
START WITH YYMMDD0000000001
INCREMENT BY 1
NOCACHE
select sequence.nextval into v_curr_id from dual;
if(substr(v_curr_id,0,6)= to_char(sysdate,'yymmdd')) then
v_next_val := to_number(to_char(SYSDATE+1, 'yymmdd') || '0000000000');
v_inc := v_next_val - v_curr_id;
execute immediate ' alter sequence sequence increment by ' || v_inc ;
select sequence.nextval into v_curr_id from dual;
execute immediate ' alter sequence sequence increment by 1';
else
dbms_output.put_line('exception : file not found');
end if;
RETURN 'ID'||v_curr_id;
END;
It doesn't matter. In terms of REST, you can't do a GET, because it's not cacheable, but it doesn't matter if you use POST or PATCH or PUT or whatever, and it doesn't matter what the URL looks like. If you're doing REST, what matters is that when you get a representation of your resource from the server, that representation is able give the client state transition options.
If your GET response had state transitions, the client just needs to know how to read them, and the server can change them if needed. Here an update is done using POST, but if it was changed to PATCH, or if the URL changes, the client still knows how to make an update:
{
"customer" :
{
},
"operations":
[
"update" :
{
"method": "POST",
"href": "https://server/customer/123/"
}]
}
You could go as far as to list required/optional parameters for the client to give back to you. It depends on the application.
As far as business operations, that might be a different resource linked to from the customer resource. If you want to send an email to the customer, maybe that service is it's own resource that you can POST to, so you might include the following operation in the customer resource:
"email":
{
"method": "POST",
"href": "http://server/emailservice/send?customer=1234"
}
Some good videos, and example of the presenter's REST architecture are these. Stormpath only uses GET/POST/DELETE, which is fine since REST has nothing to do with what operations you use or how URLs should look (except GETs should be cacheable):
https://www.youtube.com/watch?v=pspy1H6A3FM,
https://www.youtube.com/watch?v=5WXYw4J4QOU,
http://docs.stormpath.com/rest/quickstart/
A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.
In Javascript, or more specifically jQuery, for example, you can specify a callback argument to be called when an animation has finished.
In PHP, the preg_replace_callback()
function allows you to provide a function that will be called when the regular expression is matched, passing the string(s) matched as arguments.
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
I just downloaded xlrd, created an excel document (excel 2007) for testing and got the same error (message says 'found PK\x03\x04\x14\x00\x06\x00'). Extension is a xlsx. Tried saving it to an older .xls format and error disappears .....
Although there isn’t complete agreement on the distinction between the terms parallel and concurrent, many authors make the following distinctions:
So parallel programs are concurrent, but a program such as a multitasking operating system is also concurrent, even when it is run on a machine with only one core, since multiple tasks can be in progress at any instant.
Source: An introduction to parallel programming, Peter Pacheco
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
See http://developer.android.com/reference/android/R.attr.html#state_above_anchor for a list of available states.
If you want to set colors for disabled, unfocused, unchecked states etc. just negate the states:
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.RED,
Color.GREEN,
Color.BLUE
};
ColorStateList myList = new ColorStateList(states, colors);
Unfortunately there's no min
(or max
)-background-size in CSS you can only use
background-size
. However if you are seeking a responsive background image you can use Vmin
and Vmax
units for the background-size
property to achieve something similar.
#one {
background:url('../img/blahblah.jpg') no-repeat;
background-size:10vmin 100%;
}
that will set the height to 10% of the whichever smaller viewport you have whether vertical or horizontal, and will set the width to 100%.
Read more about css units here: https://www.w3schools.com/cssref/css_units.asp
Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}
private void UpdateExcel(string sheetName, int row, int col, string data)
{
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];
oSheet.Cells[row, col] = data;
oWB.Save();
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (oWB != null)
oWB.Close();
}
}
To return a file or filepath
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path
Just my take on the matter, three months later:
Jenkins has continued the path well-trodden by the original Hudson with frequent releases including many minor updates.
Oracle seems to have largely delegated work on the future path for Hudson to the Sonatype team, who has performed some significant changes, especially with respect to Maven. They have jointly moved it to the Eclipse foundation.
I would suggest that if you like the sound of:
, then I would suggest Hudson.
Conversely, if you prefer:
then I would suggest Jenkins. (and as a commenter noted, Jenkins now also has "LTS" releases which are maintained on a more "stable" branch)
The conservative course would be to choose Hudson now and migrate to Jenkins if must-have features are unavailable. The dynamic course would be to choose Jenkins now and migrate to Hudson if chasing updates becomes too time-consuming to justify.
As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:
line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
i in line
>> True
>> True
According to OpenCV cheat-sheet this can be done as follows:
IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
The cv::cvarrToMat function takes care of the conversion issues.
Another nice little method is to include the current directory in your load path with
$:.unshift('.')
You could push it onto the $: ($LOAD_PATH) array but unshift will force it to load your current working directory before the rest of the load path.
Once you've added your current directory in your load path you don't need to keep specifying
require './tokenizer'
and can just go back to using
require 'tokenizer'
If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.
Tables
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
Then you just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
And you'll have
| ID | NAME | ------------------ | LHPL001 | Jhon | | LHPL002 | Mark |
Here is SQLFiddle demo
you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"
Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.
DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";
sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );
I had the same problem, but it didn't have anything to do with JavaScript. Consider this code:
<input id="hdnTest" type="hidden" value='<%= hdnValue %>' />
<asp:PlaceHolder ID="phWrapper" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="phContent" runat="server" Visible="false">
<b>test content</b>
</asp:PlaceHolder>
In this situation you'll get the same error even though PlaceHolders don't have any harmful code blocks, it happens because of the non-server control hdnTest uses code blocks.
Just add runat=server to the hdnTest and the problem is solved.
Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.
function ptr(get, set) {
return { get: get, set: set };
}
function helloWorld(namePtr) {
console.log(namePtr.get());
namePtr.set('jack');
console.log(namePtr.get())
}
var myName = 'joe';
var myNamePtr = ptr(
function () { return myName; },
function (value) { myName = value; }
);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
In ES6, the code can be shortened to use lambda expressions:
var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
Couldn't make any of the above routing solutions work -- some of the syntax seems to have changed and I'm still new to MVC -- in a pinch though I put together this really awful (and simple) hack which will get me by for now -- note, this replaces the "public MyObject GetMyObjects(long id)" method -- we change "id"'s type to a string, and change the return type to object.
// GET api/MyObjects/5
// GET api/MyObjects/function
public object GetMyObjects(string id)
{
id = (id ?? "").Trim();
// Check to see if "id" is equal to a "command" we support
// and return alternate data.
if (string.Equals(id, "count", StringComparison.OrdinalIgnoreCase))
{
return db.MyObjects.LongCount();
}
// We now return you back to your regularly scheduled
// web service handler (more or less)
var myObject = db.MyObjects.Find(long.Parse(id));
if (myObject == null)
{
throw new HttpResponseException
(
Request.CreateResponse(HttpStatusCode.NotFound)
);
}
return myObject;
}
https://developers.google.com/web/updates/2017/09/abortable-fetch
https://dom.spec.whatwg.org/#aborting-ongoing-activities
// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;
// fetch as usual
fetch(url, { signal }).then(response => {
...
}).catch(e => {
// catch the abort if you like
if (e.name === 'AbortError') {
...
}
});
// when you want to abort
controller.abort();
works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.
on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'
// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
throw $e->getMessage();
You try to throw a string
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
You're looking for http_build_query()
.
The correct way of referring to a method parameter is like this:
As some suggested here, replacing utf8mb4
with utf8
will help you resolve the issue. IMHO, I used sed
to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is
sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql
Done!
Using set elements ...
isn't always the best way. It would be useful if there were a distinct set string-elements ...
.
So, I use these functions in my .gdbinit:
define pstr
ptype $arg0._M_dataplus._M_p
printf "[%d] = %s\n", $arg0._M_string_length, $arg0._M_dataplus._M_p
end
define pcstr
ptype $arg0
printf "[%d] = %s\n", strlen($arg0), $arg0
end
Caveats:
rake tmp:cache:clear
might be what you're looking for.
I've never actually used this, but try view.getClass().getGenericSuperclass()
Short answer:
There is no difference in semantic.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
Further reading:
RequestMapping
can be used at class level:
This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
while GetMapping
only applies to method:
Annotation for mapping HTTP GET requests onto specific handler methods.
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
A different user name is the common cause for this, Nuget downloads everything into: "C:\Users\USER_NAME\source\repos"
and if you had the project previously setup on a different user name the .csproj file may still contain that old user name there, simply open it and do a search replace for "C:\Users\_OLD_USER_NAME\source\repos"
to "C:\Users\NEW_USER_NAME\source\repos"
.
The best way to accomplish this is to use the \r
character
Just try the below code:
import time
for n in range(500):
print(n, end='\r')
time.sleep(0.01)
print() # start new line so most recently printed number stays
As this question comes up first on Google I thought I'd share a solution using TigerVNC which is the default these days.
xrandr
allows selecting the display modes (a.k.a resolutions) however
due to modelines being hard
coded
any additional modeline such as "2560x1600" or "1600x900" would need to
be added into the
code. I
think the developers who wrote the code are much smarter and the hard
coded list is just a sample of values. It leads to the conclusion that
there must be a way to add custom modelines and man xrandr
confirms
it.
With that background if the goal is to share a VNC session between two computers with the above resolutions and assuming that the VNC server is the computer with the resolution of "1600x900":
Start a VNC session with a geometry matching the physical display:
$ vncserver -geometry 1600x900 :1
On the "2560x1600" computer start the VNC viewer (I prefer Remmina) and connect to the remote VNC session:
host:5901
Once inside the VNC session start up a terminal window.
Confirm that the new geometry is available in the VNC session:
$ xrandr
Screen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768
VNC-0 connected 1600x900+0+0 0mm x 0mm
1600x900 60.00 +
1920x1200 60.00
1920x1080 60.00
1600x1200 60.00
1680x1050 60.00
1400x1050 60.00
1360x768 60.00
1280x1024 60.00
1280x960 60.00
1280x800 60.00
1280x720 60.00
1024x768 60.00
800x600 60.00
640x480 60.00
and you'll notice the screen being quite small.
List the modeline (see xrandr article in ArchLinux wiki) for the "2560x1600" resolution:
$ cvt 2560 1600
# 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz
Modeline "2560x1600_60.00" 348.50 2560 2760 3032 3504 1600 1603 1609 1658 -hsync +vsync
or if the monitor is old get the GTF timings:
$ gtf 2560 1600 60
# 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz
Modeline "2560x1600_60.00" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync
Add the new modeline to the current VNC session:
$ xrandr --newmode "2560x1600_60.00" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync
In the above xrandr
output look for the display name on the second
line:
VNC-0 connected 1600x900+0+0 0mm x 0mm
Bind the new modeline to the current VNC virtual monitor:
$ xrandr --addmode VNC-0 "2560x1600_60.00"
Use it:
$ xrandr -s "2560x1600_60.00"
While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.
The identity table:
CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED
(
[intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
and the insert trigger:
-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS
BEGIN
DECLARE @intTrackerMessageId INT
DECLARE @intRowCount INT
SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)
SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1
INSERT INTO tblsysTrackerMessages(
[intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy])
SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy] FROM INSERTED;
SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END
//XAML Code
// ViewModel code
private CategoryModel _SelectedCategory;
public CategoryModel SelectedCategory
{
get { return _SelectedCategory; }
set
{
_SelectedCategory = value;
OnPropertyChanged("SelectedCategory");
}
}
private ObservableCollection<CategoryModel> _Categories;
public ObservableCollection<CategoryModel> Categories
{
get { return _Categories; }
set
{
_Categories = value;
_Categories.Insert(0, new CategoryModel()
{
CategoryId = 0,
CategoryName = " -- Select Category -- "
});
SelectedCategory = _Categories[0];
OnPropertyChanged("Categories");
}
}
use Firebase.getAuth()
. It returns the current state of the Firebase client. Otherwise the return value is null
Here are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency
dependencies {
checkstyle project(":module")
}
this error could happen, if module doesn't contain group and version, so in the module/build.gradle
just need to be specified
plugins {
id 'java-library'
}
group = "com.example"
version = "master-SNAPSHOT"
I recommend GPick:
sudo apt-get install gpick
Applications -> Graphics -> GPick
It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.
If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.
It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.
The type comes after the name in TypeScript, partly because types are optional.
So your line:
HTMLElement el = document.getElementById('content');
Needs to change to:
const el: HTMLElement = document.getElementById('content');
Back in 2013, the type HTMLElement
would have been inferred from the return value of getElementById
, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById
has changed from HTMLElement
to HTMLElement | null
. The change makes the type more correct, because you don't always find an element.
So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
I have included the types to demonstrate what happens when you run the code. The interesting bit is that el
has the narrower type HTMLElement
within the if
statement, due to you eliminating the possibility of it being null.
You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:
const el = document.getElementById('content');
if (el) {
const definitelyAnElement = el;
}
Put this line at the top of your source
# -*- coding: utf-8 -*-
If your editor uses a different encoding, substitute for utf-8
Then you can include utf-8 characters directly in the source
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
I have a similar problem and as I'm newbie, here are some facts for somebody to comment:
I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):
fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))
Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: The value in the second column is blocked:other and there is also an error in Console tab:
GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT
In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests:
My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).
If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes
You can animate the scrolltop of the page with jQuery.
$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
See this site: http://papermashup.com/jquery-page-scrolling/
I found this ans more pythonic
:
if type(aObject) is str:
#do your stuff here
pass
since type objects are singleton, is can be used to do the compare the object to the str type
To leave the cursor in the same column when you use Ctrl+D, Ctrl+F, Ctrl+B, Ctrl+U, G, H, M, L, gg
you should define the following option:
:set nostartofline
We can make transparent in dis way also.
White color code - FFFFFF
20% white - #33FFFFFF
20% — 33
70% white - #B3FFFFFF
70% — B3
All teh hex value from 100% to 0%
100% — FF, 99% — FC, 98% — FA, 97% — F7, 96% — F5, 95% — F2, 94% — F0, 93% — ED, 92% — EB, 91% — E8, 90% — E6, 89% — E3, 88% — E0, 87% — DE, 86% — DB, 85% — D9, 84% — D6, 83% — D4, 82% — D1, 81% — CF, 80% — CC, 79% — C9, 78% — C7, 77% — C4, 76% — C2, 75% — BF, 74% — BD, 73% — BA, 72% — B8, 71% — B5, 70% — B3, 69% — B0, 68% — AD, 67% — AB, 66% — A8, 65% — A6, 64% — A3, 63% — A1, 62% — 9E, 61% — 9C, 60% — 99, 59% — 96, 58% — 94, 57% — 91, 56% — 8F, 55% — 8C, 54% — 8A, 53% — 87, 52% — 85, 51% — 82, 50% — 80, 49% — 7D, 48% — 7A, 47% — 78, 46% — 75, 45% — 73, 44% — 70, 43% — 6E, 42% — 6B, 41% — 69, 40% — 66, 39% — 63, 38% — 61, 37% — 5E, 36% — 5C, 35% — 59, 34% — 57, 33% — 54, 32% — 52, 31% — 4F, 30% — 4D, 29% — 4A, 28% — 47, 27% — 45, 26% — 42, 25% — 40, 24% — 3D, 23% — 3B, 22% — 38, 21% — 36, 20% — 33, 19% — 30, 18% — 2E, 17% — 2B, 16% — 29, 15% — 26, 14% — 24, 13% — 21, 12% — 1F, 11% — 1C, 10% — 1A, 9% — 17, 8% — 14, 7% — 12, 6% — 0F, 5% — 0D, 4% — 0A, 3% — 08, 2% — 05, 1% — 03, 0% — 00
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
SHOW CREATE TABLE bar;
you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.
This will allow you to copy the indexes and also manually tweak the table creation.
You can also run the query within a program.
You can use it only in body tag or in tables. Something like this:
<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">
This worked for me.
Easy, \n
needs to be in the string.
// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
public int count = 0;
}
public boolean haveSameElements(final List<String> list1, final List<String> list2) {
// (list1, list1) is always true
if (list1 == list2) return true;
// If either list is null, or the lengths are not equal, they can't possibly match
if (list1 == null || list2 == null || list1.size() != list2.size())
return false;
// (switch the two checks above if (null, null) should return false)
Map<String, Count> counts = new HashMap<>();
// Count the items in list1
for (String item : list1) {
if (!counts.containsKey(item)) counts.put(item, new Count());
counts.get(item).count += 1;
}
// Subtract the count of items in list2
for (String item : list2) {
// If the map doesn't contain the item here, then this item wasn't in list1
if (!counts.containsKey(item)) return false;
counts.get(item).count -= 1;
}
// If any count is nonzero at this point, then the two lists don't match
for (Map.Entry<String, Count> entry : counts.entrySet()) {
if (entry.getValue().count != 0) return false;
}
return true;
}
There's no difference between these two things. Think about it.
Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?
There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.
It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).
The canvas
element provides a toDataURL
method which returns a data:
URL that includes the base64-encoded image data in a given format. For example:
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.
The toDataURL
method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.
For more information see the MDN docs on the canvas
API, which includes details on toDataURL
, and the Wikipedia article on the data:
URI scheme, which includes details on the format of the URI you'll receive from this call.
This may be cleaner (you dont need all the into
statements):
var query =
from order in dc.Orders
from vendor
in dc.Vendors
.Where(v => v.Id == order.VendorId)
.DefaultIfEmpty()
from status
in dc.Status
.Where(s => s.Id == order.StatusId)
.DefaultIfEmpty()
select new { Order = order, Vendor = vendor, Status = status }
//Vendor and Status properties will be null if the left join is null
Here is another left join example
var results =
from expense in expenseDataContext.ExpenseDtos
where expense.Id == expenseId //some expense id that was passed in
from category
// left join on categories table if exists
in expenseDataContext.CategoryDtos
.Where(c => c.Id == expense.CategoryId)
.DefaultIfEmpty()
// left join on expense type table if exists
from expenseType
in expenseDataContext.ExpenseTypeDtos
.Where(e => e.Id == expense.ExpenseTypeId)
.DefaultIfEmpty()
// left join on currency table if exists
from currency
in expenseDataContext.CurrencyDtos
.Where(c => c.CurrencyID == expense.FKCurrencyID)
.DefaultIfEmpty()
select new
{
Expense = expense,
// category will be null if join doesn't exist
Category = category,
// expensetype will be null if join doesn't exist
ExpenseType = expenseType,
// currency will be null if join doesn't exist
Currency = currency
}
If you specifically want to use an ad hoc wireless network, then Andy's answer seems to be your only option. However, if you just want to share your laptop's internet connection via Wi-fi using any means necessary, then you have at least two more options:
*Some phones with Android 2.3 have proprietary OS extensions that enable Wi-fi Direct (mostly newer Samsung phones), but Android 4 should fully support this (source).
If you want a "rotating" progress bar, why not set the progress bar style to "Marquee" and using a BackgroundWorker
to keep the UI responsive? You won't achieve a rotating progress bar easier than using the "Marquee" - style...
CMake 3.X offers a 'clean' target.
cmake --build C:/foo/build/ --target clean
From the CMake docs for 3.0.2:
--clean-first = Build target 'clean' first, then build.
(To clean only, use --target 'clean'.)
There is no cmake clean
in CMake version 2.X
I usually build the project in a single folder like "build". So if I want to make clean
, I can just rm -rf build
.
The "build" folder in the same directory as the root "CMakeLists.txt" is usually a good choice. To build your project, you simply give cmake the location of the CMakeLists.txt as an argument. For example: cd <location-of-cmakelists>/build && cmake ..
. (From @ComicSansMS)
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
You should use Javascript animations for this - it is not possible in pure CSS, because you can't know the height of any element. Follow the instructions it has for you about javascript animation implementation, and copy slideUp and slideDown from jQuery's source.
This is another way. In my case I have:
Inside the button I have this code:
Image myImage = Image.FromFile(@"C:\imagenes\myImage.gif");
Bitmap croppedBitmap = new Bitmap(myImage);
croppedBitmap = croppedBitmap.Clone(
new Rectangle(
(int)LeftMargin.Value, (int)TopMargin.Value,
myImage.Width - (int)LeftMargin.Value,
myImage.Height - (int)TopMargin.Value),
System.Drawing.Imaging.PixelFormat.DontCare);
pictureBox1.Image = croppedBitmap;
I tried it in Visual studio 2012 using C#. I found this solution from this page
Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.
Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.
Create PROCEDURE userInfoProcedure
-- Add the parameters for the stored procedure here
@FirstName varchar,
@LastName varchar
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT FirstName , LastName,Age from UserInfo where FirstName=@FirstName
and LastName=@FirstName
END
GO
http://www.totaldotnet.com/Article/ShowArticle121_StoreProcBasic.aspx
Remove display: block;
in the div #tfl
style property
<div id="tfl" style="display: block; width: 187px; height: 260px;
Inline style take priority then css file
<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button type='button' id='submit_btn'>Submit</button>
</form>
<script>
$(document).on("click", "#submit_btn", function (e) {
//Prevent Instant Click
e.preventDefault();
// Create an FormData object
var formData = $("#form").submit(function (e) {
return;
});
//formData[0] contain form data only
// You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here -->)
var formData = new FormData(formData[0]);
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data: formData,
success: function (response) {
console.log(response);
},
contentType: false,
processData: false,
cache: false
});
return false;
});
</script>
///// otherpage.php
<?php
print_r($_FILES);
?>
Or you can simply use PRINT
command instead of SELECT
command. Try this,
PRINT dbo.fn_HomePageSlider(9, 3025)
I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!
Example:
SQLQueryString = $"
Insert into Employee values(
{txtEmployeeNo},
{txtContractsStartDate},
{txtSeatNo},
{txtFloor},
{txtLeaves}
)"
It works. Documentation Here
Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.
<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
<TR style="vertical-align:top">
<TD>
<!-- The log text-box -->
<div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
Log:
</div>
</TD>
<TD>
<!-- The 2nd column -->
</TD>
<TD>
<!-- The 3rd column -->
</TD>
</TR>
</TABLE>
I was using CMake to compile my project and I've found the same problem.
The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call
If you want to be able to reuse the function in the future then this works well based on ed Hopp's code above (I realize that the original question didn't call for this extra feature!):
var something = (function() {
var executed = false;
return function(value) {
// if an argument is not present then
if(arguments.length == 0) {
if (!executed) {
executed = true;
//Do stuff here only once unless reset
console.log("Hello World!");
}
else return;
} else {
// otherwise allow the function to fire again
executed = value;
return;
}
}
})();
something();//Hello World!
something();
something();
console.log("Reset"); //Reset
something(false);
something();//Hello World!
something();
something();
The output look like:
Hello World!
Reset
Hello World!
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
take a look at xp_sprintf. example below.
DECLARE @ret_string varchar (255)
EXEC xp_sprintf @ret_string OUTPUT,
'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
PRINT @ret_string
Result looks like this:
INSERT INTO table1 VALUES (1, 2)
Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:
create function dbo.fnSprintf (@s varchar(MAX),
@params varchar(MAX), @separator char(1) = ',')
returns varchar(MAX)
as
begin
declare @p varchar(MAX)
declare @paramlen int
set @params = @params + @separator
set @paramlen = len(@params)
while not @params = ''
begin
set @p = left(@params+@separator, charindex(@separator, @params)-1)
set @s = STUFF(@s, charindex('%s', @s), 2, @p)
set @params = substring(@params, len(@p)+2, @paramlen)
end
return @s
end
To get the same result as above you call the function as follows:
print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)
This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row">
with container
class. Cause container
class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.
So just start writing <div class="row">
without container class and you are ready to go with 100% width layout.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Basic 100% width Structure</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
<script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-3 red">Test content</div>
<div class="col-md-9 green">Another Content</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here
Reply me if you need more further assistance. Thanks.
Here's a project that combines the best parts (pros) of both redux-saga
and redux-thunk
: you can handle all side-effects on sagas while getting a promise by dispatching
the corresponding action:
https://github.com/diegohaz/redux-saga-thunk
class MyComponent extends React.Component {
componentWillMount() {
// `doSomething` dispatches an action which is handled by some saga
this.props.doSomething().then((detail) => {
console.log('Yaay!', detail)
}).catch((error) => {
console.log('Oops!', error)
})
}
}
You can try :
DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```
A simple solution if you want to check unique values ??in an indefinite number of parameters using es6.
function uniteUnique(arr, ...rest) {
const newArr = arr.concat(rest).flat()
return [...new Set(newArr)]
}
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]))
console.log(uniteUnique([1, 2, 3], [5, 2, 1]))
I hope it will be useful to someone.
This will work:
var cycles = cycleSource.AllCycles();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var vm = new JArray();
foreach (var cycle in cycles)
{
var cycleJson = JObject.FromObject(cycle);
// extend cycleJson ......
vm.Add(cycleJson);
}
return vm;
If you're using JUnit, have a look at junit-addons. It has the ability to ignore the Java security model and access private methods and attributes.
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
I think you have answered your own question with
Runtime.getRuntime().exec(myShellScript);
As to whether it is good practice... what are you trying to do with a shell script that you cannot do with Java?
Because responsive units aren't available in react-native at the moment, I would say your best bet would be to detect the screen size and then use that to infer the device type and set the fontSize conditionally.
You could write a module like:
function fontSizer (screenWidth) {
if(screenWidth > 400){
return 18;
}else if(screenWidth > 250){
return 14;
}else {
return 12;
}
}
You'll just need to look up what the default width and height are for each device. If width and height are flipped when the device changes orientation you might be able to use aspect ratio instead or just figure out the lesser of the two dimensions to figure out width.
This module or this one can help you find device dimensions or device type.
I'm sure git subtree is all fine and wonderful, but my subdirectories of git managed code that I wanted to move was all in eclipse. So if you're using egit, it's painfully easy. Take the project you want to move and team->disconnect it, and then team->share it to the new location. It will default to trying to use the old repo location, but you can uncheck the use-existing selection and pick the new place to move it. All hail egit.
The traditional way to specify quotes is to use Chr(34)
. This is error resistant and is not an abomination.
Chr(34) & "string" & Chr(34)
No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.
final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
For me, I was trying to match on the /
in a date in C#. I did it just by using (\/)
:
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/)
.
If you either want the string
or an empty string
in case something is null, without anything can break:
using (var cmd = new OdbcCommand(cmdText, connection))
{
var result = string.Empty;
var scalar = cmd.ExecuteScalar();
if (scalar != DBNull.Value) // Case where the DB value is null
{
result = Convert.ToString(scalar); // Case where the query doesn't return any rows.
// Note: Convert.ToString() returns an empty string if the object is null.
// It doesn't break, like scalar.ToString() would have.
}
return result;
}
Beware when comparing a .Net DateTime to SqlDateTime.MinValue or MaxValue. For example, the following will throw an exception:
DateTime dte = new DateTime(1000, 1, 1);
if (dte >= SqlDateTime.MinValue)
//do something
The reason is that MinValue returns a SqlDateTime, not a DateTime. So .Net tries to convert dte to a SqlDateTime for comparison and because it's outside the acceptable SqlDateTime range it throws the exception.
One solution to this is to compare your DateTime to SqlDateTime.MinValue.Value.
To access the first and last elements, try.
var nodes = div.querySelectorAll('[move_id]');
var first = nodes[0];
var last = nodes[nodes.length- 1];
For robustness, add index checks.
Yes, the order of nodes is pre-order depth-first. DOM's document order
is defined as,
There is an ordering, document order, defined on all the nodes in the document corresponding to the order in which the first character of the XML representation of each node occurs in the XML representation of the document after expansion of general entities. Thus, the document element node will be the first node. Element nodes occur before their children. Thus, document order orders element nodes in order of the occurrence of their start-tag in the XML (after expansion of entities). The attribute nodes of an element occur after the element and before its children. The relative order of attribute nodes is implementation-dependent.
Roll your own e.g.
function syncJSON(i_url, callback) {
$.ajax({
type: "POST",
async: false,
url: i_url,
contentType: "application/json",
dataType: "json",
success: function (msg) { callback(msg) },
error: function (msg) { alert('error : ' + msg.d); }
});
}
syncJSON("/pathToYourResouce", function (msg) {
console.log(msg);
})
I created a workaround with directive:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
And the input tag becomes:
<input type="file" fileread="vm.uploadme" />
Or if just the file definition is needed:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup
event, as suggested, and use a regular expression to ensure the value is as you require:
<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
function formatTextArea(textArea) {
textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
}
window.onload = function() {
var textArea = document.getElementById("t");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 13) {
formatTextArea(this);
}
};
};
</script>
I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.
Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.
In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.
This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.
OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory
Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx
More details on how to set the OnKeyListener, and have it listen for the Done button.
First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:
/*
* Respond to soft keyboard events, look for the DONE press on the password field.
*/
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER))
{
// Done pressed! Do something here.
}
// Returning false allows other listeners to react to the press.
return false;
}
Given an EditText object:
EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);
You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence %2B
in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.
Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.
I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).
One thing that will be confusing here... Technically, the %
"should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.
Also, if you have Toad for Oracle, you can highlight the statement and press CTRL + F9 and you'll get a nice view of column and their datatypes.
Nine years later. If you know your time zone. I like the T
between date and time. And if you don't want microseconds.
Python <= 3.8
pip3 install pytz # needed!
python3
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:23:28+01:00'
Tested on Ubuntu 18.04 and Python 3.6.9.
Python >= 3.9
pip3 install tzdata # only on Windows needed!
py -3
>>> import datetime
>>> import zoneinfo
>>> datetime.datetime.now(zoneinfo.ZoneInfo('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:39:36+01:00'
Tested on Windows 10 and Python 3.9.0.
Here is the Answer
CSS
#outer
{
width:100%;
text-align: center;
}
.inner
{
display: inline-block;
}
HTML
<div id="outer">
<div class="inner"><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
<div class="inner"><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
<div class="inner"><button class="msgBtnBack">Back</button></div>
</div>
This worked for me.
bundle config --global build.snappy --with-opt-dir="$(brew --prefix snappy)"
I think it's safer to cache credentials, instead of store forever:
git config --global credential.helper 'cache --timeout=10800'
now you can enter your username and password(git pull
or ...), and keep using git for next 3 hours.
nice and safe.
Timeout is in seconds(3 hours in the example).
The html() function can take strings of HTML, and will effectively modify the .innerHTML
property.
$('#regTitle').html('Hello World');
However, the text() function will change the (text) value of the specified element, but keep the html
structure.
$('#regTitle').text('Hello world');
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Use RegEx for string match or comparison.
In JavaScript, you can use match()
for string comparison,
don't forget to put i
in RegEx.
Example:
var matchString = "Test";
if (matchString.match(/test/i)) {
alert('String matched');
}
else {
alert('String not matched');
}
I found this post and I have just posted something on my blog that might help.
See Setting up a Msysgit Server with copSSH on Windows. It's long, but I have successfully got this working on Windows 7 Ultimate x64.
I was getting the same "cannot find symbol" error when I did Build -> Make Project
. I fixed this by deleting my Maven /target
folder, right clicking my project module and doing Maven -> Reimport
, and doing Build -> Rebuild Project
. This was on IntelliJ Idea 13.1.5.
It turns out the Maven -> Reimport
was key, since the problem resurfaced a few times before I finally did that.
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
You can use this query to do the above task:
DECLARE @test NVARCHAR(max)
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test
SELECT field2 = @test
For detail and step by step explanation visit the following link http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html