This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump
:
objdump -d program
This should give you its dissassembly. You can add -S
if you want it source-annotated.
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
Mostly for my own reference, here's how you get it from a private key generated by ssh-keygen
openssl rsa -text -noout -in ~/.ssh/id_rsa
Of course, this only works with the private key.
This is issue has almost driven me nut in the past. To buttress what others have said, after making sure that all the indentations on the yaml file has been corrected and the problem persist, run a 'flutter clean' command at the terminal in Android studio. As at flutter 1.9, this should fix the issue.
Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.
So instead, you can use the xhr2 module. In other words:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
becomes:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
But ... of course, there are more popular modules like Axios, because -for example- uses promises:
// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
In [34]: import pandas as pd
In [35]: import numpy as np
In [36]: df = pd.DataFrame([1,2,3,4], columns=["data"])
In [37]: df
Out[37]:
data
0 1
1 2
2 3
3 4
In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")
In [39]: df
Out[39]:
data desired_output
0 1 False
1 2 False
2 3 True
3 4 True
It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:
Returns true if this collection contains all of the elements in the specified collection.
So if an ArrayList is being passed in you can call this method to see if they are exactly the same.
List foo = new ArrayList();
List bar = new ArrayList();
String str = "foobar";
foo.add(str);
bar.add(str);
foo.containsAll(bar);
The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.
EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.
The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).
So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.
My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.
I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".
Guido has tweeted about this:
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
An empty static class is appropriate. Consider using several classes, so that you end up with good groups of related constants, and not one giant Globals.cs file.
Additionally, for some int constants, consider the notation:
[Flags]
enum Foo
{
}
As this allows for treating the values like flags.
Could you just draw an svg path inside of a span using document.write? The span isn't required for the svg to work, it just ensures that the svg remains inline with whatever text the carat is next to. I used margin-bottom to vertically center it with the text, there might be another way to do that though. This is what I did on my blog's side nav (minus the js). If you don't have text next to it you wouldn't need the span or the margin-bottom offset.
<div id="ID"></div>
<script type="text/javascript">
var x = document.getElementById('ID');
// your "margin-bottom" is the negative of 1/2 of the font size (in this example the font size is 16px)
// change the "stroke=" to whatever color your font is too
x.innerHTML = document.write = '<span><svg style="margin-bottom: -8px; height: 30px; width: 25px;" viewBox="0,0,100,50"><path fill="transparent" stroke-width="4" stroke="black" d="M20 10 L50 40 L80 10"/></svg></span>';
</script>
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
After 4 hours, of trying everything... Windows 2008 R2 the files were green in Window Explorer. The files were marked for encryption and arching that came from the zip file. unchecking those options in the file property fixed the issue for me.
If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys
:
theTypeIs = Object.keys(myVar)[0];
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
In one line, using a lambda
:
timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)
Passing a function to list.sort
:
def foo(x):
return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]
timestamps.sort(key=foo, reverse=True)
Adding to @Mike's answer. I also needed double tap to restore the image to the original dimensions when first viewed. So I added a whole heap of "orig..." instance variables and added the SimpleOnGestureListener which did the trick.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class TouchImageView extends ImageView {
Matrix matrix = new Matrix();
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;
float redundantXSpace, redundantYSpace, origRedundantXSpace, origRedundantYSpace;;
float width, height;
static final int CLICK = 3;
static final float SAVE_SCALE = 1f;
float saveScale = SAVE_SCALE;
float right, bottom, origWidth, origHeight, bmWidth, bmHeight, origScale, origBottom,origRight;
ScaleGestureDetector mScaleDetector;
GestureDetector mGestureDetector;
Context context;
public TouchImageView(Context context) {
super(context);
super.setClickable(true);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix.setTranslate(1f, 1f);
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean onDoubleTapEvent = mGestureDetector.onTouchEvent(event);
if (onDoubleTapEvent) {
// Reset Image to original scale values
mode = NONE;
bottom = origBottom;
right = origRight;
last = new PointF();
start = new PointF();
m = new float[9];
saveScale = SAVE_SCALE;
matrix = new Matrix();
matrix.setScale(origScale, origScale);
matrix.postTranslate(origRedundantXSpace, origRedundantYSpace);
setImageMatrix(matrix);
invalidate();
return true;
}
mScaleDetector.onTouchEvent(event);
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float scaleWidth = Math.round(origWidth * saveScale);
float scaleHeight = Math.round(origHeight * saveScale);
if (scaleWidth < width) {
deltaX = 0;
if (y + deltaY > 0)
deltaY = -y;
else if (y + deltaY < -bottom)
deltaY = -(y + bottom);
} else if (scaleHeight < height) {
deltaY = 0;
if (x + deltaX > 0)
deltaX = -x;
else if (x + deltaX < -right)
deltaX = -(x + right);
} else {
if (x + deltaX > 0)
deltaX = -x;
else if (x + deltaX < -right)
deltaX = -(x + right);
if (y + deltaY > 0)
deltaY = -y;
else if (y + deltaY < -bottom)
deltaY = -(y + bottom);
}
matrix.postTranslate(deltaX, deltaY);
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true; // indicate event was handled
}
});
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return true;
}
});
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
bmWidth = bm.getWidth();
bmHeight = bm.getHeight();
}
public void setMaxZoom(float x) {
maxScale = x;
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = (float) Math.min(
Math.max(.95f, detector.getScaleFactor()), 1.05);
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
right = width * saveScale - width
- (2 * redundantXSpace * saveScale);
bottom = height * saveScale - height
- (2 * redundantYSpace * saveScale);
if (origWidth * saveScale <= width
|| origHeight * saveScale <= height) {
matrix.postScale(mScaleFactor, mScaleFactor, width / 2,
height / 2);
if (mScaleFactor < 1) {
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
if (mScaleFactor < 1) {
if (Math.round(origWidth * saveScale) < width) {
if (y < -bottom)
matrix.postTranslate(0, -(y + bottom));
else if (y > 0)
matrix.postTranslate(0, -y);
} else {
if (x < -right)
matrix.postTranslate(-(x + right), 0);
else if (x > 0)
matrix.postTranslate(-x, 0);
}
}
}
} else {
matrix.postScale(mScaleFactor, mScaleFactor,
detector.getFocusX(), detector.getFocusY());
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
if (mScaleFactor < 1) {
if (x < -right)
matrix.postTranslate(-(x + right), 0);
else if (x > 0)
matrix.postTranslate(-x, 0);
if (y < -bottom)
matrix.postTranslate(0, -(y + bottom));
else if (y > 0)
matrix.postTranslate(0, -y);
}
}
return true;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
// Fit to screen.
float scale;
float scaleX = (float) width / (float) bmWidth;
float scaleY = (float) height / (float) bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
setImageMatrix(matrix);
saveScale = SAVE_SCALE;
origScale = scale;
// Center the image
redundantYSpace = (float) height - (scale * (float) bmHeight);
redundantXSpace = (float) width - (scale * (float) bmWidth);
redundantYSpace /= (float) 2;
redundantXSpace /= (float) 2;
origRedundantXSpace = redundantXSpace;
origRedundantYSpace = redundantYSpace;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = width - 2 * redundantXSpace;
origHeight = height - 2 * redundantYSpace;
right = width * saveScale - width - (2 * redundantXSpace * saveScale);
bottom = height * saveScale - height
- (2 * redundantYSpace * saveScale);
origRight = right;
origBottom = bottom;
setImageMatrix(matrix);
}
}
var token = 'spo';
switch(token){
case ( (token.match(/spo/) )? token : undefined ) :
console.log('MATCHED')
break;;
default:
console.log('NO MATCH')
break;;
}
--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case
--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.
The ternary test can be anything for instance in your case
( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined
===========================================
(token.match(/spo/) )? token : undefined )
is a ternary expression.
The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).
If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).
Obviously token === token so the switch statement is matched and the case evaluated
It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.
Use related name to count votes for a specific contest
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
contest = models.ForeignKey(Contest, related_name="contest_votes")
comment = models.TextField()
>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()
rdtsc solution did not work for me.
Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.
Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.
I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk
This fixed the issue for me.
Usual way to empty textbox using jquery is:
$('#txtInput').val('');
If above code is not working than please check that you are able to get the input element.
console.log($('#txtInput')); // should return element in the console.
If still facing the same problem, please post your code.
A lot of answers, not the simple one.
To check if a index 'id' exists at dictionary dict:
dic = {}
dic['name'] = "joao"
dic['age'] = "39"
if 'age' in dic
returns true if 'age' exists.
I had the same problem. It was caused because I compiled the Boost with the Visual C++ 2010(v100) and I tried to use the library with the Visual Studio 2012 (v110) by mistake.
So, I changed the configurations (in Visual Studio 2012) going to Project properties -> General -> Plataform Toolset and change the value from Visual Studio 2012 (v110) to Visual Studio 2010 (v100).
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
I found easiest solution.
@XmlElement(name="attribute")
public String[] getAttributes(){
return attributes.keySet().toArray(new String[1]);
}
}
Now it will generate in you xml output like this:
<attribute>key1<attribute>
...
<attribute>keyN<attribute>
I don't understand the need of having private setters which started with C# 2.
For example, the invoice class allows the user to add or remove items from the Items property but it does not allow the user from changing the Items reference (ie, the user cannot assign Items property to another item list object instance).
public class Item
{
public string item_code;
public int qty;
public Item(string i, int q)
{
this.item_code = i;
this.qty = q;
}
}
public class Invoice
{
public List Items { get; private set; }
public Invoice()
{
this.Items = new List();
}
}
public class TestInvoice
{
public void Test()
{
Invoice inv = new Invoice();
inv.Items.Add(new Item("apple", 10));
List my_items = new List();
my_items.Add(new Item("apple", 10));
inv.Items = my_items; // compilation error here.
}
}
You can use this function instead if curl is installed on your system:
function get_url_contents($url){
if (function_exists('file_get_contents')) {
$result = @file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
A simplest working example based on the other answers is the following:
from flask import Flask, request
app = Flask(__name__, static_url_path='')
@app.route('/index/')
def root():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run(debug=True)
With the HTML called index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<div>
<p>
This is a test.
</p>
</div>
</body>
</html>
IMPORTANT: And index.html is in a folder called static, meaning <projectpath>
has the .py
file, and <projectpath>\static
has the html
file.
If you want the server to be visible on the network, use app.run(debug=True, host='0.0.0.0')
EDIT: For showing all files in the folder if requested, use this
@app.route('/<path:path>')
def static_file(path):
return app.send_static_file(path)
Which is essentially BlackMamba
's answer, so give them an upvote.
easy
// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );
Nathan's answer will give you jokes from last 24, 168, and 744 hours, NOT the jokes from today, this week, this month. If that's what you want, great, but I think you might be looking for something different.
Using his code, at noon, you will get the jokes beginning yesterday at noon, and ending today at noon. If you really want today's jokes, try the following:
SELECT * FROM jokes WHERE date >= CURRENT_DATE() ORDER BY score DESC;
You would have to do something a little different from current week, month, etc., but you get the idea.
simply type in which git
in your terminal window and it will show you exactly where it was installed.
You have to check your quotes
properly,
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
I have a simpler answer, which works perfectly for days; for months, it's +-2 days:
let today=new Date();
const days_to_subtract=30;
let new_date= new Date(today.valueOf()-(days_to_subtract*24*60*60*1000));
You get the idea - for months, multiply by 30; but that will be +-2 days.
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
See the documentation events section
Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".
Version 4.0 +
Events are now in format: select2:selecting
(instead of select2-selecting
)
Thanks to snakey for the notification that this has changed as of 4.0
$('#yourselect').on("select2:selecting", function(e) {
// what you would like to happen
});
Version Before 4.0
$('#yourselect').on("select2-selecting", function(e) {
// what you would like to happen
});
Just to clarify, the documentation for select2-selecting
reads:
select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()
whereas change has:
change Fired when selection is changed.
So change
may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.
in my case, I reinstall all packages installed with Homebrew
$ brew list | xargs brew reinstall
After that, I start to install my version that I need
I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:
double dblInteger;
if( dblNumber < 0 )
dblInteger = Math.Ceiling(dblNumber);
else
dblInteger = Math.Floor(dblNumber);
Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.
Janky at best
<a href="file://///server/folders/x/x/filename.ext">right click </a></td>
and then right click, select "copy location" option, and then paste into url.
The following works for Python 2.7. Save this script and launch it:
https://raw.github.com/pypa/pip/master/contrib/get-pip.py
Pip is installed, then add the path to your environment :
C:\Python27\Scripts
Finally
pip install virtualenv
Also you need Microsoft Visual C++ 2008 Express to get the good compiler and avoid these kind of messages when installing packages:
error: Unable to find vcvarsall.bat
If you have a 64-bit version of Windows 7, you may read 64-bit Python installation issues on 64-bit Windows 7 to successfully install the Python executable package (issue with registry entries).
The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:
User Pinch Zooms and controls appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP
User Pinch Zoom and Controls don't appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP
Can you shed more light on your solution?
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);
Use [[:blank:]]
to match any kind of horizontal white_space characters.
gsub("[[:blank:]]", "", " xx yy 11 22 33 ")
# [1] "xxyy112233"
lines
is a list. re.findall()
doesn't take lists.
>>> import re
>>> f = open('README.md', 'r')
>>> lines = f.readlines()
>>> match = re.findall('[A-Z]+', lines)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
>>> type(lines)
<type 'list'>
From help(file.readlines)
. I.e. readlines()
is for loops/iterating:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
To find all uppercase characters in your file:
>>> import re
>>> re.findall('[A-Z]+', open('README.md', 'r').read())
['S', 'E', 'A', 'P', 'S', 'I', 'R', 'C', 'I', 'A', 'P', 'O', 'G', 'P', 'P', 'T', 'V', 'W', 'V', 'D', 'A', 'L', 'U', 'O', 'I', 'L', 'P', 'A', 'D', 'V', 'S', 'M', 'S', 'L', 'I', 'D', 'V', 'S', 'M', 'A', 'P', 'T', 'P', 'Y', 'C', 'M', 'V', 'Y', 'C', 'M', 'R', 'R', 'B', 'P', 'M', 'L', 'F', 'D', 'W', 'V', 'C', 'X', 'S']
These answers actually dissuaded me from trying the simplest possible thing! Simply specify a threshold for an appender (say, "console") in your log4j.configuration
like so:
log4j.appender.console.threshold=${my.logging.threshold}
Then, on the command line, include the system property -Dlog4j.info -Dmy.logging.threshold=INFO
. I assume that any other property can be parameterized in this way, but this is the easiest way to raise or lower the logging level globally.
This worked for me on Windows
add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file
$file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';
$file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';
$file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';
$command = 'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
$result = exec($command);
Try using ReadAsStringAsync() instead.
var foo = resp.Content.ReadAsStringAsync().Result;
The reason why it ReadAsAsync<string>()
doesn't work is because ReadAsAsync<>
will try to use one of the default MediaTypeFormatter
(i.e. JsonMediaTypeFormatter
, XmlMediaTypeFormatter
, ...) to read the content with content-type
of text/plain
. However, none of the default formatter can read the text/plain
(they can only read application/json
, application/xml
, etc).
By using ReadAsStringAsync()
, the content will be read as string regardless of the content-type.
Since he specified Windows, where awk & sed aren't standard:
for /f "tokens=1*" %e in ('svn status^|findstr "^\?"') do svn add "%f"
or in a batch file:
for /f "tokens=1*" %%e in ('svn status^|findstr "^\?"') do svn add "%%f"
Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...
my $size=1234;
sub sub1{
$_[0]=500;
}
sub1 $size;
Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:
sub sub2{
my @m=@_;
....
}
assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.
Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).
Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.
GL!
for f in `find -depth`; do mv ${f} ${f,,} ; done
find -depth
prints each file and directory, with a directory's contents printed before the directory itself. ${f,,}
lowercases the file name.
Try this
$window.location.href="#page-name";
$window.location.reload();
As well as the more general memory management techniques given in the answers above, I always try to reduce the size of my objects as far as possible. For example, I work with very large but very sparse matrices, in other words matrices where most values are zero. Using the 'Matrix' package (capitalisation important) I was able to reduce my average object sizes from ~2GB to ~200MB as simply as:
my.matrix <- Matrix(my.matrix)
The Matrix package includes data formats that can be used exactly like a regular matrix (no need to change your other code) but are able to store sparse data much more efficiently, whether loaded into memory or saved to disk.
Additionally, the raw files I receive are in 'long' format where each data point has variables x, y, z, i
. Much more efficient to transform the data into an x * y * z
dimension array with only variable i
.
Know your data and use a bit of common sense.
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
You can use new Date().getTimezoneOffset()/60
for the timezone. There is also a toLocaleString()
method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
You can simply use jQuery’s delay() method to set the delay time interval.
HTML code:
<div class="box"></div>
JQuery code:
$(document).ready(function(){
$(".show-box").click(function(){
$(this).text('loading...').delay(1000).queue(function() {
$(this).hide();
showBox();
$(this).dequeue();
});
});
});
You can see an example here: How to Call a Function After Some Time in jQuery
this helped me
git checkout -b newbranch
git checkout master
git merge newbranch
git branch -d newbranch
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.
Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.
EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)
public class Job
{
public string id { get; set; }
public string position_title { get; set; }
public string organization_name { get; set; }
public string rate_interval_code { get; set; }
public int minimum { get; set; }
public int maximum { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public List<string> locations { get; set; }
public string url { get; set; }
}
And an edit to your code:
List<Job> model = null;
var client = new HttpClient();
var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);
});
task.Wait();
This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.
EDIT 2:
There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:
http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
Simplistically malloc
and free
work like this:
malloc
provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.
Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.
When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.
When one calls malloc
, memory is taken from the large heap cell, which is returned by malloc
. The rest is formed into a new heap cell that consists of all the rest of the memory.
When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc
's walk the free list looking for a cell of suitable size.
As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.
When there is no memory left on the free list for a desired allocation, malloc
calls brk
or sbrk
which are the system calls requesting more memory pages from the operating system.
Now there are a few modification to optimize heap operations.
This is pure JPA without using getters/setters. As of 2013/2014 it is the best answer without using any Hibernate specific annotations, but please note this solution is JPA 2.1, and was not available when the question was first asked:
@Entity
public class Person {
@Convert(converter=BooleanToStringConverter.class)
private Boolean isAlive;
...
}
And then:
@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {
@Override
public String convertToDatabaseColumn(Boolean value) {
return (value != null && value) ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
return "Y".equals(value);
}
}
Edit:
The implementation above considers anything different from character "Y", including null
, as false
. Is that correct? Some people here consider this incorrect, and believe that null
in the database should be null
in Java.
But if you return null
in Java, it will give you a NullPointerException
if your field is a primitive boolean. In other words, unless some of your fields actually use the class Boolean it's best to consider null
as false
, and use the above implementation. Then Hibernate will not to emit any exceptions regardless of the contents of the database.
And if you do want to accept null
and emit exceptions if the contents of the database are not strictly correct, then I guess you should not accept any characters apart from "Y", "N" and null
. Make it consistent, and don't accept any variations like "y", "n", "0" and "1", which will only make your life harder later. This is a more strict implementation:
@Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null) return null;
else return value ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
if (value == null) return null;
else if (value.equals("Y")) return true;
else if (value.equals("N")) return false;
else throw new IllegalStateException("Invalid boolean character: " + value);
}
And yet another option, if you want to allow for null
in Java but not in the database:
@Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null) return "-";
else return value ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
if (value.equals("-") return null;
else if (value.equals("Y")) return true;
else if (value.equals("N")) return false;
else throw new IllegalStateException("Invalid boolean character: " + value);
}
Switch is not same as if-else-if.
Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.
keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk
to obtain the hash md5keytool -list -v -keystore clave-release.jks
my solution is this:
cd android
and then:
./gradlew assembleMyBuild --stacktrace
df.filter(df.location.contains('google.com'))
You can use plain SQL in
filter
df.filter("location like '%google.com%'")
or with DataFrame column methods
df.filter(df.location.like('%google.com%'))
If you are in same WORKGROUP you need software to connect and control the target server.shutdown.exe /s /m \\<target-computer-name>
should be enough shutdown /?
for more, otherwise
UPDATE:
Seems shutdown.bat here is for shutting down apache-tomcat.
So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client
As native solution could be wmic
Example:
wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"
In your example should be:
wmic /node:inidsoasrv01 process call create ^
"cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"
wmic /?
and wmic /node /?
for more
Here is an iterative solution using object-scan. The advantage is that you can easily do other processing in the filter function and specify the paths in a more readable format. There is a trade-off in introducing a dependency though, so it really depends on your use case.
// const objectScan = require('object-scan');
const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
rtn: 'parent',
filterFn: ({ value }) => value === v
})(haystack);
const obj = { list: [ { name: 'my Name', id: 12, type: 'car owner' }, { name: 'my Name2', id: 13, type: 'car owner2' }, { name: 'my Name4', id: 14, type: 'car owner3' }, { name: 'my Name4', id: 15, type: 'car owner5' } ] };
console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.
What did the trick was:
bfg -b 100M # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Then, you need to push force on your branch:
git push origin <your_branch_name> --force
Note: bfg is a tool that can be installed on Linux and macOS using brew:
brew install bfg
Try this,
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Date
{
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = "2013-05-14 17:07:21";
try
{
java.util.Date dt = sdf.parse(strDate);
System.out.println(sdf.format(dt));
}
catch (ParseException pe)
{
pe.printStackTrace();
}
}
}
Output:
2013-05-14 17:07:21
For more on date and time formatting in java refer links below
Try this Its Working :
In Xcode, go to File->Project/Workspace settings.
Change the build system to Legacy Build system.
//By : Dhaval Nimavat
import UIKit
func weather_diff(country1:String,temp1:Double,country2:String,temp2:Double)->(c1:String,c2:String,diff:Double)
{
let c1 = country1
let c2 = country2
let diff = temp1 - temp2
return(c1,c2,diff)
}
let result =
weather_diff(country1: "India", temp1: 45.5, country2: "Canada", temp2: 18.5)
print("Weather difference between \(result.c1) and \(result.c2) is \(result.diff)")
In your R script, called test.R
:
args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")
From the command line run:
R CMD BATCH -4 test.R
Your output file, test.Rout, will show that the argument 4
has been successfully passed to R:
cat test.Rout
> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user system elapsed
0.222 0.022 0.236
You can absolutely do that, just remove the @RequestParam
annotation, Spring will cleanly bind your request parameters to your class instance:
public @ResponseBody List<MyObject> myAction(
@RequestParam(value = "page", required = false) int page,
MyObject myObject)
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
this is working with Swift 4 :
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
This answer is not yet possible, but I am posting it for "future generations". Hopefully, some day we will be able to do this via the CSS @viewport rule:
@viewport {
orientation: portrait;
}
Here is the "Can I Use" page (as of 2019 only IE and Edge):
https://caniuse.com/#feat=mdn-css_at-rules_viewport_orientation
Spec(in process):
https://drafts.csswg.org/css-device-adapt/#orientation-desc
MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/@viewport/orientation
Based on the MDN browser compatibility table and the following article, looks like there is some support in certain versions of IE and Opera:
http://menacingcloud.com/?c=cssViewportOrMetaTag
This JS API Spec also looks relevant:
https://w3c.github.io/screen-orientation/
I had assumed that because it was possible with the proposed @viewport
rule, that it would be possible by setting orientation
in the viewport settings in a meta
tag, but I have had no success with this thus far.
Feel free to update this answer as things improve.
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
Check your entitlements against your app bundle id. It is probable it is not the same.
The way this still do not work is when I export for testing in my device but in Release mode.
That work to me.
Following link might help you. Here's code from the following link.
reference : getting-the-client-ip-via-asp-net-web-api
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
namespace Trikks.Controllers.Api
{
public class IpController : ApiController
{
public string GetIp()
{
return GetClientIp();
}
private string GetClientIp(HttpRequestMessage request = null)
{
request = request ?? Request;
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
}
}
Another way of doing this is below.
reference: how-to-access-the-client-s-ip-address
For web hosted version
string clientAddress = HttpContext.Current.Request.UserHostAddress;
For self hosted
object property;
Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property);
RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty;
Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).
I would use sed
:
sed 's/, /,/' input.txt
This will remove on leading space after the ,
.
Output:
Name,Order
Trim,working
cat,cat1
More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,
:
sed 's/,[ \t]\?/,/g' input.txt
It will also work with more than two columns because of the global modifier /g
@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:
sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt
*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *
IMO sed
is the optimal tool for this job. However, here comes a solution with awk
because you've asked for that:
awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
Another simple solution that comes in mind to remove all whitespaces is tr -d
:
cat input.txt | tr -d ' '
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
The capitalization is wrong, and you have an extra argument.
Do this instead:
$('img#thumb').removeAttr('id');
For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.
I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.
Is it impossible to assign session values directly through javascript? No, there is a way to do that.
Look again your code:
<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script>
A little bit change:
<script type="text/javascript" >
{
<%Session["controlID"] = "This is my session";%>
}
</script>
The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?
Let change a little bit more:
<script type="text/javascript" >
{
var strTest = "This is my session";
<%Session["controlID"] = "'+ strTest +'";%>
}
</script>
The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:
<%Session["controlID"] = strTest;%>
Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.
Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:
<script type="text/javascript" >
{
var strTest = "This is my session";
PageMethods.CreateSessionViaJavascript(strTest);
}
</script>
In code-behind page. I create a WebMethod:
[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
Page objp = new Page();
objp.Session["controlID"] = strTest;
return strTest;
}
After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".
If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.
<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>
Source: JavaScript - How to Set values to Session in Javascript
Happy codding, Tri
if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
Actually I would advocate .profile
if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc
is fine, though.
At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
There is no "better" but the more common one is ||
. They have different precedence and ||
would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
Here is the code
<input type="button" value="Back" onclick="window.history.back()" />
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
There are two separate things here:
For example:
{
vector<MyObject> v;
// do some stuff, push some objects onto v
v.clear(); // 1
// maybe do some more stuff
} // 2
At 1
, you clear v
: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject
is now released.
However, vector v
has the right to keep the raw storage around in case you want it later.
If you decide to push some more things into it between 1
and 2
, this saves time as it can reuse the old memory.
At 2
, the vector v
goes out of scope: any objects you pushed into it since 1
will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v
won't be around to reuse it any more).
If I change the example so v
becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2
doesn't do that for you. It's better to use something like std::unique_ptr
in that case, but if you don't and v
is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v
is deleted, and calling clear
isn't sufficient.
If you're using Guava, you can take a functional approach and do the following
FluentIterable.from(list).find(new Predicate<MyObject>() {
public boolean apply(MyObject input) {
return "John".equals(input.getName());
}
}).Any();
which looks a little verbose. However the predicate is an object and you can provide different variants for different searches. Note how the library itself separates the iteration of the collection and the function you wish to apply. You don't have to override equals()
for a particular behaviour.
As noted below, the java.util.Stream framework built into Java 8 and later provides something similar.
You could instantiate the values from a dictionary if you wanted different values for each column & you don't mind making a dictionary on the line before.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
>>> df
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
>>> cols = {
'column_new_1':np.nan,
'column_new_2':'dogs',
'column_new_3': 3
}
>>> df[list(cols)] = pd.DataFrame(data={k:[v]*len(df) for k,v in cols.items()})
>>> df
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
Not necessarily better than the accepted answer, but it's another approach not yet listed.
I got the same error, and fixed it with the following PHP in my back-end script:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
You can do
$result = Model::where(...)->count();
to count the results.
You can also use
if ($result->isEmpty()){}
to check whether or not the result is empty.
I had the same error. Creating a new AVD with the appropriate API level solved my problem.
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
I think this is a best practice (You may be have many Tomcat instance in same computer, you want per Tomcat instance use other Java Runtime Environment):
This is manual inside file: catalina.sh
# JRE_HOME Must point at your Java Runtime installation.
# Defaults to JAVA_HOME if empty. If JRE_HOME and JAVA_HOME
# are both set, JRE_HOME is used.
a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
c = 2 · atan2( va, v(1-a) )
distance = R · c
where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!
fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
val earthRadius = 6371000.0
val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
val a = sin(deltaLatitudeDegree / 2).pow(2) +
cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
sin(deltaLongitudeDegree / 2).pow(2)
val c = 2f * atan2(sqrt(a), sqrt(1 - a))
return earthRadius * c
}
data class Location(val latitude: Double, val longitude: Double)
You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache
Below the initial setp to configure and use it.
Step 1:
C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test
Step 2 :
C:\Program Files\MongoDB\Server\4.0\bin>mongo
C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
MongoDB Enterprise test:PRIMARY>
Step 3 : Verify the replication.
MongoDB Enterprise test:PRIMARY> rs.status();
{
"set" : "test",
"date" : ISODate("2019-01-18T11:39:00.380Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
}
},
"lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
"members" : [
{
"_id" : 0,
"name" : "localhost:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 736,
"optime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2019-01-18T11:38:57Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1547810805, 1),
"electionDate" : ISODate("2019-01-18T11:26:45Z"),
"configVersion" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
}
],
"ok" : 1,
"operationTime" : Timestamp(1547811537, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1547811537, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
MongoDB Enterprise test:PRIMARY>
Step 4.
Download the "https://github.com/rwynn/monstache/releases".
Unzip the download and adjust your PATH variable to include the path to the folder for your platform.
GO to cmd and type "monstache -v"
# 4.13.1
Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml
Step 5.
My config.toml -->
mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]
direct-read-namespaces = [ "admin.users" ]
gzip = true
stats = true
index-stats = true
elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000
dropped-collections = false
dropped-databases = false
resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false
index-as-update=true
index-oplog-time=true
Step 6.
D:\15-1-19>monstache -f config.toml
I removed the tag in the .project .
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
It's worked very well for me.
You can use hashlib.md5()
Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the md5
method:
import hashlib
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
Note: hash_md5.hexdigest()
will return the hex string representation for the digest, if you just need the packed bytes use return hash_md5.digest()
, so you don't have to convert back.
System.Net.WebUtility
class is
available starting from .NET 4.0
(You don't need System.Web.dll dependency).
A note from Microsoft concerning SQL Server:
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.
When referencing the PRIMARY KEY of the independent (parent) table by the similarly named column(s) in the dependent (child) table, I omit the column name(s):
FK_ChildTable_ParentTable
When referencing other columns, or the column names vary between the two tables, or just to be explicit:
FK_ChildTable_childColumn_ParentTable_parentColumn
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
Try:
return $this->sendRequest($uri);
Since PHP is not a pure Object-Orieneted language, it interprets sendRequest()
as an attempt to invoke a globally defined function (just like nl2br()
for example), but since your function is part of a class ('InstagramController'), you need to use $this
to point the interpreter in the right direction.
The basic answer is "It depends".
What is your objective in versioning? Many people use version.revision.build and only advertise version.revision to the world as that's a release version rather than a dev version. If you use the check-in 'version' then you'll quickly find that your version numbers become large.
If you are planning your project then I'd increment revision for releases with minor changes and increment version for releases with major changes, bug fixes or functionality/features. If you are offering beta or nightly build type releases then extend the versioning to include the build and increment that with every release.
Still, at the end of the day, it's up to you and it has to make sense to you.
dict.iteritems() in python 2 is equivalent to dict.items() in python 3.
Or
public class Section
{
public String Head { get; set; }
private readonly List<string> _subHead = new List<string>();
private readonly List<string> _content = new List<string>();
public IEnumerable<string> SubHead { get { return _subHead; } }
public IEnumerable<string> Content { get { return _content; } }
public void AddContent(String argValue)
{
_content.Add(argValue);
}
public void AddSubHeader(String argValue)
{
_subHead.Add(argValue);
}
}
All depends on how much of the implementaton of content and subhead you want to hide.
If you're looking to build a GUI interface to trace an IP address, I would recommend VB.
But if you insist on sticking with Python, TkInter and wxPython are the best choices.
n=int(input())
pair = dict()
for i in range(0,n):
word = input().split()
key = word[0]
value = word[1]
pair[key]=value
print(pair)
The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.
(Shame about the layout table in the first example)
As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.
One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path
in that, and you must be fine to go.
One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
From version 2.0, in copy module you can use remote_src
parameter.
If True
it will go to the remote/target machine for the src.
- name: Copy files from foo to bar
copy: remote_src=True src=/path/to/foo dest=/path/to/bar
If you want to move file you need to delete old file with file module
- name: Remove old files foo
file: path=/path/to/foo state=absent
From version 2.8 copy module remote_src
supports recursive copying.
char * const a;
*a
is writable, but a
is not; in other words, you can modify the value pointed to by a
, but you cannot modify a
itself. a
is a constant pointer to char
.
const char * a;
a
is writable, but *a
is not; in other words, you can modify a
(pointing it to a new location), but you cannot modify the value pointed to by a
.
Note that this is identical to
char const * a;
In this case, a
is a pointer to a const char
.
Look at the responseText
property of the request parameter.
Integers are inherently finite. The closest you can get is by setting a
to int
's maximum value:
#include <limits>
// ...
int a = std::numeric_limits<int>::max();
Which would be 2^31 - 1
(or 2 147 483 647
) if int
is 32 bits wide on your implementation.
If you really need infinity, use a floating point number type, like float
or double
. You can then get infinity with:
double a = std::numeric_limits<double>::infinity();
Hovering over the icon "read only" in mysql workbench shows a tooltip that explains why it cannot be edited. In my case it said, only tables with primary keys or unique non-nullable columns can be edited.
function traverse(o) {
for (var i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i]);
traverse(o[i]);
} else {
console.log(i, o[i]);
}
}
}
foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.
Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I think it does E.g. Does it start from zero, does it include or exclude the end point etc.?
Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.
For me worked this one:
|([\'"])(.*?)\1|i
I've used in a sentence like this one:
preg_match_all('|([\'"])(.*?)\1|i', $cont, $matches);
and it worked great.
try
{
// Some code
}
catch (Web2PDFException ex)
{
// It's your special exception
}
catch (Exception ex)
{
// Any other exception here
}
Jquery version
var currentdate = new Date();
$('#DatePickerInputID').val($.datepicker.formatDate('dd-M-y', currentdate));
Here is my code:
background: #e8e3e3; /* Old browsers */
background: -moz-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
background: linear-gradient(to bottom, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */
The amount of "neurons", or "cells", or whatever the layer has inside it.
It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:
Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.
Ex: a shape (30,4,10)
means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.
What flows between layers are tensors. Tensors can be seen as matrices, with shapes.
In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.
Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3)
. Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).
Each type of layer requires the input with a certain number of dimensions:
Dense
layers require inputs as (batch_size, input_size)
(batch_size, optional,...,optional, input_size)
channels_last
: (batch_size, imageside1, imageside2, channels)
channels_first
: (batch_size, channels, imageside1, imageside2)
(batch_size, sequence_length, features)
Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.
All the other shapes are calculated automatically based on the units and particularities of each layer.
Given the input shape, all other shapes are results of layers calculations.
The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).
Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)
Let's show what happens with "Dense" layers, which is the type shown in your graph.
A dense layer has an output shape of (batch_size,units)
. So, yes, units, the property of the layer, also defines the output shape.
(batch_size,4)
. (batch_size,4)
. (batch_size,1)
. Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.
In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.
In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.
Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3)
.
Since the input shape is the only one you need to define, Keras will demand it in the first layer.
But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:
input_shape = (50,50,3)
#regardless of how many images I have, each image has this shape
Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3)
or batch_shape=(30,50,50,3)
. This limits your training possibilities to this unique batch size, so it should be used only when really required.
Either way you choose, tensors in the model will have the batch dimension.
So, even if you used input_shape=(50,50,3)
, when keras sends you messages, or when you print the model summary, it will show (None,50,50,3)
.
The first dimension is the batch size, it's None
because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None
)
Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.
input_shape=(50,50,3)
(30,50,50,3)
(None,50,50,3)
or (30,50,50,3)
, depending on what type of message it sends you. And in the end, what is dim
?
If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim
as a scalar number.
So, in your model, where your input layer has 3 elements, you can use any of these two:
input_shape=(3,)
-- The comma is necessary when you have only one dimension input_dim = 3
But when dealing directly with the tensors, often dim
will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.
Keras has two ways of doing it, Sequential
models, or the functional API Model
. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.
PS: here I ignored other aspects, such as activation functions.
With the Sequential model:
from keras.models import Sequential
from keras.layers import *
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
With the functional API Model:
from keras.models import Model
from keras.layers import *
#Start defining the input tensor:
inpTensor = Input((3,))
#create the layers and pass them the input tensor to get the output tensor:
hidden1Out = Dense(units=4)(inpTensor)
hidden2Out = Dense(units=4)(hidden1Out)
finalOut = Dense(units=1)(hidden2Out)
#define the model's start and end points
model = Model(inpTensor,finalOut)
Shapes of the tensors
Remember you ignore batch sizes when defining layers:
(None,3)
(None,4)
(None,4)
(None,1)
I found that CURL can decide to use IPv6, in which case it tries to resolve but doesn't get an IPv6 answer (or something to that effect) and times out.
You can try the command line switch -4 to test this out.
In PHP, you can configure this line by setting this:
curl_setopt($_h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
The most libraries offer escaping everything they can, including hundreds of symbols and thousands of non-ASCII characters which is not what you want in UTF-8 world.
Also, as Jeff Williams noted, there's no single “escape HTML” option, there are several contexts.
Assuming you never use unquoted attributes, and keeping in mind that different contexts exist, it've written my own version:
private static final long BODY_ESCAPE =
1L << '&' | 1L << '<' | 1L << '>';
private static final long DOUBLE_QUOTED_ATTR_ESCAPE =
1L << '"' | 1L << '&' | 1L << '<' | 1L << '>';
private static final long SINGLE_QUOTED_ATTR_ESCAPE =
1L << '"' | 1L << '&' | 1L << '\'' | 1L << '<' | 1L << '>';
// 'quot' and 'apos' are 1 char longer than '#34' and '#39' which I've decided to use
private static final String REPLACEMENTS = ""&'<>";
private static final int REPL_SLICES = /* |0, 5, 10, 15, 19, 23*/
5<<5 | 10<<10 | 15<<15 | 19<<20 | 23<<25;
// These 5-bit numbers packed into a single int
// are indices within REPLACEMENTS which is a 'flat' String[]
private static void appendEscaped(
StringBuilder builder,
CharSequence content,
long escapes // pass BODY_ESCAPE or *_QUOTED_ATTR_ESCAPE here
) {
int startIdx = 0, len = content.length();
for (int i = 0; i < len; i++) {
char c = content.charAt(i);
long one;
if (((c & 63) == c) && ((one = 1L << c) & escapes) != 0) {
// -^^^^^^^^^^^^^^^ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// | | take only dangerous characters
// | java shifts longs by 6 least significant bits,
// | e. g. << 0b110111111 is same as >> 0b111111.
// | Filter out bigger characters
int index = Long.bitCount(SINGLE_QUOTED_ATTR_ESCAPE & (one - 1));
builder.append(content, startIdx, i /* exclusive */)
.append(REPLACEMENTS,
REPL_SLICES >>> 5*index & 31,
REPL_SLICES >>> 5*(index+1) & 31);
startIdx = i + 1;
}
}
builder.append(content, startIdx, len);
}
Consider copy-pasting from Gist without line length limit.
You need to delete your old db folder and recreate new one. It will resolve your issue.
Nop... I believe you have to make as many calls as the file types you want.
I would create a function myself taking an array on strings with the extensions I need and then iterate on that array making all the necessary calls. That function would return a generic list of the files matching the extensions I'd sent.
Hope it helps.
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:
SQLSVCACCOUNT: NT AUTHORITY\SYSTEM
According to the link provided by @royki:
The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.
This would explain why other respondents had success after changing to different accounts:
To fix the user profile that's causing the error, follow the steps listed KB947215.
The main steps from KB947215 are summarized as follows:-
regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
Navigate to the SID for the corrupted profile
To find the SID, click on each SID GUID, review the value for the ProfileImagePath
value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:
The main system account SIDs of interest are:
SID Name Also Known As
S-1-5-18 Local System NT AUTHORITY\SYSTEM
S-1-5-19 LocalService NT AUTHORITY\LOCAL SERVICE
S-1-5-20 NetworkService NT AUTHORITY\NETWORK SERVICE
For information on additional SIDs, see Well-known security identifiers in Windows operating systems.
RefCount
and State
to be 0
.You can user either
.your-class{
position:absolute;
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
}
or
.your-class{
position:absolute;
transform: rotate(360deg) scaleX(-1);
}
Notice that setting position
to absolute
is very important! If you won't set it, you will need to set display: inline-block;
In my case adding sudo before npm install solved gulp command not found problem
sudo npm install
You must do something like this
SELECT onDay, id,
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate
FROM ... where stockParent_id =16120 group by sdate order by onDay
This answer is based upon Matifou's answer.
First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.
Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.
getOption("scipen")
options("scipen"=10)
mtcars %>%
count(am, gear) %>%
mutate(freq = (n / sum(n)) * 100)
I'm assuming you mean that you don't care which row is used to obtain the title
, id
, and commentname
values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:
select
id,
title,
email,
commentname
from
(
select
*,
row_number() over (partition by email order by id) as RowNbr
from YourTable
) source
where RowNbr = 1
You have to change the ID of the button to be different from the function name JSFiddle
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
counter++;_x000D_
var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
newFields.id = '';_x000D_
newFields.style.display = 'block';_x000D_
var newField = newFields.childNodes;_x000D_
for (var i = 0; i < newField.length; i++) {_x000D_
var theName = newField[i].name_x000D_
if (theName) newField[i].name = theName + counter;_x000D_
}_x000D_
var insertHere = document.getElementById('writeroot');_x000D_
insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
<input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
<br />_x000D_
<br />_x000D_
<input name="cd" value="title" />_x000D_
<select name="rankingsel">_x000D_
<option>Rating</option>_x000D_
<option value="excellent">Excellent</option>_x000D_
<option value="good">Good</option>_x000D_
<option value="ok">OK</option>_x000D_
<option value="poor">Poor</option>_x000D_
<option value="bad">Bad</option>_x000D_
</select>_x000D_
<br />_x000D_
<br />_x000D_
<textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
<br />Radio buttons included to test them in Explorer:_x000D_
<br />_x000D_
<input type="radio" name="something" value="test1" />Test 1_x000D_
<br />_x000D_
<input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
<input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
<input type="submit" value="Send form" />_x000D_
</form>
_x000D_
In case the post build event contains copy/xcopy command for copying build output to some directory(which usually is the most common post build operation) the problem can occur in case the full directory path either of source or target destinations contain folder names which include spaces. Remove space for the directory name(s) and try.
For binary files, the fastest way of reading them I have found is this.
MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file);
MemoryMappedViewStream mms = mmf.CreateViewStream();
using (BinaryReader b = new BinaryReader(mms))
{
}
In my tests it's hundreds of times faster.
Despite @Saint Hill's answer if you consider the time complexity of str.toCharArray(),
the first one is faster even for very large strings. You can run the code below to see it for yourself.
char [] ch = new char[1_000_000_00];
String str = new String(ch); // to create a large string
// ---> from here
long currentTime = System.nanoTime();
for (int i = 0, n = str.length(); i < n; i++) {
char c = str.charAt(i);
}
// ---> to here
System.out.println("str.charAt(i):"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");
/**
* ch = str.toCharArray() itself takes lots of time
*/
// ---> from here
currentTime = System.nanoTime();
ch = str.toCharArray();
for (int i = 0, n = str.length(); i < n; i++) {
char c = ch[i];
}
// ---> to here
System.out.println("ch = str.toCharArray() + c = ch[i] :"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");
output:
str.charAt(i):5.492102 (ms)
ch = str.toCharArray() + c = ch[i] :79.400064 (ms)
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
It is possible to convert any expression string in infix notation to a postfix notation using Djikstra's shunting-yard algorithm. The result of the algorithm can then serve as input to the postfix algorithm with returns the result of the expression.
I wrote an article about it here, with an implementation in java
How about another, simpler approach:
require 'fileutils'
FileUtils.cmp(file1, file2)
Use the EXECUTABLE_OUTPUT_PATH
CMake variable to set the needed path. For details, refer to the online CMake documentation:
I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:
string removeCharsFromString(const string str, char* charsToRemove )
{
char c[str.length()+1]; // + terminating char
const char *p = str.c_str();
unsigned int z=0, size = str.length();
unsigned int x;
bool rem=false;
for(x=0; x<size; x++)
{
rem = false;
for (unsigned int i = 0; charsToRemove[i] != 0; i++)
{
if (charsToRemove[i] == p[x])
{
rem = true;
break;
}
}
if (rem == false) c[z++] = p[x];
}
c[z] = '\0';
return string(c);
}
Just use as
myString = removeCharsFromString(myString, "abc\r");
and it will remove all the occurrence of the given char list.
This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.
Had the same problem with a zipcode field. Some folks sent me an excel file with zips, but they were formatted as #'s. Had to convert them to strings as well as prepend leading 0's to them if they were < 5 len ...
declare @int tinyint
set @int = 25
declare @len tinyint
set @len = 3
select right(replicate('0', @len) + cast(@int as varchar(255)), @len)
You just alter the @len to get what you want. As formatted, you'll get...
001
002
...
010
011
...
255
Ideally you'd "varchar(@len)", too, but that blows up the SQL compile. Have to toss an actual # into it instead of a var.
pip has a --no-dependencies
switch. You should use that.
For more information, run pip install -h
, where you'll see this line:
--no-deps, --no-dependencies
Ignore package dependencies
I hope i am not too late, this solution here worked for me, i am using COMODO SSL, the above solutions seem invalid over time, my website lifetanstic.co.ke
Instead of contacting Comodo Support and gain a CA bundle file You can do the following:
When You get your new SSL cert from Comodo (by mail) they have a zip file attached. You need to unzip the zip-file and open the following files in a text editor like notepad:
AddTrustExternalCARoot.crt
COMODORSAAddTrustCA.crt
COMODORSADomainValidationSecureServerCA.crt
Then copy the text of each ".crt" file and paste the texts above eachother in the "Certificate Authority Bundle (optional)" field.
After that just add the SSL cert as usual in the "Certificate" field and click at "Autofil by Certificate" button and hit "Install".
Run this inside python shell:
from distutils.sysconfig import get_python_lib
print(get_python_lib())
I use brew and the prefix was already set to be:
$ npm config get prefix
/Users/[user]/.node
I did notice that the bin and lib folder were owned by root, which prevented the usual non sudo install, so I re-owned them to the user
$ cd /Users/[user]/.node
$ chown -R [user]:[group] lib
$ chown -R [user]:[group] bin
Then I just added the path to my .bash_profile which is located at /Users/[user]
PATH=$PATH:~/.node/bin
Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)
xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J
In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.
File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.
You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98
I had exactly the same problem, one day eclipse wouldn't open. Tried editing eclipse.ini to the correct java version 1.7, but still the same error. Eventually changed :
-Xms384m
-Xmx384m
...and all working.
:(){ :|:& };:
This fork bomb will cause havoc to the CPU and will likely crash your computer.
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
There are just two minor things here.
The first is in the following carousel indicator list items:
<li data-target="carousel" data-slide-to="0"></li>
You need to pass the data-target
attribute a selector which means the ID must be prefixed with #
. So change them to the following:
<li data-target="#carousel" data-slide-to="0"></li>
Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active
class. Like this:
<ol class="carousel-indicators">
<li data-target="#carousel" data-slide-to="0" class="active"></li>
<!-- Other Items -->
</ol>
<div class="carousel-inner">
<div class="item active">
<img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
</div>
<!-- Other Items -->
</div>
Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.
x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).
x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:
x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).
For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):
10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.
When booting a kernel with the support, you must use syscall.x32=y
option. When building a kernel, you must include the CONFIG_X86_X32=y
option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).
Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:
__x86_64__
(and friends) and __ILP32__
, but not __i386__
/__i686__
(and friends)__ILP32__
alone because it shows up unexpectedly under Clang and Sun Studiopushq
and popq
adcq
If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap
to install the X32 chroot environment, and (3) chroot debian-x32
to enter into the environment and test your software.
I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.
Teaser:
public class SampleViewModel: BaseViewModelStub
{
public string Name { get; set; }
[UiCommand]
public void HelloWorld()
{
MessageBox.Show("Hello World!");
}
[UiCommand]
public void Print()
{
MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
}
public bool CanPrint()
{
return !String.IsNullOrEmpty(Name);
}
}
}
UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.
It's probably easiest to use xargs
. In your case:
ls -1 | xargs -L1 echo
The -L
flag ensures the input is read properly. From the man page of xargs
:
-L number
Call utility for every number non-empty lines read.
A line ending with a space continues to the next non-empty line. [...]
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
This happened to me when I started to work with a colleque's project.
He was using jdk 12.0.2 .
If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):
The below code always gives the public IP of the client (and not a private IP behind a proxy).
from flask import request
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
print(request.environ['REMOTE_ADDR'])
else:
print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy
Yes (write your own), something like the following complete function.
#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>
/* Create a string of binary digits based on the input value.
Input:
val: value to convert.
buff: buffer to write to must be >= sz+1 chars.
sz: size of buffer.
Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
char *pbuff = buff;
/* Must be able to store one character at least. */
if (sz < 1) return NULL;
/* Special case for zero to ensure some output. */
if (val == 0) {
*pbuff++ = '0';
*pbuff = '\0';
return buff;
}
/* Work from the end of the buffer back. */
pbuff += sz;
*pbuff-- = '\0';
/* For each bit (going backwards) store character. */
while (val != 0) {
if (sz-- == 0) return NULL;
*pbuff-- = ((val & 1) == 1) ? '1' : '0';
/* Get next bit. */
val >>= 1;
}
return pbuff+1;
}
Add this main to the end of it to see it in operation:
#define SZ 32
int main(int argc, char *argv[]) {
int i;
int n;
char buff[SZ+1];
/* Process all arguments, outputting their binary. */
for (i = 1; i < argc; i++) {
n = atoi (argv[i]);
printf("[%3d] %9d -> %s (from '%s')\n", i, n,
binrep(n,buff,SZ), argv[i]);
}
return 0;
}
Run it with "progname 0 7 12 52 123"
to get:
[ 1] 0 -> 0 (from '0')
[ 2] 7 -> 111 (from '7')
[ 3] 12 -> 1100 (from '12')
[ 4] 52 -> 110100 (from '52')
[ 5] 123 -> 1111011 (from '123')
Add a comma separated list of classes like this :
jQuery(document).ready(function($) {
$('.class, .id').click(function() {
// Your code
}
});
If we wanted to return the same matrix we would write:
return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]
What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:
[[1,2,3],
[4,5,6],
[7,8,9]]
Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:
[[1,4,7],
[2,5,8],
[3,6,9]]
Therefore just switch the order in which we iterate:
return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.
For example:
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
browserHistory,
Switch
} from 'react-router-dom';
import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';
const Root = () => (
<Router history={browserHistory}>
<Switch>
<Route exact path="/" component={App}/>
<Route path="/welcome" component={Welcome}/>
<Route component={NotFound}/>
</Switch>
</Router>
);
ReactDOM.render(
<Root/>,
document.getElementById('root')
);
Clang's document on Objective-C Automatic Reference Counting (ARC) explains the ownership qualifiers and modifiers clearly:
There are four ownership qualifiers:
- __autoreleasing
- __strong
- __*unsafe_unretained*
- __weak
A type is nontrivially ownership-qualified if it is qualified with __autoreleasing, __strong, or __weak.
Then there are six ownership modifiers for declared property:
- assign implies __*unsafe_unretained* ownership.
- copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
- retain implies __strong ownership.
- strong implies __strong ownership.
- *unsafe_unretained* implies __*unsafe_unretained* ownership.
- weak implies __weak ownership.
With the exception of weak, these modifiers are available in non-ARC modes.
Semantics wise, the ownership qualifiers have different meaning in the five managed operations: Reading, Assignment, Initialization, Destruction and Moving, in which most of times we only care about the difference in Assignment operation.
Assignment occurs when evaluating an assignment operator. The semantics vary based on the qualification:
- For __strong objects, the new pointee is first retained; second, the lvalue is loaded with primitive semantics; third, the new pointee is stored into the lvalue with primitive semantics; and finally, the old pointee is released. This is not performed atomically; external synchronization must be used to make this safe in the face of concurrent loads and stores.
- For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is updated to a null pointer. This must execute atomically with respect to other assignments to the object, to reads from the object, and to the final release of the new pointee.
- For __*unsafe_unretained* objects, the new pointee is stored into the lvalue using primitive semantics.
- For __autoreleasing objects, the new pointee is retained, autoreleased, and stored into the lvalue using primitive semantics.
The other difference in Reading, Init, Destruction and Moving, please refer to Section 4.2 Semantics in the document.
The CSS class that can be changed to add a image to the JQuery slider handle is called ".ui-slider-horizontal .ui-slider-handle".
The following code shows a demo:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
<style type="text/css">
.ui-slider-horizontal .ui-state-default {background: white url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat scroll 50% 50%;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#slider").slider();
});
</script>
</head>
<body>
<div id="slider"></div>
</body>
</html>
I think registering a handle option was the old way of doing it and no longer supported in JQuery-ui 1.7.2?
Here is example for list of Objects
Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));
In [6]: os.listdir?
Type: builtin_function_or_method
String Form:<built-in function listdir>
Docstring:
listdir(path) -> list_of_strings
Return a list containing the names of the entries in the directory.
path: path of directory to list
The list is in **arbitrary order**. It does not include the special
entries '.' and '..' even if they are present in the directory.
I used this in my code:
<div class="sticky-top h-100">
<nav id="sidebar" class="vh-100">
....
this cause your sidebar height become 100% and fixed at top.
I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:
div { background:red;
overflow:hidden;
}
span { display:block;
margin:0 auto;
width:200px;
}
span a { padding:5px 10px;
color:#fff;
background:#222;
}
I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.
Depending on the Tkinter activity, and especially when using Tkinter.after, stopping this activity with destroy()
-- even by using protocol(), a button, etc. -- will disturb this activity ("while executing" error) rather than just terminate it. The best solution in almost every case is to use a flag. Here is a simple, silly example of how to use it (although I am certain that most of you don't need it! :)
from Tkinter import *
def close_window():
global running
running = False # turn off while loop
print( "Window closed")
root = Tk()
root.protocol("WM_DELETE_WINDOW", close_window)
cv = Canvas(root, width=200, height=200)
cv.pack()
running = True;
# This is an endless loop stopped only by setting 'running' to 'False'
while running:
for i in range(200):
if not running:
break
cv.create_oval(i, i, i+1, i+1)
root.update()
This terminates graphics activity nicely. You only need to check running
at the right place(s).
Just add a STYLE line and your progress becomes horizontal:
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progress"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:max="100"
android:progress="45"/>
contentType
is the HTTP header sent to the server, specifying a particular format.dataType
is you telling jQuery what kind of response to expect.The $.ajax()
documentation has full descriptions of these as well.
In your particular case, the first is asking for the response to be in UTF-8
, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.
So the first would be:
success: function(data) {
// get data, e.g. data.title;
}
The second:
success: function(data) {
alert("Here's lots of data, just a string: " + data);
}
If your instance is down, you are look for version information in alert.log
Or another crude way is to look into Oracle binary, If DB in hosted on Linux, try strings on Oracle binary.
strings -a $ORACLE_HOME/bin/oracle |grep RDBMS | grep RELEASE
A LINQ one-liner for good measure (assuming a private static Random Random
)...
public static string RandomString(int length)
{
return new string(Enumerable.Range(0, length).Select(_ => (char)Random.Next('a', 'z')).ToArray());
}
echoing @HYRY, see the new docs in 0.11
http://pandas.pydata.org/pandas-docs/stable/indexing.html
Here we have new operators, .iloc
to explicity support only integer indexing, and .loc
to explicity support only label indexing
e.g. imagine this scenario
In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))
In [2]: df
Out[2]:
A B
0 1.068932 -0.794307
2 -0.470056 1.192211
4 -0.284561 0.756029
6 1.037563 -0.267820
8 -0.538478 -0.800654
In [5]: df.iloc[[2]]
Out[5]:
A B
4 -0.284561 0.756029
In [6]: df.loc[[2]]
Out[6]:
A B
2 -0.470056 1.192211
[]
slices the rows (by label location) only
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
As mentioned above, by default text editors will not use UTF-8 as the standard encoding for documents. However most editors will allow you to change that in the settings. Even for each specific document.
You could wrap your h1
tags in another div
and then the first one would be the first-child
. That div
doesn't even need styles. It's just a way to segregate those children.
<div class="h1-holder">
<h1>Title 1</h1>
<h1>Title 2</h1>
</div>
try this in eclipse: Window - Preferences - Android
- SDK Location and setup SDK path
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond])
constructor signature of the Date
object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
just change it to
compile 'com.google.android.gms:play-services-maps:9.6.0'
compile 'com.google.android.gms:play-services-location:9.6.0'
this works for me current version is 10.0.1
You can clear the error state and empty the stringstream all in one line
std::stringstream().swap(m); // swap m with a default constructed stringstream
This effectively resets m to a default constructed state
You have two choices, depending on your table order
create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)
-- type 1
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht
-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht
In your case, you need to use Sprintf() for format string.
func Sprintf(format string, a ...interface{}) string
Sprintf formats according to a format specifier and returns the resulting string.
s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)
Your output will be :
Good Morning, This is John and I'm living here from last 20 years.
Make sure there are no 'echo off' statements in the scripts and call 'echo on' after calling each script to reset any you have missed.
The reason is that if echo is left on, then the command interpreter will output each command (after parameter processing) before executing it. Makes it look really bad for using in production, but very useful for debugging purposes as you can see where output has gone wrong.
Also, make sure you are checking the ErrorLevels set by the called batch scripts and programs. Remember that there are 2 different methods used in .bat files for this. If you called a program, the Error level is in %ERRORLEVEL%, while from batch files the error level is returned in the ErrorLevel variable and doesn't need %'s around it.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info: