if any interested I've made a typescript version:
interface IResizeImageOptions {
maxSize: number;
file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
const file = settings.file;
const maxSize = settings.maxSize;
const reader = new FileReader();
const image = new Image();
const canvas = document.createElement('canvas');
const dataURItoBlob = (dataURI: string) => {
const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
const max = bytes.length;
const ia = new Uint8Array(max);
for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
return new Blob([ia], {type:mime});
};
const resize = () => {
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
let dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise((ok, no) => {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = (readerEvent: any) => {
image.onload = () => ok(resize());
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
})
};
and here's the javascript result:
var resizeImage = function (settings) {
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
usage is like:
resizeImage({
file: $image.files[0],
maxSize: 500
}).then(function (resizedImage) {
console.log("upload resized image")
}).catch(function (err) {
console.error(err);
});
or (async
/await
):
const config = {
file: $image.files[0],
maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")
I use this solution
int G = 0;
private void toolStripMenuItem17_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("picture");// ??? ??????? ????? ???? ?? ???? ???? ????????
G = G + 1;
FormScreen();
memoryImage1.Save("picture\\picture" + G.ToString() + ".jpg");
pictureBox1.Image = Image.FromFile("picture\\picture" + G.ToString() + ".jpg");
}
All given answers are good, if i might add something: To directly use string's methods and properties (e.g. ToLower) you can't write:
(string)o.ToLower(); // won't compile
you can only write:
((string)o).ToLower();
but you could write instead:
(o as string).ToLower();
The as
option is more readable (at least to my opinion).
Use the dist()
function, but you need to form a matrix from the two inputs for the first argument to dist()
:
dist(rbind(x1, x2))
For the input in the OP's question we get:
> dist(rbind(x1, x2))
x1
x2 7.94821
a single value that is the Euclidean distance between x1
and x2
.
Remember that o(1) does not mean that each lookup only examines a single item - it means that the average number of items checked remains constant w.r.t. the number of items in the container. So if it takes on average 4 comparisons to find an item in a container with 100 items, it should also take an average of 4 comparisons to find an item in a container with 10000 items, and for any other number of items (there's always a bit of variance, especially around the points at which the hash table rehashes, and when there's a very small number of items).
So collisions don't prevent the container from having o(1) operations, as long as the average number of keys per bucket remains within a fixed bound.
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
You may be looking for the special HTML character,
.
You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt
label.
Nobody mentioned using reversed:
f=open(file,"r")
r=reversed(f.readlines())
last_line_of_file = r.next()
Have you ever tried Genymotion? I've read about it last week and it is great. They have several Android Images that you run (with their own software). The images are INCREDIBLY fast and they have Google Play installed on them. Check it out if it is the kind of thing that you need.
This is a user-defined function to iterate through a dictionary:
func findDic(dict: [String: String]){
for (key, value) in dict{
print("\(key) : \(value)")
}
}
findDic(dict: ["Animal":"Lion", "Bird":"Sparrow"])
//prints Animal : Lion
Bird : Sparrow
select pg_get_viewdef('viewname', true)
A list of all those functions is available in the manual:
http://www.postgresql.org/docs/current/static/functions-info.html
There's lots of pain getting stuff like this to work across browsers.
I was originally looking to do the same sort of thing - open a new page styled for print, print it using JS, then close it again. This was a nightmare.
In the end, I opted to simply click-through to the printable page and then use the below JS to initiate a print, then redirect myself to where I wanted to go when done (with a variable set in PHP in this instance).
I've tested this across Chrome and Firefox on OSX and Windows, and IE11-8, and it works on all (although IE8 will freeze for a bit if you don't actually have a printer installed).
Happy hunting (printing).
<script type="text/javascript">
window.print(); //this triggers the print
setTimeout("closePrintView()", 3000); //delay required for IE to realise what's going on
window.onafterprint = closePrintView(); //this is the thing that makes it work i
function closePrintView() { //this function simply runs something you want it to do
document.location.href = "'.$referralurl.'"; //in this instance, I'm doing a re-direct
}
</script>
In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.
<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">
All of those will render tooltips in most every browser.
For me, this was caused by the PATH environment variable being set to an empty value for my user profile. The system variable was set correctly, so I deleted the blank PATH variable from my profile and everything worked again.
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
In most modern browsers, you can now specify:
<table>
<colgroup>
<col width="100px" />
<col width="200px" />
<col width="145px" />
</colgroup>
<thead>
<tr>
<th>My 100px header</th>
<th>My 200px header</th>
<th>My 145px header</th>
</tr>
</thead>
<tbody>
<td>100px is all you get - anything more hides due to overflow.</td>
<td>200px is all you get - anything more hides due to overflow.</td>
<td>100px is all you get - anything more hides due to overflow.</td>
</tbody>
</table>
Then if you apply the styles from the posts above, as follows:
table {
table-layout: fixed; /* This enforces the "col" widths. */
}
table th, table td {
overflow: hidden;
white-space: nowrap;
}
The result gives you nicely hidden overflow throughout the table. Works in latest Chrome, Safari, Firefox and IE. I haven't tested in IE prior to 9 - but my guess is that it will work back as far as 7, and you might even get lucky enough to see 5.5 or 6 support. ;)
As complement to Mark's answer, the compile function does not have access to scope, but the link function does.
I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).
It appears I cannot use an if statement.
Arrow functions either allow to use an expression or a block as their body. Passing an expression
foo => bar
is equivalent to the following block
foo => { return bar; }
However,
if (person.age > 18) person
is not an expression, if
is a statement. Hence you would have to use a block, if you wanted to use if
in an arrow function:
foo => { if (person.age > 18) return person; }
While that technically solves the problem, this a confusing use of .filter
, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter
should return a Boolean, i.e. true
or false
, indicating whether the element should be included in the new array or not.
So all you need is
family.filter(person => person.age > 18);
In ES5:
family.filter(function (person) {
return person.age > 18;
});
Just to mention a simple one-line concatenation as it can be useful sometimes.
# for bash
v=" guga "$'\n'" puga "
# Just for an example.
v2="bar "$'\n'" foo "$'\n'"$v"
# Let's simplify the previous version of $v2.
n=$'\n'
v3="bar ${n} foo ${n}$v"
echo "$v3"
You'll get something like this
bar foo guga puga
All leading and ending white spaces will be preserved right for
echo "$v3" > filename
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']
Reference: INFORMATION_SCHEMA COLUMNS
It looks like you are willing to create a temporary Map
, so I'd do it like this:
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
Here, patch
is the map that you are adding to the target
map.
Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:
patch.forEach(target::putIfAbsent);
The element you were trying to find wasn’t in the DOM when your script ran.
The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.
Consider the following markup; script #1 fails to find the <div>
while script #2 succeeds:
<script>_x000D_
console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
So, what should you do? You've got a few options:
Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:
<body>_x000D_
<button id="test">click me</button>_x000D_
<script>_x000D_
document.getElementById("test").addEventListener("click", function() {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
</script>_x000D_
</body><!-- closing body tag -->
_x000D_
Note: Placing scripts at the bottom is generally considered a best practice.
ready()
Defer your script until the DOM has been completely parsed, using $(handler)
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
$("#test").click(function() {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
});_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
Note: You could simply bind to DOMContentLoaded
or window.onload
but each has its caveats. jQuery's ready()
delivers a hybrid solution.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.
jQuery's on()
performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).on("click", "#test", function(e) {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document
(for demonstrative purposes), you should select the nearest reliable ancestor.
defer
attributeUse the defer
attribute of <script>
.
[
defer
, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firingDOMContentLoaded
.
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
For reference, here's the code from that external script:
document.getElementById("test").addEventListener("click", function(e){
console.log("clicked: %o", this);
});
Note: The defer
attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer
can only be used for external scripts, i.e.: those having a src
attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10
Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:
var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=90)'; // IE fallback
The following will order your data depending on both column in descending order.
ORDER BY article_rating DESC, article_time DESC
Here is my solution, it is based on @alexbirkett's solution.
public class ZoomImageView extends ImageView {
// region . Static fields .
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int CLICK = 3;
// endregion . Static fields .
// region . Fields .
private int mode = NONE;
private Matrix mMatrix = new Matrix();
private PointF mLastTouch = new PointF();
private PointF mStartTouch = new PointF();
private float minScale = 0.5f;
private float maxScale = 4f;
private float[] mCriticPoints;
private float mScale = 1f;
private float mRight;
private float mBottom;
private float mOriginalBitmapWidth;
private float mOriginalBitmapHeight;
private ScaleGestureDetector mScaleDetector;
//endregion . Fields .
// region . Ctor .
public ZoomImageView(Context context) {
super(context);
init(context);
}
public ZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
// endregion . Ctor .
// region . Overrider .
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int bmHeight = getBmHeight();
int bmWidth = getBmWidth();
float width = getMeasuredWidth();
float height = getMeasuredHeight();
float scale = 1;
// If image is bigger then display fit it to screen.
if (width < bmWidth || height < bmHeight) {
scale = width > height ? height / bmHeight : width / bmWidth;
}
mMatrix.setScale(scale, scale);
mScale = 1f;
mOriginalBitmapWidth = scale * bmWidth;
mOriginalBitmapHeight = scale * bmHeight;
// Center the image
float redundantYSpace = (height - mOriginalBitmapHeight);
float redundantXSpace = (width - mOriginalBitmapWidth);
mMatrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
setImageMatrix(mMatrix);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mMatrix.getValues(mCriticPoints);
float translateX = mCriticPoints[Matrix.MTRANS_X];
float trnslateY = mCriticPoints[Matrix.MTRANS_Y];
PointF currentPoint = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
//when one finger is touching
//set the mode to DRAG
case MotionEvent.ACTION_DOWN:
mLastTouch.set(event.getX(), event.getY());
mStartTouch.set(mLastTouch);
mode = DRAG;
break;
//when two fingers are touching
//set the mode to ZOOM
case MotionEvent.ACTION_POINTER_DOWN:
mLastTouch.set(event.getX(), event.getY());
mStartTouch.set(mLastTouch);
mode = ZOOM;
break;
//when a finger moves
//If mode is applicable move image
case MotionEvent.ACTION_MOVE:
//if the mode is ZOOM or
//if the mode is DRAG and already zoomed
if (mode == ZOOM || (mode == DRAG && mScale > minScale)) {
// region . Move image.
float deltaX = currentPoint.x - mLastTouch.x;// x difference
float deltaY = currentPoint.y - mLastTouch.y;// y difference
float scaleWidth = Math.round(mOriginalBitmapWidth * mScale);// width after applying current scale
float scaleHeight = Math.round(mOriginalBitmapHeight * mScale);// height after applying current scale
// Move image to lef or right if its width is bigger than display width
if (scaleWidth > getWidth()) {
if (translateX + deltaX > 0) {
deltaX = -translateX;
} else if (translateX + deltaX < -mRight) {
deltaX = -(translateX + mRight);
}
} else {
deltaX = 0;
}
// Move image to up or bottom if its height is bigger than display height
if (scaleHeight > getHeight()) {
if (trnslateY + deltaY > 0) {
deltaY = -trnslateY;
} else if (trnslateY + deltaY < -mBottom) {
deltaY = -(trnslateY + mBottom);
}
} else {
deltaY = 0;
}
//move the image with the matrix
mMatrix.postTranslate(deltaX, deltaY);
//set the last touch location to the current
mLastTouch.set(currentPoint.x, currentPoint.y);
// endregion . Move image .
}
break;
//first finger is lifted
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(currentPoint.x - mStartTouch.x);
int yDiff = (int) Math.abs(currentPoint.y - mStartTouch.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
// second finger is lifted
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(mMatrix);
invalidate();
return true;
}
//endregion . Overrides .
// region . Privates .
private void init(Context context) {
super.setClickable(true);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
mCriticPoints = new float[9];
setImageMatrix(mMatrix);
setScaleType(ScaleType.MATRIX);
}
private int getBmWidth() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicWidth();
}
return 0;
}
private int getBmHeight() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicHeight();
}
return 0;
}
//endregion . Privates .
// region . Internal classes .
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
float newScale = mScale * scaleFactor;
if (newScale < maxScale && newScale > minScale) {
mScale = newScale;
float width = getWidth();
float height = getHeight();
mRight = (mOriginalBitmapWidth * mScale) - width;
mBottom = (mOriginalBitmapHeight * mScale) - height;
float scaledBitmapWidth = mOriginalBitmapWidth * mScale;
float scaledBitmapHeight = mOriginalBitmapHeight * mScale;
if (scaledBitmapWidth <= width || scaledBitmapHeight <= height) {
mMatrix.postScale(scaleFactor, scaleFactor, width / 2, height / 2);
} else {
mMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
}
}
return true;
}
}
// endregion . Internal classes .
}
You can do it.
BUT you cannot use @color references for colors (..lame), otherwise it will work only for L+
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FFAABB"
android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zm-6,0C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>
In the terminal just write : $ mongod --version
Faced this scenario using Git Bash.
Our repository has multiple branches and each branch has a different commit cycle and merge happens once in a while. Old_Branch was used as a parent for New_Branch
Old_Branch was updated with some changes which required to be merged with New_Branch
Was using below pull command without any branch to get all sources from all branches.
git pull origin
Strangely this doesn't pull all the commits from all the branches. Had thought it so as the indicated shows almost all branches and tags.
So to fix this had checked out the Old_Branch pulled the latest using
git checkout Old_Branch
git pull origin Old_Branch
Now checked out New_Branch
git checkout New_Branch
Pulled it to be sure
git pull origin New_Branch
git merge Old_Branch
And viola got conflicts to fix from Old_Branch to New_Branch :) which was expected
Using modern --inspect with node the console.log is captured and relayed to the browser.
node --inspect myApp.js
or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...
node --inspect-brk myApp.js
I know that this is an old question, but I'm surprised that no answer mentions GetDateTime
:
Gets the value of the specified column as a
DateTime
object.
Which you can use like:
while (MyReader.Read())
{
TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy");
}
It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething())
seems fine. However, if you have
if(!doSomething()) {
...
}
else {
// do something else
}
I'd probably reverse that logic to remove the !
operator and make the if
clause slightly more clear.
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
...also do the conversion to upper or lower outside of the query:
tableName:= UPPER(someValue || '%');
...
Select * from table where upper(table.name) like tableName
With the following,
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(5) << 25;
}
the output will be
00025
setfill
is set to the space character (' '
) by default. setw
sets the width of the field to be printed, and that's it.
If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.
We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.
var Head = [[_x000D_
'Heading 1',_x000D_
'Heading 2', _x000D_
'Heading 3', _x000D_
'Heading 4'_x000D_
]];_x000D_
_x000D_
var row = [_x000D_
{key1:1,key2:2, key3:3, key4:4},_x000D_
{key1:2,key2:5, key3:6, key4:7},_x000D_
{key1:3,key2:2, key3:3, key4:4},_x000D_
{key1:4,key2:2, key3:3, key4:4},_x000D_
{key1:5,key2:2, key3:3, key4:4}_x000D_
];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
Head.push([_x000D_
row[item].key1,_x000D_
row[item].key2,_x000D_
row[item].key3,_x000D_
row[item].key4_x000D_
]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
_x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
There is a great solution for this problem ,You can use the Merge Keyword of Sql
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
You can check this before following, below is the sample
IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
DROP TABLE dbo.TargetTable
GO
CREATE TABLE dbo.TargetTable
(
Id INT NOT NULL,
Name VARCHAR (255) NOT NULL,
CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
)
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
To get an individual table's creation script:
- select all the table (with shift key)
- just right click on the table name and click Copy to Clipboard > Create Statement.
Menu File → Preference → Settings →
Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".
It's an old topic but for future readers, using ToolBar makes everything very easy:
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.someColor));
setSupportActionBar(toolbar);
for direct access a object property by position... generally usefull for property [0]... so it holds info about the further... or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.
Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]
I also faced a similar issue, the problem was the form was inside a folder and the file .aspx.designer.cs
I had the namespace referencing specifically to that directory; which caused the error to appear in several components:
El nombre no existe en el contexto actual
This in your case, a possible solution is to leave the namespace line of the Members_Jobs.aspx.designer.cs
file specified globally, ie change this
namespace stman.Members {
For this
namespace stman {
It's what helped me solve the problem.
I hope to be helpful
First of all we open the file and as datafile
then we apply .read()
method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6']
and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.
with open("sample.txt", "r") as datafile:
print datafile.read().split()[1::3]
Output:
['10', '20', '30', '40', '23', '13']
You could let your DataAdapter
do the work. DataAdapter.Fill(DataTable)
will append your new rows to any existing rows in DataTable
.
The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload
handler:
window.onload = function () {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
};
Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload
waits for all images, too. You do not need that in most cases.
Another approach is to place the script tag right before your closing </body>
-tag, since everything in front of it is loaded at the time of execution, then.
axis
refers to the dimension of the array, in the case of pd.DataFrame
s axis=0
is the dimension that points downwards and axis=1
the one that points to the right.
Example: Think of an ndarray
with shape (3,5,7)
.
a = np.ones((3,5,7))
a
is a 3 dimensional ndarray
, i.e. it has 3 axes ("axes" is plural of "axis"). The configuration of a
will look like 3 slices of bread where each slice is of dimension 5-by-7. a[0,:,:]
will refer to the 0-th slice, a[1,:,:]
will refer to the 1-st slice etc.
a.sum(axis=0)
will apply sum()
along the 0-th axis of a
. You will add all the slices and end up with one slice of shape (5,7)
.
a.sum(axis=0)
is equivalent to
b = np.zeros((5,7))
for i in range(5):
for j in range(7):
b[i,j] += a[:,i,j].sum()
b
and a.sum(axis=0)
will both look like this
array([[ 3., 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3., 3.]])
In a pd.DataFrame
, axes work the same way as in numpy.array
s: axis=0
will apply sum()
or any other reduction function for each column.
N.B. In @zhangxaochen's answer, I find the phrases "along the rows" and "along the columns" slightly confusing. axis=0
should refer to "along each column", and axis=1
"along each row".
If your newline character is CRLF
, that means it's a CHR(13)
followed by CHR(10)
. If you REPLACE(input, CHR(10), '_')
, that turns into CHR(13)
followed by an underscore. Since CR
on its own can be just as well rendered as a newline character, it'll appear to you as if an underscore has ben inserted after your newline, but actually only half of your newline has been replaced.
Use REPLACE(REPLACE(input, CHR(13)), CHR(10))
to replace all CR
's and LF
's.
There is also GLib solution for this case, I did not try it yet, but I believe it is a good solution. https://developer.gnome.org/glib/2.36/glib-Asynchronous-Queues.html#g-async-queue-new
my solution was:
.parent {
display: flex;
flex-wrap: wrap;
}
.product {
width: 240px;
margin-left: auto;
height: 127px;
margin-right: auto;
}
If you are using Marshmallow, you have to either:
This is because in Marshmallow, Google completely revamped how permissions work.
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
The documentation says that the date
method returns a new date set to the current date and time regardless of the language used.
The issue probably sits somewhere where you present the date using NSDateFormatter
. NSDate
is just a point on a time line. There is no time zones when talking about NSDate
. I made a test.
print(NSDate())
Output: 2014-07-23 17:56:45 +0000
NSLog(@"%@", [NSDate date]);
Output: 2014-07-23 17:58:15 +0000
Result - No difference.
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController
@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
@Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.content_name)
@Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController
@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>@ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.content_name)
@Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Solved!
$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
Generally, you need to get a handle to the control via its clientId. This example uses a JSF2 Facelets view with a request-scope binding to get a handle to the other control:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head><title>Show/Hide</title></h:head>
<h:body>
<h:form>
<h:button value="toggle"
onclick="toggle('#{requestScope.foo.clientId}'); return false;" />
<h:inputText binding="#{requestScope.foo}" id="x" style="display: block" />
</h:form>
<script type="text/javascript">
function toggle(id) {
var element = document.getElementById(id);
if(element.style.display == 'block') {
element.style.display = 'none';
} else {
element.style.display = 'block'
}
}
</script>
</h:body>
</html>
Exactly how you do this will depend on the version of JSF you're working on. See this blog post for older JSF versions: JSF: working with component identifiers.
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example. It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
@Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley. https://github.com/evancharlton/folly/
While your Sleep
method is async, Thread.Sleep
is not. The whole idea of async is to reuse a single thread, not to start multiple threads. Because you've blocked using a synchronous call to Thread.Sleep, it's not going to work.
I'm assuming that Thread.Sleep
is a simplification of what you actually want to do. Can your actual implementation be coded as async methods?
If you do need to run multiple synchronous blocking calls, look elsewhere I think!
I solved the problem by covering the download button of a audio controller with a transparent div that changes the symbol of the mouse-cursor to "not-allowed".
The div blocks the activation of the download button.
Height: 50px, Width: 35px, Left: (document-right -60), Top: (same as the audio controller).
You must set the z-index style of the div above the z-index of the audio-controller.
See sapplic.com/jive66 for an example that works for chrome on win7 and on win8.
If you want to solve this without using Ajax, use the FileReader()
Web API.
Example implementation:
.csv
filefunction readSingleFile(e) {_x000D_
var file = e.target.files[0];_x000D_
if (!file) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(e) {_x000D_
var contents = e.target.result;_x000D_
displayContents(contents);_x000D_
displayParsed(contents);_x000D_
};_x000D_
reader.readAsText(file);_x000D_
}_x000D_
_x000D_
function displayContents(contents) {_x000D_
var element = document.getElementById('file-content');_x000D_
element.textContent = contents;_x000D_
}_x000D_
_x000D_
function displayParsed(contents) {_x000D_
const element = document.getElementById('file-parsed');_x000D_
const json = contents.split(',');_x000D_
element.textContent = JSON.stringify(json);_x000D_
}_x000D_
_x000D_
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />_x000D_
_x000D_
<h3>Raw contents of the file:</h3>_x000D_
<pre id="file-content">No data yet.</pre>_x000D_
_x000D_
<h3>Parsed file contents:</h3>_x000D_
<pre id="file-parsed">No data yet.</pre>
_x000D_
Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.
function tree() {
find ${1:-.} | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
}
This works in gitbash too.
Source: Comment from @javasheriff here
As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])
Where the format
param takes any valid standard format string or custom formatting string
Example:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')
Further Reading:
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
This is the safer way:
var elements = document.getElementsByClassName("myclass");
for (var i = 0; i < elements.length; i++) myFunction(elements[i]);
Below function gives the last day of the month :
function getLstDayOfMonFnc(date) {_x000D_
return new Date(date.getFullYear(), date.getMonth(), 0).getDate()_x000D_
}_x000D_
_x000D_
console.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29_x000D_
console.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28_x000D_
console.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30_x000D_
console.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31
_x000D_
Similarly we can get first day of the month :
function getFstDayOfMonFnc(date) {_x000D_
return new Date(date.getFullYear(), date.getMonth(), 1).getDate()_x000D_
}_x000D_
_x000D_
console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1
_x000D_
Complementing (as an algebraic curiosity) the @deceze answer with the @
operator, and indicating cases where is "better" to use @
... Not really better if you need (no log and) micro-performance optimization:
array_key_exists
: is true if a key exists in an array; isset
: is true
if the key/variable exists and is not null
[faster than array_key_exists]; @$array['key']
: is true
if the key/variable exists and is not (null
or '' or 0); [so much slower?] $a = array('k1' => 'HELLO', 'k2' => null, 'k3' => '', 'k4' => 0);
print isset($a['k1'])? "OK $a[k1].": 'NO VALUE.'; // OK
print array_key_exists('k1', $a)? "OK $a[k1].": 'NO VALUE.'; // OK
print @$a['k1']? "OK $a[k1].": 'NO VALUE.'; // OK
// outputs OK HELLO. OK HELLO. OK HELLO.
print isset($a['k2'])? "OK $a[k2].": 'NO VALUE.'; // NO
print array_key_exists('k2', $a)? "OK $a[k2].": 'NO VALUE.'; // OK
print @$a['k2']? "OK $a[k2].": 'NO VALUE.'; // NO
// outputs NO VALUE. OK . NO VALUE.
print isset($a['k3'])? "OK $a[k3].": 'NO VALUE.'; // OK
print array_key_exists('k3', $a)? "OK $a[k3].": 'NO VALUE.'; // OK
print @$a['k3']? "OK $a[k3].": 'NO VALUE.'; // NO
// outputs OK . OK . NO VALUE.
print isset($a['k4'])? "OK $a[k4].": 'NO VALUE.'; // OK
print array_key_exists('k4', $a)? "OK $a[k4].": 'NO VALUE.'; // OK
print @$a['k4']? "OK $a[k4].": 'NO VALUE.'; // NO
// outputs OK 0. OK 0. NO VALUE
PS: you can change/correct/complement this text, it is a Wiki.
let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123@"); //true as it contains all the above
If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...
import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";
You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.
This safeguards use of jQuery and jQuery UI from fighting with VueJS.
Vue.prototype.$fValidateTag = function( sTag, rRules )
{
return ValidateTag( sTag, rRules );
};
function ValidateTag( sTag, rRules )
{
Var rTagT = $( sTag );
return rParentTag.validate( sTag, rRules );
}
the best one :D (RFC-friendly & no error "too complex") :
function isMail(mail)
{
pattuser = /^([A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+\.?)*[A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+$/i;
pattdomain = /^([A-Z0-9-]+\.?)*[A-Z0-9-]+(\.[A-Z]{2,9})+$/i;
tab = mail.split("@");
if (tab.length != 2)
return false;
return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));
}
You can fire chnage event by these methods:
First
$('#selectid').change(function () {
alert('This works');
});
Second
$(document).on('change', '#selectid', function() {
alert('This Works');
});
Third
$(document.body).on('change','#selectid',function(){
alert('This Works');
});
If this methods not working, check your jQuery working or not:
$(document).ready(function($) {
alert('Jquery Working');
});
I don't know if this can be related to the OP's post but I was missing the [HttpGet] annotation and that was what was causing the error, as stated by @dinesh_ravva methods are assumed to be HttpPost by default.
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
While creating a project from a full folder may or may not work within the workspace, there's a condition outside of the workspace that prevents starting a new project with a full folder.
This is relevant if you use numerous folder locations for sources, for example an htdocs or www folder for web projects, and a different location for desktop Java applications.
The condition mentioned occurs when Eclipse is told to create a new project, and given a full folder outside the workspace. Eclipse will say the folder isn't empty, and prevent creating a new project within the given folder. I haven't found a way around this, and any solution requires extra steps.
My favorite solution is as follows
Eclipse should make a new project, and update that project with the new folder contents as it scans for changes. The existing sources are now part of the new project.
Although you had to perform three extra steps, you now have a backup with the original sources available, and are also able to use a copy of them in an existing project. If storage space is a concern, simply move/cut the source rather than fully copy the original folder contents.
You could use the fillna
method on the DataFrame and specify the method as ffill
(forward fill):
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
This method...
propagate[s] last valid observation forward to next valid
To go the opposite way, there's also a bfill
method.
This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify inplace=True
:
df.fillna(method='ffill', inplace=True)
A version in Kotlin, in this algorithm I created a decorator that allows you to set and get variables from the environment.
import java.util.Collections
import kotlin.reflect.KProperty
?
class EnvironmentDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return System.getenv(property.name) ?: "-"
}
?
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
val key = property.name
?
val classes: Array<Class<*>> = Collections::class.java.declaredClasses
val env = System.getenv()
?
val cl = classes.first { "java.util.Collections\$UnmodifiableMap" == it.name }
?
val field = cl.getDeclaredField("m")
field.isAccessible = true
val obj = field[env]
val map = obj as MutableMap<String, String>
map.putAll(mapOf(key to value))
}
}
?
class KnownProperties {
var JAVA_HOME: String by EnvironmentDelegate()
var sample: String by EnvironmentDelegate()
}
?
fun main() {
val knowProps = KnownProperties()
knowProps.sample = "2"
?
println("Java Home: ${knowProps.JAVA_HOME}")
println("Sample: ${knowProps.sample}")
}
The statement:
(my $newstring = $oldstring) =~ s/foo/bar/g;
Which is equivalent to:
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;
Alternatively, as of Perl 5.13.2 you can use /r
to do a non destructive substitution:
use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber
parameter. You can overload the method if you need to support earlier versions.
static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);
// connection string
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
var cnn = new OleDbConnection(cnnStr);
// get schema, then data
var dt = new DataTable();
try {
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheet);
var da = new OleDbDataAdapter(sql, cnn);
da.Fill(dt);
}
catch (Exception e) {
// ???
throw e;
}
finally {
// free resources
cnn.Close();
}
// write out CSV data
using (var wtr = new StreamWriter(csvOutputFile)) {
foreach (DataRow row in dt.Rows) {
bool firstLine = true;
foreach (DataColumn col in dt.Columns) {
if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
wtr.Write(String.Format("\"{0}\"", data));
}
wtr.WriteLine();
}
}
}
For me, it works (java - android)
void RevokeAcess()
{
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
org.apache.http.HttpResponse response = client.execute(post);
}
catch(IOException e)
{
}
CookieManager.getInstance().removeAllCookie(); // this is clear the cookies which tends to same user in android web view
}
You have to call this function in AsyncTask in android
I was facing the same problem, following code worked for me:
$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.
Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):
input {
width: 20px;
position: relative;
left: 200px;
vertical-align: middle;
}
label {
width: 200px;
position: relative;
left: -20px;
display: inline-block;
vertical-align: middle;
}
Create a batch file with the following lines:
start foo.exe
start bar.exe
start baz.exe
The start command runs your command in a new window, so all 3 commands would run asynchronously.
You can do like follow:
String date = DateTime.Now.Date.ToString();
String Month = DateTime.Now.Month.ToString();
String Year = DateTime.Now.Year.ToString();
On the place of datetime you can use your column..
I think actually nvarchar(MAX)
can store approximately 1070000000 chars.
var div = document.createElement('div');
document.body.appendChild(div);
div.style.left = '32px';
div.style.top = '-16px';
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
div.parentNode.removeChild(div);
div = document.getElementById('test');
array = document.getElementsByTagName('div');
array = document.getElementsByClassName('ui-modal');
div = document.querySelector('div #test .ui-modal');
array = document.querySelectorAll('div');
This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.
const absolutePath = path.join(__dirname, some, dir);
vs.
const absolutePath = path.resolve(__dirname, some, dir);
path.join
will concatenate __dirname
which is the directory name of the current file concatenated with values of some
and dir
with platform-specific separator.
Whereas
path.resolve
will process __dirname
, some
and dir
i.e. from right to left prepending it by processing it.
If any of the values of some
or dir
corresponds to a root path then the previous path will be omitted and process rest by considering it as root
In order to better understand the concept let me explain both a little bit more detail as follows:-
The path.join
and path.resolve
are two different methods or functions of the path module provided by nodejs.
Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.
path.join
concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
When no arguments supplied
The following example will help you to clearly understand both concepts:-
My filename is index.js
and the current working directory is E:\MyFolder\Pjtz\node
const path = require('path');
console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname
Result
? node index.js
path.join() : .
path.resolve() : E:\MyFolder\Pjtz\node
path.resolve()
method will output the absolute path whereas the path.join()
returns . representing the current working directory if nothing is provided
When some root path is passed as arguments
const path=require('path');
console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));
Result i
? node index.js
path.join() : abc\bcd
path.resolve() : E:\bcd
path.join()
only concatenates the input list with platform-specific separator while the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
If you have multiple applications on heroku and want to add changes to a particular application, run the following command : heroku git:remote -a appname and then run the following. 1) git add . 2)git commit -m "changes" 3)git push heroku master
I use this.
var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var currentFrame = innerDoc.location.href;
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Seconds with 2 decimal spaces:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer
Milliseconds:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer
Milliseconds with comma seperator:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer
Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.
Use a subquery:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.
For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.
Here is the code for helper:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
if (enabled)
{
return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
}
var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
htmlAttributesAsDict.Add("disabled", "disabled");
string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
htmlAttributesAsDict.Add("id", selectClientId + "_disabled");
var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
}
and usage, goal is to disable select if there is just one item in options, markup:
@Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { @class = "some-class" }, Model.SomeList > 1)
And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):
public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
{
if (disabled)
{
var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
var doc = new HtmlDocument();
doc.LoadHtml(previous.ToString());
var rootElements = doc.DocumentNode.Descendants().Where(
hn => hn.NodeType == HtmlNodeType.Element &&
canBeDisabled.Contains(hn.Name.ToLower()) &&
(disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));
foreach (var element in rootElements)
{
element.SetAttributeValue("disabled", "");
}
string html = doc.DocumentNode.OuterHtml;
return MvcHtmlString.Create(html);
}
return previous;
}
For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:
@Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)
@Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
Uses Guava's static factory methods for Maps and is only 105 characters long.
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = Maps.newHashMap();
The name of the resource is the name space plus the "pseudo" name space of the path to the file. The "pseudo" name space is made by the sub folder structure using \ (backslashes) instead of . (dots).
public static Stream GetResourceFileStream(String nameSpace, String filePath)
{
String pseduoName = filePath.Replace('\\', '.');
Assembly assembly = Assembly.GetExecutingAssembly();
return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName);
}
The following call:
GetResourceFileStream("my.namespace", "resources\\xml\\my.xml")
will return the stream of my.xml located in the folder-structure resources\xml in the name space: my.namespace.
Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.
You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:
How to find the record in a table that contains the maximum value?
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
If you have ruby installed
cat FileWithColumnOfNumbers.txt | xargs ruby -e "puts ARGV.map(&:to_i).inject(&:+)"
I encountered same problem in opening android React Native Project in Android Studio.
The root cause is I opened the root folder of React Native Project instead of android folder of the React Native Project.
Reopen the project under android folder of React Native Project solved my problem.
Sometimes you, also, need to clean this folder: C:\Windows\Temp\Temporary ASP.NET
The __del__
method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.
If you want to delete your object and thus call the __del__
method use
del obj1
which will delete the object (provided there weren't any other references to it).
I suggest you write a small class like this
class T:
def __del__(self):
print "deleted"
And investigate in the python interpreter, eg
>>> a = T()
>>> del a
deleted
>>> a = T()
>>> b = a
>>> del b
>>> del a
deleted
>>> def fn():
... a = T()
... print "exiting fn"
...
>>> fn()
exiting fn
deleted
>>>
Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__
is called. It isn't considered good practice to use __del__
though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__
will be called either - the interpreter can exit in various ways without deleteting all objects.
Can some body explain me the differences between a Document style and RPC style webservices?
There are two communication style models that are used to translate a WSDL binding to a SOAP message body. They are: Document & RPC
The advantage of using a Document style model is that you can structure the SOAP body any way you want it as long as the content of the SOAP message body is any arbitrary XML instance. The Document style is also referred to as Message-Oriented style.
However, with an RPC style model, the structure of the SOAP request body must contain both the operation name and the set of method parameters. The RPC style model assumes a specific structure to the XML instance contained in the message body.
Furthermore, there are two encoding use models that are used to translate a WSDL binding to a SOAP message. They are: literal, and encoded
When using a literal use model, the body contents should conform to a user-defined XML-schema(XSD) structure. The advantage is two-fold. For one, you can validate the message body with the user-defined XML-schema, moreover, you can also transform the message using a transformation language like XSLT.
With a (SOAP) encoded use model, the message has to use XSD datatypes, but the structure of the message need not conform to any user-defined XML schema. This makes it difficult to validate the message body or use XSLT based transformations on the message body.
The combination of the different style and use models give us four different ways to translate a WSDL binding to a SOAP message.
Document/literal
Document/encoded
RPC/literal
RPC/encoded
I would recommend that you read this article entitled Which style of WSDL should I use? by Russell Butek which has a nice discussion of the different style and use models to translate a WSDL binding to a SOAP message, and their relative strengths and weaknesses.
Once the artifacts are received, in both styles of communication, I invoke the method on the port. Now, this does not differ in RPC style and Document style. So what is the difference and where is that difference visible?
The place where you can find the difference is the "RESPONSE"!
RPC Style:
package com.sample;
import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface StockPrice {
public String getStockPrice(String stockName);
public ArrayList getStockPriceList(ArrayList stockNameList);
}
The SOAP message for second operation will have empty output and will look like:
RPC Style Response:
<ns2:getStockPriceListResponse
xmlns:ns2="http://sample.com/">
<return/>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>
Document Style:
package com.sample;
import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.DOCUMENT)
public interface StockPrice {
public String getStockPrice(String stockName);
public ArrayList getStockPriceList(ArrayList stockNameList);
}
If we run the client for the above SEI, the output is:
123 [123, 456]
This output shows that ArrayList elements are getting exchanged between the web service and client. This change has been done only by the changing the style attribute of SOAPBinding annotation. The SOAP message for the second method with richer data type is shown below for reference:
Document Style Response:
<ns2:getStockPriceListResponse
xmlns:ns2="http://sample.com/">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">123</return>
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">456</return>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>
Conclusion
Similarly, in what way SOAP over HTTP differ from XML over HTTP? After all SOAP is also XML document with SOAP namespace. So what is the difference here?
Why do we need a standard like SOAP? By exchanging XML documents over HTTP, two programs can exchange rich, structured information without the introduction of an additional standard such as SOAP to explicitly describe a message envelope format and a way to encode structured content.
SOAP provides a standard so that developers do not have to invent a custom XML message format for every service they want to make available. Given the signature of the service method to be invoked, the SOAP specification prescribes an unambiguous XML message format. Any developer familiar with the SOAP specification, working in any programming language, can formulate a correct SOAP XML request for a particular service and understand the response from the service by obtaining the following service details.
Using SOAP streamlines the process for exposing an existing software component as a Web service since the method signature of the service identifies the XML document structure used for both the request and the response.
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.
try this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/upkia"/>
<corners android:radius="10dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp" />
</shape>
The other answers are correct, as far as they go, but they don't answer why this issue might be occurring, and how to address that root cause.
There are two possible causes to this issue:
brew doctor
suggests, if you run it.If you have multiple user accounts, and you want more than one of them to be able to use brew, you need to run through a few steps, otherwise you will constantly have to change ownership of the Homebrew file structure every time you switch users, and that's not a great idea.
Detailed instructions can be found online, but the quick answer is this:
Create a group named brew:
sudo chgrp -R brew /usr/local
sudo chmod -R g+w /usr/local
sudo chgrp -R brew /Library/Caches/Homebrew
sudo chmod -R g+w /Library/Caches/Homebrew
If you're not trying to use more than one user with Homebrew, then the solution provided by the other answers, based on the suggestions of brew doctor
is probably sufficient:
sudo chown -R $(whoami) /usr/local
sudo chown -R $(whoami) /Library/Caches/Homebrew
After these steps, brew doctor
should report success by any user in the brew group, assuming you've logged out and back in to apply the new group memberships (if you went the multiuser route). If you just corrected things for single user homebrew, then logging out and back in shouldn't be necessary as none of your group memberships have changed.
Just another solution using the datetime
module for Python 3+.
round(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)
To "loop" and take advantage of Spark's parallel computation framework, you could define a custom function and use map.
def customFunction(row):
return (row.name, row.age, row.city)
sample2 = sample.rdd.map(customFunction)
or
sample2 = sample.rdd.map(lambda x: (x.name, x.age, x.city))
The custom function would then be applied to every row of the dataframe. Note that sample2 will be a RDD
, not a dataframe.
Map may be needed if you are going to perform more complex computations. If you just need to add a simple derived column, you can use the withColumn
, with returns a dataframe.
sample3 = sample.withColumn('age2', sample.age + 2)
Downloading java dependencies is possible, if you actually really need to download them into a folder.
Example:
apply plugin: 'java'
dependencies {
runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6'
}
repositories { mavenCentral() }
task getDeps(type: Copy) {
from sourceSets.main.runtimeClasspath
into 'runtime/'
}
Download the dependencies (and their dependencies) into the folder runtime
when you execute gradle getDeps
.
Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.
CIFS on linux information can be found here: http://linux-cifs.samba.org/
If you don't want to validate all the calls to doSomething()
, only the last one, you can just use ArgumentCaptor.getValue()
. According to the Mockito javadoc:
If the method was called multiple times then it returns the latest captured value
So this would work (assumes Foo
has a method getName()
):
ArgumentCaptor<Foo> fooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar, times(2)).doSomething(fooCaptor.capture());
//getValue() contains value set in second call to doSomething()
assertEquals("2nd one", fooCaptor.getValue().getName());
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
If you dont use asp.net or .net core there is also an easy way in >= .Net Standard 2.0 projects.
First you can set the desired size of the hash, salt and iteration number which is related to the duration of the hash generation:
private const int SaltSize = 32;
private const int HashSize = 32;
private const int IterationCount = 10000;
To generare the password hash and salt you can use something like this:
public static string GeneratePasswordHash(string password, out string salt)
{
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, SaltSize))
{
rfc2898DeriveBytes.IterationCount = IterationCount;
byte[] hashData = rfc2898DeriveBytes.GetBytes(HashSize);
byte[] saltData = rfc2898DeriveBytes.Salt;
salt = Convert.ToBase64String(saltData);
return Convert.ToBase64String(hashData);
}
}
To verify if the password which the user entered is valid you can check with the values in your database:
public static bool VerifyPassword(string password, string passwordHash, string salt)
{
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, SaltSize))
{
rfc2898DeriveBytes.IterationCount = IterationCount;
rfc2898DeriveBytes.Salt = Convert.FromBase64String(salt);
byte[] hashData = rfc2898DeriveBytes.GetBytes(HashSize);
return Convert.ToBase64String(hashData) == passwordHash;
}
}
The following unit test shows the usage:
string password = "MySecret";
string passwordHash = PasswordHasher.GeneratePasswordHash(password, out string salt);
Assert.True(PasswordHasher.VerifyPassword(password, passwordHash, salt));
Assert.False(PasswordHasher.VerifyPassword(password.ToUpper(), passwordHash, salt));
It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []
. So assuming that you have list1 that you want to append to the list for 'MORPHINE'
you should do:
drug_dictionary['MORPHINE'].append(list1)
You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0]
etc.
To traverse the lists stored against key you would do:
for listx in drug_dictionary['MORPHINE'] :
do stuff on listx
Found a better solution, which works across all browsers.
Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.
function createCSSSelector (selector, style) {
if (!document.styleSheets) return;
if (document.getElementsByTagName('head').length == 0) return;
var styleSheet,mediaType;
if (document.styleSheets.length > 0) {
for (var i = 0, l = document.styleSheets.length; i < l; i++) {
if (document.styleSheets[i].disabled)
continue;
var media = document.styleSheets[i].media;
mediaType = typeof media;
if (mediaType === 'string') {
if (media === '' || (media.indexOf('screen') !== -1)) {
styleSheet = document.styleSheets[i];
}
}
else if (mediaType=='object') {
if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
styleSheet = document.styleSheets[i];
}
}
if (typeof styleSheet !== 'undefined')
break;
}
}
if (typeof styleSheet === 'undefined') {
var styleSheetElement = document.createElement('style');
styleSheetElement.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(styleSheetElement);
for (i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].disabled) {
continue;
}
styleSheet = document.styleSheets[i];
}
mediaType = typeof styleSheet.media;
}
if (mediaType === 'string') {
for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
styleSheet.rules[i].style.cssText = style;
return;
}
}
styleSheet.addRule(selector,style);
}
else if (mediaType === 'object') {
var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
for (var i = 0; i < styleSheetLength; i++) {
if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
styleSheet.cssRules[i].style.cssText = style;
return;
}
}
styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
}
}
Function is used as follows.
createCSSSelector('.mycssclass', 'display:none');
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
du -s -- * | sort -n
(this willnot show hidden (.dotfiles) files)
Use du -sm
for Mb units etc. I always use
du -smc -- * | sort -n
because the total line (-c
) will end up at the bottom for obvious reasons :)
Try this:
body
{
font-family:your font;
font-size:your value;
font-weight:your value;
}
I haven't seen this anywhere, either, but my instinct would be that this means that the IF
prevented the whole statement from executing.
Try to run the statement with a database where the IF
passes.
Also check if there are any triggers involved which might change the result.
[EDIT] When the standard says that this function should never return -1
, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.
If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF
returns false
and one where it returns true
).
If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.
You should use "Microsoft OLE DB Provider for ODBC Drivers" to get to access to Microsoft Access. Here is the sample tutorial on using it
http://msdn.microsoft.com/en-us/library/aa288452(v=vs.71).aspx
Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
You can use the function MROUND(<reference cell>, <round to multiple of digit needed>)
.
Example:
For a value A1 = 21
round to multiple of 10 it would be written as
=MROUND(A1,10)
for which Result = 20
For a value Z4 = 55.1
round to multiple of 10 it would be written as
=MROUND(Z4,10)
for which Result = 60
Building onto answer from @zeusstl, for multiple images uploaded:
function img_resize()
{
$input = 'input-upload-img1'; // Name of input
$maxDim = 400;
foreach ($_FILES[$input]['tmp_name'] as $file_name){
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
}
}
Above solution didn't work for me. So what I did is take ProgressDialog
as globally and then add this to my activity
@Override
protected void onDestroy() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
super.onDestroy();
}
so that in case if activity is destroyed then the ProgressDialog will also be destroy.
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
I did everything from visiting http://www.google.com/accounts/DisplayUnlockCaptcha to setting up 2-fa and creating an application password. The only thing that worked was logging into http://mail.google.com and sending an email from the server itself.
I know this is a somewhat old thread, but I had this problem too with a c#/WPF app I was creating. The app worked fine on the development machine, but would not start on the test machine. The Application Log in the Event Viewer gave a somewhat nebulous .NET Runtime error of System.IO.DirectoryNotFoundException.
I tried using some debugging software but the app would not stay running long enough to attach the debugger to the process. After banging my head against my desk for a day and looking at many web pages like this one, what I wound up doing to troubleshoot this was to install VS2019 on my test machine. I then dragged the .exe file from its folder (it was deep in the Users[user]\AppData\Apps\2.0... folder) to the open VS2019 instance and went to start it from there. Immediately, it came up with a dialog box giving the exception and the cause.
In my case, when I added an icon to one of the forms, the complete path to the icon was placed into the XAML instead of just the icon name. I had copied the icon file into the project folder, but since the project folder does not exist on the test machine, this was the root cause of the error. I then removed the path from the XAML, leaving just the icon name one, rebuilt the solution and re-published it, and it ran just fine on the test machine now. Of course there are many causes besides what gave me the error, but this method of troubleshooting should hopefully identify the root cause of the error, since the Windows Event Viewer gives a somewhat vague answer.
To summarize, use Visual Studio on the test machine as a debugger of sorts. But, to get it to work right, I had to drag the .exe file into the IDE and Start (run) it from there. I believe this will also work with VS2017 as well as VS2019. Hopefully this helps someone who is still having this issue.
<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
Here are the possible ways to take a unique pointer as an argument, as well as their associated meaning.
Base(std::unique_ptr<Base> n)
: next(std::move(n)) {}
In order for the user to call this, they must do one of the following:
Base newBase(std::move(nextBase));
Base fromTemp(std::unique_ptr<Base>(new Base(...));
To take a unique pointer by value means that you are transferring ownership of the pointer to the function/object/etc in question. After newBase
is constructed, nextBase
is guaranteed to be empty. You don't own the object, and you don't even have a pointer to it anymore. It's gone.
This is ensured because we take the parameter by value. std::move
doesn't actually move anything; it's just a fancy cast. std::move(nextBase)
returns a Base&&
that is an r-value reference to nextBase
. That's all it does.
Because Base::Base(std::unique_ptr<Base> n)
takes its argument by value rather than by r-value reference, C++ will automatically construct a temporary for us. It creates a std::unique_ptr<Base>
from the Base&&
that we gave the function via std::move(nextBase)
. It is the construction of this temporary that actually moves the value from nextBase
into the function argument n
.
Base(std::unique_ptr<Base> &n)
: next(std::move(n)) {}
This has to be called on an actual l-value (a named variable). It cannot be called with a temporary like this:
Base newBase(std::unique_ptr<Base>(new Base)); //Illegal in this case.
The meaning of this is the same as the meaning of any other use of non-const references: the function may or may not claim ownership of the pointer. Given this code:
Base newBase(nextBase);
There is no guarantee that nextBase
is empty. It may be empty; it may not. It really depends on what Base::Base(std::unique_ptr<Base> &n)
wants to do. Because of that, it's not very evident just from the function signature what's going to happen; you have to read the implementation (or associated documentation).
Because of that, I wouldn't suggest this as an interface.
Base(std::unique_ptr<Base> const &n);
I don't show an implementation, because you cannot move from a const&
. By passing a const&
, you are saying that the function can access the Base
via the pointer, but it cannot store it anywhere. It cannot claim ownership of it.
This can be useful. Not necessarily for your specific case, but it's always good to be able to hand someone a pointer and know that they cannot (without breaking rules of C++, like no casting away const
) claim ownership of it. They can't store it. They can pass it to others, but those others have to abide by the same rules.
Base(std::unique_ptr<Base> &&n)
: next(std::move(n)) {}
This is more or less identical to the "by non-const l-value reference" case. The differences are two things.
You can pass a temporary:
Base newBase(std::unique_ptr<Base>(new Base)); //legal now..
You must use std::move
when passing non-temporary arguments.
The latter is really the problem. If you see this line:
Base newBase(std::move(nextBase));
You have a reasonable expectation that, after this line completes, nextBase
should be empty. It should have been moved from. After all, you have that std::move
sitting there, telling you that movement has occurred.
The problem is that it hasn't. It is not guaranteed to have been moved from. It may have been moved from, but you will only know by looking at the source code. You cannot tell just from the function signature.
unique_ptr
, take it by value.unique_ptr
for the duration of that function's execution, take it by const&
. Alternatively, pass a &
or const&
to the actual type pointed to, rather than using a unique_ptr
.&&
. But I strongly advise against doing this whenever possible.You cannot copy a unique_ptr
. You can only move it. The proper way to do this is with the std::move
standard library function.
If you take a unique_ptr
by value, you can move from it freely. But movement doesn't actually happen because of std::move
. Take the following statement:
std::unique_ptr<Base> newPtr(std::move(oldPtr));
This is really two statements:
std::unique_ptr<Base> &&temporary = std::move(oldPtr);
std::unique_ptr<Base> newPtr(temporary);
(note: The above code does not technically compile, since non-temporary r-value references are not actually r-values. It is here for demo purposes only).
The temporary
is just an r-value reference to oldPtr
. It is in the constructor of newPtr
where the movement happens. unique_ptr
's move constructor (a constructor that takes a &&
to itself) is what does the actual movement.
If you have a unique_ptr
value and you want to store it somewhere, you must use std::move
to do the storage.
Works in all modern browsers
.rotate{
animation: loading 3s linear infinite;
@keyframes loading {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
}
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
Example.
var request = require('request');
var url = "http://localhost:3000";
var requestData = {
...
}
var data = {
url: url,
json: true,
body: JSON.stringify(requestData)
}
request.post(data, function(error, httpResponse, body){
console.log(body);
});
As inserting json: true
option,
sets body to JSON representation of value and adds "Content-type": "application/json"
header. Additionally, parses the response body as JSON.
LINK
if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful
File file = ResourceUtils.getFile("classpath:config/sample.txt")
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void
.
Then in your Ajax call please mention dataType='text'
.
It will resolve the problem.
this will be slow, but if it is a one time thing, try...
select * from parameters where name like '%'+char(13)+'%' or name like '%'+char(10)+'%'
Note that the ANSI SQL string concatenation operator is "||", so it may need to be:
select * from parameters where name like '%' || char(13) || '%' or name like '%' || char(10) || '%'
I would go with the function Get-RegistryValue
. In fact it gets requested values (so that it can be used not only for testing). As far as registry values cannot be null, we can use null result as a sign of a missing value. The pure test function Test-RegistryValue
is also provided.
# This function just gets $true or $false
function Test-RegistryValue($path, $name)
{
$key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
$key -and $null -ne $key.GetValue($name, $null)
}
# Gets the specified registry value or $null if it is missing
function Get-RegistryValue($path, $name)
{
$key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
if ($key) {
$key.GetValue($name, $null)
}
}
# Test existing value
Test-RegistryValue HKCU:\Console FontFamily
$val = Get-RegistryValue HKCU:\Console FontFamily
if ($val -eq $null) { 'missing value' } else { $val }
# Test missing value
Test-RegistryValue HKCU:\Console missing
$val = Get-RegistryValue HKCU:\Console missing
if ($val -eq $null) { 'missing value' } else { $val }
OUTPUT:
True
54
False
missing value
I encountered this issue with entity framework when typing migration commands in Nuget console.
the problem showed up when I moved my OAuthAuthorizationServerProvider
codes from my application into a class library project which contained core data access logic as well as my DBContext class.
I check all my DLLs referenced by the class library project. and for all of them (except .net system DLLs) CopyToLocal was true I was completely confused.
I knew that there was something wrong with DLLs themselves not my codes. I checked them again and I noticed that when I moved my ApplicationOauthProvider
class into a class library project the ApplicationOauthProvider
inherits from OAuthAuthorizationServerProvider
class which is located in Microsoft.Owin.Security.OAuth
assembly, I checked it's package version and suddenly noticed that the version of package that I used for the class library project (not my application project) is very old 2.1, but on my application the latest version was installed (3.0.1) so I upgraded version of the Microsoft.Owin.Security.OAuth
package from Nuget fo my class library project and problem got away
In short after checking CopyToLocal
property of your DLLs check their versions too and update the old ones to letest version
For those who uses last versions of spring boot will help this:
.properties:
spring.jpa.properties.hibernate.default_schema=<name of your schema>
.yml:
spring:
jpa:
properties:
hibernate:
default_schema: <name of your schema>
You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.
You can use the Get-InstalledModule
If (-not(Get-InstalledModule SomeModule -ErrorAction silentlycontinue)) {
Write-Host "Module does not exist"
}
Else {
Write-Host "Module exists"
}
I managed to get a good result with the following sequence (run Matlab twice at the beginning):
h = gcf; % Current figure handle
set(h,'Resize','off');
set(h,'PaperPositionMode','manual');
set(h,'PaperPosition',[0 0 9 6]);
set(h,'PaperUnits','centimeters');
set(h,'PaperSize',[9 6]); % IEEE columnwidth = 9cm
set(h,'Position',[0 0 9 6]);
% xpos, ypos must be set
txlabel = text(xpos,ypos,'$$[\mathrm{min}]$$','Interpreter','latex','FontSize',9);
% Dump colored encapsulated PostScript
print('-depsc2','-loose', 'signals');
You could remove bcrypt entirely and install bcryptjs. It is ~30% slower, but has no dependencies, so no pains installing it.
npm i -S bcryptjs && npm uninstall -S bcrypt
We've installed it successfully for our applications. We had issues with bcrypt not compiling on AWS instances for Node v8.x
This works for me and runs client-side: http://www.convertcsv.com/csv-to-json.htm
You might find this Wikipedia article on salting worthwhile. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}
For kotlin I use the following
val fcmtoken = FirebaseMessaging.getInstance().token.await()
and for the extension functions
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
I use Octave, but Matlab has the same syntax.
Create 3d matrix:
octave:3> m = ones(2,3,2)
m =
ans(:,:,1) =
1 1 1
1 1 1
ans(:,:,2) =
1 1 1
1 1 1
Now, say I have a 2D matrix that I want to expand in a new dimension:
octave:4> Two_D = ones(2,3)
Two_D =
1 1 1
1 1 1
I can expand it by creating a 3D matrix, setting the first 2D in it to my old (here I have size two of the third dimension):
octave:11> Three_D = zeros(2,3,2)
Three_D =
ans(:,:,1) =
0 0 0
0 0 0
ans(:,:,2) =
0 0 0
0 0 0
octave:12> Three_D(:,:,1) = Two_D
Three_D =
ans(:,:,1) =
1 1 1
1 1 1
ans(:,:,2) =
0 0 0
0 0 0
Curl is a non-java program and must be provided outside your Java program.
You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)
You can also send (POST
) multiple params within {}
and add it.
Example:
$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
.then(function(response) {
NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
}, function(response) {
});
where employeeId
, bType
(Badge Catagory), and badge
are three parameters.
Swift 4.2
guard let someVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "someVC") as? someVC else {
return
}
someVC.modalPresentationStyle = .overCurrentContext
present(someVC, animated: true, completion: nil)
If you are making the fetch call to your localhost which I'm guessing is run by node.js in the same directory as your backbone code, than it will most likely be on http://localhost:3000
or something like that. Than this should be your model:
var model = Backbone.Model.extend({
url: '/item'
});
And in your node.js you now have to accept that call like this:
app.get('/item', function(req, res){
res.send('some info here');
});
Perhaps the best two browser techs for this are Canvas, with Flash as a back up.
We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.
With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)J(2)EE, strictly speaking, is a set of API
s (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.
In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!
J2EE was a marketing construct.
Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll()
when you click on a label, right?
Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label
<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
Select All
</label>
As Sayse mentioned, exit code 259 (0x103)
has special meaning, in this case the process being debugged is still running.
I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).
It is possible by dumping, editing and reimporting the table.
This script will do it for you (Adapt the values at the start of the script to your needs):
#!/bin/bash
DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql
echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP
echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP
read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key
echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"
echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
echo "DROP INDEX '$idx';" | sqlite3 $DB
done
echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}
An example of how you might use this:
var test = JoinDataTables(transactionInfo, transactionItems,
(row1, row2) =>
row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));
One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.
What one program writes to stdout can be read by another via stdin. So simply, using c, write prog1
to print something using printf()
and prog2
to read something using scanf()
. Then just run
./prog1 | ./prog2
>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.
string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
if(!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("user", "role1");
UserManager.AddToRole("user", "role2");
context.SaveChanges();
If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook
with export VARIABLE=value
in .bashrc
.
In my case tensorflow needs the exported variable for successful importing it in a notebook.
It works like this:
h4 {
display:inline;
}
h4:after {
content:"\a";
white-space: pre;
}
Example: http://jsfiddle.net/Bb2d7/
The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)
If all else fails, you can always submit a query, limiting the return rows to none:
select * from MYTABLENAME limit 0
As has already been mentioned in these answers, you just need the right font name. I find that iOSFonts.com is the most helpful resource for knowing exactly what name to use.
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.
:set t_Co=256
After that you can to change your background.
Something like this:
array.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1;
if (nameA > nameB)
return 1;
return 0; //default return value (no sorting)
});
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size)
:
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List
.
Step 1: create a MANIFEST.in
file in the same folder with setup.py
Step 2: include the relative path to the files you want to add in MANIFEST.in
include README.rst
include docs/*.txt
include funniest/data.json
Step 3: set include_package_data=True
in the setup()
function to copy these files to site-package
Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.
Please see the below example code for Windows IIS Servers with Web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="1024" maxUrl="2048">
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
This would also work on a server level using machine.config.
Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.
It happens when $ret
hasn't been defined. The solution is simple. Right above $tags = get_tags();
, add the following line:
$ret = array();
Session.Remove("name of your session here");
const arrayOfObjects = [
{name: 'test'},
{name: 'test2'}
]
const order = ['test2', 'test']
const setOrder = (arrayOfObjects, order) =>
arrayOfObjects.sort((a, b) => {
if (order.findIndex((i) => i === a.name) < order.findIndex((i) => i === b.name)) {
return -1;
}
if (order.findIndex((i) => i === a.name) > order.findIndex((i) => i === b.name)) {
return 1;
}
return 0;
});
Below Different tools for Editing Rdlc report:
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script>
tag at the end of the popup's HTML, and call window.print()
inside it. Then it won't be called until the HTML has loaded.
Just in case if someone stumbles onto this thread then here is a bullet proof solution to SQL Server stuck in SINGLE USER MODE
-- Get the process ID (spid) of the connection you need to kill
-- Replace 'DBName' with the actual name of the DB
SELECT sd.[name], sp.spid, sp.login_time, sp.loginame
FROM sysprocesses sp
INNER JOIN sysdatabases sd on sp.dbid = sd.dbid
WHERE sd.[name] = 'DBName'
As an alternative, you can also use the command “sp_who” to get the “spid” of the open connection:
-- Or use this SP instead
exec sp_who
-- Then Execute the following and replace the [spid] and [DBName] with correct values
KILL SpidToKillGoesHere
GO
SET DEADLOCK_PRIORITY HIGH
GO
ALTER DATABASE [DBName] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO
This will return true only if host responds to ping. Works on windows and linux
def ping(host):
"""
Returns True if host (str) responds to a ping request.
NB on windows ping returns true for success and host unreachable
"""
param = '-n' if platform.system().lower()=='windows' else '-c'
result = False
try:
out = subprocess.check_output(['ping', param, '1', host])
#ping exit code 0
if 'Reply from {}'.format(host) in str(out):
result = True
except subprocess.CalledProcessError:
#ping exit code not 0
result = False
#print(str(out))
return result
You can also start a server without python using php interpreter.
E.g:
cd /your/path/to/website/root
php -S localhost:8000
This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
Per issue 12987, Blundell's answer crashes (at least on my 2.3 VM). Instead, I intercept a call to console.log with a special prefix:
// intercept calls to console.log
web.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cmsg)
{
// check secret prefix
if (cmsg.message().startsWith("MAGIC"))
{
String msg = cmsg.message().substring(5); // strip off prefix
/* process HTML */
return true;
}
return false;
}
});
// inject the JavaScript on page load
web.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String address)
{
// have the page spill its guts, with a secret prefix
view.loadUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
}
});
web.loadUrl("http://www.google.com");
Not sure if I get you right, but the simplest way would be something like:
<c:if test="${languageBean.locale == 'en'">
<f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>
Just a quick copy and paste from an app of mine...
HTH
I was facing this issue when I added Nuget package Newtonsoft.Json 12.0.0.2 into my two .netstandard library projects and it grabbed almost my full day to solve this issue.
Exception -: Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.
Solution -: I had to remove package from Nuget and went to the following location and followed the next steps -
Step 1. Go to location "C:\Users[UserName].nuget\packages\newtonsoft.json\12.0.2\lib" and here you will get all Nuget versions you installed previously.
Step 2. Since i wanted to use it in my .netstandard 2.0 library project, so i copied "netstandard2.0" folder from this location and paste somewhere my preferred location (**where i generally keep 3rd party dlls).
Step 3. Now i added DLL reference from here to my both project and this way problem solved.
Thanks
Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf
as well.
Try this:
List<Thread> myThreads = new List<Thread>();
foreach (Thread curThread in myThreads)
{
curThread.Start();
}
foreach (Thread curThread in myThreads)
{
curThread.Join();
}
Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).
A complete solution to changing/switching videos in HTML5 video tags via javascript can be found here and is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).
If this helps, or if you're having trouble, please let me know.
Add include_directories("/your/path/here")
.
This will be similar to calling gcc
with -I/your/path/here/
option.
Make sure you put double quotes around the path. Other people didn't mention that and it made me stuck for 2 days. So this answer is for people who are very new to CMake and very confused.
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
If you don't care about timezone, or want to use the time zone your server uses:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324 (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
I just restarted the adb (Android Debug Bridge) this way:
and it works again!