My problem solved with multiple execute of limited deletes like
Before
DELETE FROM TableName WHERE Condition
After
DELETE TOP(1000) FROM TableName WHERECondition
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
I have just found ActiveSharp - Automatic INotifyPropertyChanged, I have yet to use it, but it looks good.
To quote from it's web site...
Send property change notifications without specifying property name as a string.
Instead, write properties like this:
public int Foo
{
get { return _foo; }
set { SetValue(ref _foo, value); } // <-- no property name here
}
Note that there is no need to include the name of the property as a string. ActiveSharp reliably and correctly figures that out for itself. It works based on the fact that your property implementation passes the backing field (_foo) by ref. (ActiveSharp uses that "by ref" call to identify which backing field was passed, and from the field it identifies the property).
Just to make this thread more complete i am adding my version of answer:
What i wanted to achieve: The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.
Solution:
The solution is an extremely small extension to F1sher's solution:
=> First step is to integrate F1sher's solution.
=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:
size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(size.width, size.height);
mCamera.setParameters(parameters);
double screenRatio = (double) screenHeight / screenWidth;
double previewRatio = (double) size.height / size.width;
if (previewRatio > screenRatio) /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
else /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
flPreview.addView(mPreview);
/* The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView */
In kotlin you can use unaryPlus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
This is a simple solution:
Example 1
my $var1 = "123abc";
print $var1 + 0;
Result
123
Example 2
my $var2 = "abc123";
print $var2 + 0;
Result
0
With Windows 8.1 I couldn't find any .exd files using windows search. On the other hand, a cmd command dir *.exd /S
found the one file on my system.
This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");
You could start by reading the documentation for Date. Then you realize that Date’s methods are all deprecated and turn to Calender instead.
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.DAY_OF_MONTH));
As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
array([[ 0, 2],
[ 4, 6],
[12, 14]])
np.ix_
I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])]
returns the array[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]
.
So you use it like this:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))
Also, as MikeC says in a comment, np.ix_
has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:
>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a
array([[-1, 1, -1, 3],
[-1, 5, -1, 7],
[ 8, 9, 10, 11],
[-1, 13, -1, 15],
[16, 17, 18, 19]])
This will work
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
A very portable version (even to legacy bourne shell):
if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then do-something
fi
This has the additional quality of running only one subprocess at most (which is the process [
), whatever the shell flavor.
Replace =
with -eq
if variables contain numeric values, e.g.
3 -eq 03
is true, but3 = 03
is false. (string comparison)in dir bootstrap\autoload.php
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add
add this file
app\Helpers\function.php
We can pass headers as arguments,
onClickHandler = () => {
const data = new FormData()
for(var x = 0; x<this.state.selectedFile.length; x++) {
data.append('file', this.state.selectedFile[x])
}
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post("http://localhost:8000/upload", data, options, {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
})
},
})
.then(res => { // then print response status
console.log('upload success')
})
.catch(err => { // then print response status
console.log('upload fail with error: ',err)
})
}
How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."
And what is the role of the FollowSymLinks setting in this?
FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.
The only way I got it to work...
RewriteEngine On
RewriteCond %{HTTP_HOST} ^site\.ro
RewriteRule (.*) http://www.site.ro/$1 [R=301,L]
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
You can load jpeg binary data as a file and parse the jpeg headers yourself. The one you are looking for is the 0xFFC0 or Start of Frame header:
Start of frame marker (FFC0)
* the first two bytes, the length, after the marker indicate the number of bytes, including the two length bytes, that this header contains
* P -- one byte: sample precision in bits (usually 8, for baseline JPEG)
* Y -- two bytes
* X -- two bytes
* Nf -- one byte: the number of components in the image
o 3 for color baseline JPEG images
o 1 for grayscale baseline JPEG images
* Nf times:
o Component ID -- one byte
o H and V sampling factors -- one byte: H is first four bits and V is second four bits
o Quantization table number-- one byte
The H and V sampling factors dictate the final size of the component they are associated with. For instance, the color space defaults to YCbCr and the H and V sampling factors for each component, Y, Cb, and Cr, default to 2, 1, and 1, respectively (2 for both H and V of the Y component, etc.) in the Jpeg-6a library by the Independent Jpeg Group. While this does mean that the Y component will be twice the size of the other two components--giving it a higher resolution, the lower resolution components are quartered in size during compression in order to achieve this difference. Thus, the Cb and Cr components must be quadrupled in size during decompression.
For more info about the headers check out wikipedia's jpeg entry or I got the above info here.
I used a method similar to the code below which I got from this post at the sun forums:
import java.awt.Dimension;
import java.io.*;
public class JPEGDim {
public static Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
public static void main(String[] args) throws IOException {
System.out.println(getJPEGDimension(new File(args[0])));
}
}
Delete the .sdf file that is in your solution directory. It's just the Intellisense database, and Visual Studio will recreate it the next time you open that solution. This db can get corrupted and cause the IDE to not be able to find things, and since the compiler generates this information for itself on the fly, it wouldn't be affected.
On IntelliJ go to Preference -> Build, Execution, Deployment -> Build Tools -> Maven. Turn on the checkbox for "Always update snapshots" apply and save changes then do mvn clean install
This worked for me like a charm for downloading PNG and PDF.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url)); //Absolute URL
ob_clean();
flush();
readfile($file_url); //Absolute URL
exit();
Set a breakpoint on the last line of code.
Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:
String.prototype.format = function(placeholders) {
var s = this;
for(var propertyName in placeholders) {
var re = new RegExp('{' + propertyName + '}', 'gm');
s = s.replace(re, placeholders[propertyName]);
}
return s;
};
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) {_x000D_
var s = this;_x000D_
for(var propertyName in placeholders) {_x000D_
var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
s = s.replace(re, placeholders[propertyName]);_x000D_
} _x000D_
return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
I had Node.js 6.x installed and wanted to install Node.js 8.x.
Here's the commands I used (taken from Nodejs's site with a few extra steps to handle the yum cached data):
sudo yum remove nodejs
: Uninstall Node.js 6.x (I don't know if this was necessary or not)curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
sudo yum clean all
sudo yum makecache
: Regenerate metadata cache (this wasn't in the docs, but yum kept trying to install Node.jx 6.x, unsuccessfully, until I issued these last two commands)sudo yum install nodejs
: Install Node.js 8.xPattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);
This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.
replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings )
Working example: https://codesandbox.io/s/ov7zxp9mjq
function replaceAt(indexArray, [...string]) {
const replaceValue = i => string[i] = <b>{string[i]}</b>;
indexArray.forEach(replaceValue);
return string;
}
And here is another alternate method
function replaceAt(indexArray, [...string]) {
const startTag = '<b>';
const endTag = '</b>';
const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
indexArray.forEach(tagLetter);
return string.join('');
}
And another...
function replaceAt(indexArray, [...string]) {
for (let i = 0; i < indexArray.length; i++) {
string = Object.assign(string, {
[indexArray[i]]: <b>{string[indexArray[i]]}</b>
});
}
return string;
}
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
To initialize a numpy array with a specific matrix:
import numpy as np
mat = np.array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]])
print mat.shape
print mat
output:
(5, 5)
[[1 1 0 0 0]
[0 1 0 0 1]
[1 0 0 1 1]
[0 0 0 0 0]
[1 0 1 0 1]]
The "no frills" options are as follows:
ActiveSheet.Name = "New Name"
and
Sheets("Sheet2").Name = "New Name"
You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.
There are two easy ways:
In your cpanel Go to cpanel/ softaculous/ wordpress, under the current installation, you will see the websites you have installed with the wordpress. Click the "edit detail" of the particular website and you will see your SQL database username and password.
In your server Access your FTP and view the wp-config.php
event viewer shows Logon failure - the user has not been granted the requested logon type at this computer
Here, the myThing variable is private and is part of the closure:
class Person {
constructor() {
var myThing = "Hello World";
return {
thing: myThing,
sayThing: this.sayThing
}
}
sayThing() {
console.log(this.thing);
}
}
var person = new Person();
console.log(person);
A bit late here, but none of the above seemed to work. Try this, using printf, inserts spaces between each. I chose to not have newline at the end.
awk '{for(i=3;i<=NF;++i) printf("%s ", $i) }'
There are two main options:
.NET >= 4.0 Dynamic LINQ:
var people = people.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();
You can also get it by NuGet.
.NET < 4.0 Extension Methods:
private static readonly Hashtable accessors = new Hashtable();
private static readonly Hashtable callSites = new Hashtable();
private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(string name) {
var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
if(callSite == null)
{
callSites[name] = callSite = CallSite<Func<CallSite, object, object>>.Create(
Binder.GetMember(CSharpBinderFlags.None, name, typeof(AccessorCache),
new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
}
return callSite;
}
internal static Func<dynamic,object> GetAccessor(string name)
{
Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
lock (accessors )
{
accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
if(name.IndexOf('.') >= 0) {
string[] props = name.Split('.');
CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked);
accessor = target =>
{
object val = (object)target;
for (int i = 0; i < arr.Length; i++)
{
var cs = arr[i];
val = cs.Target(cs, val);
}
return val;
};
} else {
var callSite = GetCallSiteLocked(name);
accessor = target =>
{
return callSite.Target(callSite, (object)target);
};
}
accessors[name] = accessor;
}
}
}
return accessor;
}
public static IOrderedEnumerable<dynamic> OrderBy(this IEnumerable<dynamic> source, string property)
{
return Enumerable.OrderBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(this IEnumerable<dynamic> source, string property)
{
return Enumerable.OrderByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(this IOrderedEnumerable<dynamic> source, string property)
{
return Enumerable.ThenBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(this IOrderedEnumerable<dynamic> source, string property)
{
return Enumerable.ThenByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
You can practice Regex In Visual Studio and Visual Studio Code using find/replace.
You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here
I'm posting this since I have always been struggling when renaming a project in XCode
.
Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.
REF links:
Rename Project.
Rename Source Folder and other files.
1- Backup your project.
If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).
2- Open your project.
3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.
NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.
4- Rename the Scheme
a) Click the menu right next to the stop button and select Manage Schemes.
b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.
c) Click ok.
5 - Build and run to make sure it works.
NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.
6- Close the project.
7- Rename the main and the source folder.
8- Right click the project bundle .xcodeproj
file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.
9- Search and replace any occurrence of the original folder name with the new folder name.
10- Save the file.
11- Open XCode project, test it.
12- Done.
There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer
Likewise, here's a 2nd caveat to @Artif3x elaboration of @max-malysh's excellent answer, both above.
With any delayed application of transactions from the master the follower(s) will have an older, stale view of the data. Therefore while providing time for the query on the follower to finish by setting max_standby_archive_delay and max_standby_streaming_delay makes sense, keep both of these caveats in mind:
If the value of the follower for backup ends up being too much in conflict with hosting queries, one solution would be multiple followers, each optimized for one or the other.
Also, note that several queries in a row can cause the application of wal entries to keep being delayed. So when choosing the new values, it’s not just the time for a single query, but a moving window that starts whenever a conflicting query starts, and ends when the wal entry is finally applied.
I had this problem today, where I had updated a submodule, but wasn't on any branch. I had already committed, so stashing, checkout, unstashing wouldn't work. I ended up cherry-picking the detached head's commit. So immediately after I committed (when the push failed), I did:
git checkout master
git cherry-pick 99fe23ab
My thinking went: I'm on a detached head, but I want to be on master. Assuming my detached state is not very different from master, if I could apply my commit to master, I'd be set. This is exactly what cherry-pick does.
The idea of your first snippet is right. You probably meant to check iByteCount == -1
: whether the file has at least one byte:
if (iByteCount == -1)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
Here I can add Resolutions and Display Specifications for iphone 6 & 6+ size:
iPhone 6+ - Asset Resolution (@3x) - Resolution (2208 x 1242)px
iPhone 6 - Asset Resolution (@2x) - Resolution (1334 x 750)px
iPad Air / Retina iPad (1st & 2nd Generation / 3rd & 4th) - Asset Resolution (@2x) - Resolution (2048 x 1536)px
iPad Mini (2nd & 3rd Generation) - Asset Resolution (@2x) - Resolution (2048 x 1536)px
iPhone (6, 5S, 5, 5C, 4S, 4) - App Icon (120x120 px) - AppStore Icon (1024x1024 px) - Spotlight (80x80 px) - Settings (58x58 px)
iPhone (6+) - App Icon (180x180 px) - AppStore Icon (1024x1024 px) - Spotlight (120x120 px) - Settings (87x87 px)
Add the class constraint as the first constraint to your generic type.
static T FindThing<T>(IList collection, int id) where T : class, IThing, new()
The problem is that you're calling List<T>.Reverse()
which returns void
.
You could either do:
List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();
or:
IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();
The latter is more expensive, as reversing an arbitrary IEnumerable<T>
involves buffering all of the data and then yielding it all - whereas List<T>
can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>()
extension method, instead of the List<T>.Reverse()
instance method.)
More efficient yet, you could use:
string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();
This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.
A quick addition to @Cem Catikka's comment, when using ExpectedException:
Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired(required = true)
private BizService svc;
@Test
public void testValidateRequest() throws Exception {
thrown.expect(BizException.class);
thrown.expectMessage(expectMessage);
BizRequest request = /* Mock it, read from source - file, etc. */;
validateRequest(request);
}
private void validateRequest(BizRequest request) throws Exception {
Method method = svc.getClass().getDeclaredMethod("validateRequest", BizRequest.class);
method.setAccessible(true);
try {
method.invoke(svc, request);
}
catch (InvocationTargetException e) {
throw ((BizException)e.getCause());
}
}
To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});
To prevent the script from failing when the script file resides on a non system drive (c:) and in a directory with spaces.
Batch_Script_Run_As_Admin.cmd
@echo off
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
::ENTER YOUR CODE BELOW::
::END OF YOUR CODE::
echo.
echo...Script Complete....
echo.
pause
From Java 8 onward you can try the following:
import java.time.*;
import java.time.temporal.ChronoUnit;
Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();
System.out.println(Duration.between(start_time, stop_time).toMillis());
//or
System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));
From the help (if /?
):
The ELSE clause must occur on the same line as the command after the IF. For example: IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. ) The following would NOT work because the del command needs to be terminated by a newline: IF EXIST filename. del filename. ELSE echo filename. missing Nor would the following work, since the ELSE command must be on the same line as the end of the IF command: IF EXIST filename. del filename. ELSE echo filename. missing
In fact the "[" square opening bracket is just an internal shell alias for the test command.
So you can say:
test -f "/bin/bash" && echo "This system has a bash shell"
or
[ -f "/bin/bash" ] && echo "This system has a bash shell"
... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.
select * from employee_list order by salary desc limit 2;
Why don't you disable the view cache with cache-view="false"?
In your view add this to the ion-nav-view like that:
<ion-nav-view name="other" cache-view="false"></ion-nav-view>
Or in your stateProvider:
$stateProvider.state('other', {
cache: false,
url : '/other',
templateUrl : 'templates/other/other.html'
})
Either one will make your controller being called always.
Simple function to accomplish this:
def insert_str(string, str_to_insert, index):
return string[:index] + str_to_insert + string[index:]
I used the answer in this question and I got an issue with it.
It return exception: {"The system cannot find the file specified."}
After a bit of investigation. It turns out that if your WPF application is CORE, you need to change UseShellExecute
to true
.
This is mentioned in Microsoft docs:
true if the shell should be used when starting the process; false if the process should be created directly from the executable file. The default is true on .NET Framework apps and false on .NET Core apps.
So to make this work you need to added UseShellExecute
and set it to true
:
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri){ UseShellExecute = true });
If you need to support MBCS as well as Unicode, Mr.C64's answer is not quite enough. The buffer must be declared TCHAR, and cast to LPTSTR. Note that this code doesn't deal with the annoying newline that Microsoft appends to the error message.
CString FormatErrorMessage(DWORD ErrorCode)
{
TCHAR *pMsgBuf = NULL;
DWORD nMsgLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&pMsgBuf), 0, NULL);
if (!nMsgLen)
return _T("FormatMessage fail");
CString sMsg(pMsgBuf, nMsgLen);
LocalFree(pMsgBuf);
return sMsg;
}
Also, for brevity I find the following method useful:
CString GetLastErrorString()
{
return FormatErrorMessage(GetLastError());
}
Most of the time the solution for this error is really simple:
Use JSON to transfer data types (arrays and objects) between client and server.
In PHP:
In JavaScript:
PHP:
echo json_encode($id_numbers);
JavaScript:
id_numbers = JSON.parse(msg);
As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.
id_numbers = new Array();
$.ajax({
url:"Example.php",
type:"POST",
success:function(msg){
id_numbers = msg;
},
dataType:"json"
});
2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine
exec getlist 47,1,0
create procedure getlist
@convId int,
@SortOrder int,
@contestantsOnly bit = 0
as
A performance comparison:
322ms: show tables like 'table201608';
691ms: select 1 from table201608 limit 1;
319ms: SELECT count(*) FROM information_schema.TABLES WHERE (TABLE_SCHEMA = 'mydb') AND (TABLE_NAME = 'table201608');
Note if you're running this a lot -- like over many HTML requests in a short period -- the 2nd will be way faster since it'll be cached an average 200 ms or faster.
What is the
dict.get()
method?
As already mentioned the get
method contains an additional parameter which indicates the missing value. From the documentation
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a
KeyError
.
An example can be
>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1
Are there speed improvements anywhere?
As mentioned here,
It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.
Earlier get
was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)
def getway(d):
for i in range(100):
s = d.get(i)
def lookup(d):
for i in range(100):
s = d[i]
Now timing these two functions using timeit
>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979
As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis
>>> def lookup(d,val):
... return d[val]
...
>>> def getway(d,val):
... return d.get(val)
...
>>> dis.dis(getway)
2 0 LOAD_FAST 0 (d)
3 LOAD_ATTR 0 (get)
6 LOAD_FAST 1 (val)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>> dis.dis(lookup)
2 0 LOAD_FAST 0 (d)
3 LOAD_FAST 1 (val)
6 BINARY_SUBSCR
7 RETURN_VALUE
Where will it be useful?
It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces
if key in dic:
val = dic[key]
else:
val = def_val
To a single line, val = dic.get(key,def_val)
Where will it be NOT useful?
Whenever you want to return a KeyError
stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!
Is it possible to have
get
like feature indict['key']
?
Yes! We need to implement the __missing__
in a dict subclass.
A sample program can be
class MyDict(dict):
def __missing__(self, key):
return None
A small demonstration can be
>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'
If you are in windows you can go to simbol system and write ipconfig and check what ip is assigned to your machine.
Here is my implementation in java for your requirement. In the treeNode class i used generic array to store the tree data. we can also use arraylist or dynamic array to store the tree value.
public class TreeNode<T> {
private T value = null;
private TreeNode[] childrens = new TreeNode[100];
private int childCount = 0;
TreeNode(T value) {
this.value = value;
}
public TreeNode addChild(T value) {
TreeNode newChild = new TreeNode(value, this);
childrens[childCount++] = newChild;
return newChild;
}
static void traverse(TreeNode obj) {
if (obj != null) {
for (int i = 0; i < obj.childCount; i++) {
System.out.println(obj.childrens[i].value);
traverse(obj.childrens[i]);
}
}
return;
}
void printTree(TreeNode obj) {
System.out.println(obj.value);
traverse(obj);
}
}
And the client class for the above implementation.
public class Client {
public static void main(String[] args) {
TreeNode menu = new TreeNode("Menu");
TreeNode item = menu.addChild("Starter");
item = item.addChild("Veg");
item.addChild("Paneer Tikka");
item.addChild("Malai Paneer Tikka");
item = item.addChild("Non-veg");
item.addChild("Chicken Tikka");
item.addChild("Malai Chicken Tikka");
item = menu.addChild("Main Course");
item = item.addChild("Veg");
item.addChild("Mili Juli Sabzi");
item.addChild("Aloo Shimla Mirch");
item = item.addChild("Non-veg");
item.addChild("Chicken Do Pyaaza");
item.addChild("Chicken Chettinad");
item = menu.addChild("Desserts");
item = item.addChild("Cakes");
item.addChild("Black Forest");
item.addChild("Black Current");
item = item.addChild("Ice Creams");
item.addChild("chocolate");
item.addChild("Vanilla");
menu.printTree(menu);
}
}
OUTPUT
Menu
Starter
Veg
Paneer Tikka
Malai Paneer Tikka
Non-veg
Chicken Tikka
Malai Chicken Tikka
Main Course
Veg
Mili Juli Sabzi
Aloo Shimla Mirch
Non-veg
Chicken Do Pyaaza
Chicken Chettinad
Desserts
Cakes
Black Forest
Black Current
Ice Creams
chocolate
Vanilla
If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
sys.path.insert(1, path_to_dev_pyworkbooks)
This could be important since 3rd party code may rely on sys.path documentation conformance:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
I've had issue with IE7 and returning false before.
Check my answer here to another problem: Javascript not running on IE
To expose just one port, this is what you need to do:
docker run -p <host_port>:<container_port>
To expose multiple ports, simply provide multiple -p
arguments:
docker run -p <host_port1>:<container_port1> -p <host_port2>:<container_port2>
select ID from A where ID not in (select ID from B);
or
select ID from A except select ID from B;
Your second question:
delete from A where ID not in (select ID from B);
DBeaver allows you connect to a DB2 database, run a query, and export the result-set to a CSV file that can be opened and fine-tuned in MS Excel or LibreOffice Calc.
To do this, all you have to do (in DBeaver) is right-click on the results grid (after running the query) and select "Export Resultset" from the context-menu.
This produces the dialog below, where you can ultimately save the result-set to a file as CSV, XML, or HTML:
I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important
property.
HTML
<a href="#" class="selected_btn" data-role="button">Button name</a>
CSS
.selected_btn
{
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red !important;
background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}
Here is the demo
I want to just refresh the div, without refreshing the page ... Is this possible?
Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.
If you just want the graphical fade-in effect, simply remove the .html(data)
call:
$("#panel").hide().fadeIn('fast');
Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/
It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.
html:
<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?
javascript:
$("#changePanel").click(function() {
var data = "foobar";
$("#panel").hide().html(data).fadeIn('fast');
});?
css:
div {
padding: 1em;
background-color: #00c000;
}
input {
padding: .25em 1em;
}?
git rebase -i HEAD^^^
Now mark the ones you want to amend with edit
or e
(replace pick
). Now save and exit.
Now make your changes, then
git add .
git rebase --continue
If you want to add an extra delete remove the options from the commit command. If you want to adjust the message, omit just the --no-edit
option.
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body
or pass it directly within quotes as 'raw text to be sent'
in place of body
.
The signature of the axios post is axios.post(url[, data[, config]])
, so the data
is where you pass your request body.
axios.get
accepts a request config as the second parameter (not query string params).
You can use the params
config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
Beware that the line this.state = initialState;
requires you never to mutate your state, otherwise you'll pollute initialState
and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState
in the constructor. (Or make initialState
a function, as per getInitialState()
.)
Finally, I'd recommend you use setState()
and not replaceState()
.
If you need binary mode, you'll need to do it the hard way:
s = File.open(filename, 'rb') { |f| f.read }
If not, shorter and sweeter is:
s = IO.read(filename)
Swift 4.2 version:
let indexPath:IndexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .none, animated: true)
Enum: These are the available tableView scroll positions - here for reference. You don't need to include this section in your code.
public enum UITableViewScrollPosition : Int {
case None
case Top
case Middle
case Bottom
}
DidSelectRow:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let theCell:UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)
if let theCell = theCell {
var tableViewCenter:CGPoint = tableView.contentOffset
tableViewCenter.y += tableView.frame.size.height/2
tableView.contentOffset = CGPointMake(0, theCell.center.y-65)
tableView.reloadData()
}
}
str.strip()
returns a string with leading+trailing whitespace removed, .lstrip
and .rstrip
for only leading and trailing respectively.
grades.append(lists[i].rstrip('\n').split(','))
First Build your Project and if it was successful, right click on the "model.tt" file and choose run custom tool. It will fix it.
Again Build your project and point to "model.context.tt" run custom tool. it will update DbSet lists.
StackOverflow: How to execute a command and get output of command within C++?
StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...
Also if you know how to make user become the super-user that would be nice also. Thanks!
sudo. su. chmod 04500. (setuid() & seteuid(), but they require you to already be root. E..g. chmod'ed 04***.)
Take care. These can open "interesting" security holes...
Depending on what you are doing, you may not need root. (For instance: I'll often chmod/chown /dev devices (serial ports, etc) (under sudo root) so I can use them from my software without being root. On the other hand, that doesn't work so well when loading/unloading kernel modules...)
I'd like to add a clarification...
A common misunderstanding, in fact one that I had for some time, is that a storyboard segue is triggered by the prepareForSegue:sender:
method. It is not. A storyboard segue will perform, regardless of whether you have implemented a prepareForSegue:sender:
method for that (departing from) view controller.
I learnt this from Paul Hegarty's excellent iTunesU lectures. My apologies but unfortunately cannot remember which lecture.
If you connect a segue between two view controllers in a storyboard, but do not implement a prepareForSegue:sender:
method, the segue will still segue to the target view controller. It will however segue to that view controller unprepared.
Hope this helps.
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
it should end up like this in the $_POST[] array (PHP format for easy visualization)
$_POST[] = array(
'firstname'=>'value',
'lastname'=>'value',
'email'=>'value',
'address'=>'value',
'tree' => array(
'tree1'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree2'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree3'=>array(
'fruit'=>'value',
'height'=>'value'
)
)
)
Assuming your data frame is named d
,
d[order(as.Date(d$V3, format="%d/%m/%Y")),]
Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.
If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:
offset = 5
DF = DF.append([np.nan for x in range(offset)])
DF = DF.shift(periods=offset)
DF = DF.reset_index() #Only works if sequential index
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
There's a caveat with the general 39 character IPv6 structure. For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this:
IPv6 (39 characters) :
ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD
IPv4-mapped IPv6 (45 characters) :
ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190
Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the .
character), so the maximum is DDD.DDD.DDD.DDD
).
The correct maximum IPv6 string length, therefore, is 45.
This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)
You can use the following formula,
=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")
set text-decoration: none; for anchor tag.
Example html.
<body>
<ul class="nav-tabs">
<li><a href="#"><i class="fas fa-th"></i>Business</a></li>
<li><a href="#"><i class="fas fa-th"></i>Expertise</a></li>
<li><a href="#"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
Example CSS:
.nav-tabs li a{
text-decoration: none;
}
The spaces are significant. You created a variable named 'location '
with a value of
' "bob"'
. Note - enclosing single quotes were added to show location of space.
If you want quotes in your value, then your code should look like
set location="bob"
If you don't want quotes, then your code should look like
set location=bob
Or better yet
set "location=bob"
The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like &
|
etc.
I believe question was not whether you can call the static member of the class by calling ClassName::staticMember
. Question was what's the difference between using self::classmember
and $this->classmember
.
For e.g., both of the following examples work without any errors, whether you use self::
or $this->
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
$this->name = $new_name;
$this->address = $new_address;
}
}
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
self::$name = $new_name;
self::$address = $new_address;
}
}
Focusing on one of the accepted answer's jQuery solutions, $.getScript()
is an .ajax()
request in disguise. It allows to execute other function on success by adding a second parameter:
$.getScript(url, function() {console.log('loaded script!')})
Or on the request's handlers themselves, i.e. success (.done()
- script was loaded) or failure (.fail()
):
$.getScript(_x000D_
"https://code.jquery.com/color/jquery.color.js",_x000D_
() => console.log('loaded script!')_x000D_
).done((script,textStatus ) => {_x000D_
console.log( textStatus );_x000D_
$(".block").animate({backgroundColor: "green"}, 1000);_x000D_
}).fail(( jqxhr, settings, exception ) => {_x000D_
console.log(exception + ': ' + jqxhr.status);_x000D_
}_x000D_
);
_x000D_
.block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="block"></div>
_x000D_
public Boolean addArtist(String artistName){
SQLiteDatabase db= getWritableDatabase();
ContentValues data=new ContentValues();
data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);
if(id>0){
return true;
}else{
return false;
}
}
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
You need to use double apostrophe instead of single in the "You''re", eg:
String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);
The better option would be to just use the resource returned array as an array, meaning :
getResources().getStringArray(R.array.your_array)[position]
This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.
The Google Python Style Guide has the following convention:
module_name
,package_name
,ClassName
,method_name
,ExceptionName
,function_name
,GLOBAL_CONSTANT_NAME
,global_var_name
,instance_var_name
,function_parameter_name
,local_var_name
.
A similar naming scheme should be applied to a CLASS_CONSTANT_NAME
In DBTools for Sybase, it's sp_columns your_table_name
.
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
IEnumerable<T> ids = list.Select(x => x).Distinct();
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
StatTransfer is a program that moves data easily between Stata, Excel (or csv), SAS, etc. It is very user friendly (requires no programming skills). See www.stattransfer.com
If you use the program just note that you will have to choose "ASCII/Text - Delimited" to work with .csv files rather than .xls
To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.
public class CommentsController : Controller
{
public ActionResult Index()
{
return View("../Articles/Index", model );
}
}
and
public class ArticlesController : Controller
{
public ActionResult Index()
{
return View();
}
}
Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
Use display instead of visibility. display: none for invisible and no setting for visible.
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this
needing to be enclosed as $(this)
Given $arrService = Get-Service -Name $ServiceName
, $arrService.Status
is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh()
when needed to renew the properties to current values.
MSDN ~ ServiceController.Refresh()
Refreshes property values by resetting the properties to their current values.
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way :
document.activeElement
EDIT: It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported by the latest version of Chrome, Safari and Firefox at least.
The main problem is that:
in a constructor, the injection of the dependencies has not yet occurred*
*obviously excluding Constructor Injection
Real-world example:
public class Foo {
@Inject
Logger LOG;
@PostConstruct
public void fooInit(){
LOG.info("This will be printed; LOG has already been injected");
}
public Foo() {
LOG.info("This will NOT be printed, LOG is still null");
// NullPointerException will be thrown here
}
}
IMPORTANT:
@PostConstruct
and @PreDestroy
have been completely removed in Java 11.
To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
In SQL Server Management Studio query window
I had a similar problem in IE9 where some CORS calls were aborting, while others weren't. My app is also dependent on a promise interface, so the XDomainRequest suggestions above weren't EXACTLY what I needed, so I added a deferred into my service.get workaround for IE9. Hopefully it can be useful to someone else running across this problem. :
get: function (url) {
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var deferred = $.Deferred();
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
json = xdr.responseText;
parsed_json = $.parseJSON(json);
deferred.resolve(parsed_json);
}
xdr.send();
return deferred;
} else {
return $.ajax({
url: url,
type: 'GET',
dataType: 'json',
crossDomain: true
});
}
}
it is not working in the Powershell and should use CMD in my case
Currently the method to add the listener to the map would be
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
And not
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.
If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.
For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.
If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.
//add urlencode to your address $address = urlencode("technopark, Trivandrun, kerala,India"); $region = "IND"; $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region"); echo $json; $decoded = json_decode($json); print_r($decoded);
I found the solution below on this page:
x="test\ me"
eval cd $x
A combination of \
in a double-quoted text constant and an eval
before cd
makes it work like a charm!
Possibly mine isn't a great answer but here goes.
Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.
To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.
So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.
Edit
I blogged about this.
https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819
Use the backslash \
or choose a different delimiter, ie m#.\d#
instead of /.\d/
"In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
C++11/Linux version:
#include <dirent.h>
if (auto dir = opendir("some_dir/")) {
while (auto f = readdir(dir)) {
if (!f->d_name || f->d_name[0] == '.')
continue; // Skip everything that starts with a dot
printf("File: %s\n", f->d_name);
}
closedir(dir);
}
If you have your array in scope you can use sizeof
to determine its size in bytes and use the division to calculate the number of elements:
#define NUM_OF_ELEMS 10
int arr[NUM_OF_ELEMS];
size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);
If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof
. You'll have to store/pass the size information somehow to be able to use it:
void DoSomethingWithArray(int* arr, int NumOfElems)
{
for(int i = 0; i < NumOfElems; ++i) {
arr[i] = /*...*/
}
}
I know this is an old post. However, I observed another instance where in the project already has Tomcat added but we still get this error. Did this to resolve that:
Alt + Enter
Project Facets
On the right, next to details, is another tab "Runtimes".
The installed tomcat server will be listed there. Select it.
Save the configuration and DONE!
Hope this helps someone.
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:
$var = new YourClass();
$var->method();
You can also use the new way to do the same since PHP 5.4:
(new YourClass)->method();
I hope it helps you!
For some - possibly valid - reason the url was encoded twice. %25
is the urlencoded %
sign. So the original url looked like:
http://server.com/my path/
Then it got urlencoded once:
http://server.com/my%20path/
and twice:
http://server.com/my%2520path/
So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space
@bogatron already gave the answer suggested by the matplotlib docs, which produces the right height, but it introduces a different problem. Now the width of the colorbar (as well as the space between colorbar and plot) changes with the width of the plot. In other words, the aspect ratio of the colorbar is not fixed anymore.
To get both the right height and a given aspect ratio, you have to dig a bit deeper into the mysterious axes_grid1
module.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
import numpy as np
aspect = 20
pad_fraction = 0.5
ax = plt.gca()
im = ax.imshow(np.arange(200).reshape((20, 10)))
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
plt.colorbar(im, cax=cax)
Note that this specifies the width of the colorbar w.r.t. the height of the plot (in contrast to the width of the figure, as it was before).
The spacing between colorbar and plot can now be specified as a fraction of the width of the colorbar, which is IMHO a much more meaningful number than a fraction of the figure width.
UPDATE:
I created an IPython notebook on the topic, where I packed the above code into an easily re-usable function:
import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("right", size=width, pad=pad)
plt.sca(current_ax)
return im.axes.figure.colorbar(im, cax=cax, **kwargs)
It can be used like this:
im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)
In ECMAScript 6 it's more or less possible by wrapping the code inside a with
statement with a proxy object. Note it requires non-strict mode and it's bad practice.
function storeVars(target) {_x000D_
return new Proxy(target, {_x000D_
has(target, prop) { return true; },_x000D_
get(target, prop) { return (prop in target ? target : window)[prop]; }_x000D_
});_x000D_
}_x000D_
var vars = {}; // Outer variable, not stored._x000D_
with(storeVars(vars)) {_x000D_
var a = 1; // Stored in vars_x000D_
var b = 2; // Stored in vars_x000D_
(function() {_x000D_
var c = 3; // Inner variable, not stored._x000D_
})();_x000D_
}_x000D_
console.log(vars);
_x000D_
The proxy claims to own all identifiers referenced inside with
, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let
and const
variables are not included.
Inspired by this answer by Bergi.
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
Use the View's post method like this
post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
}
});
Try giving your divs a width of 100%
.
For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.
I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev
(the version I use).
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
0 * * * * cd folder_containing_exe && ./exe_name
should work unless there is something else that needs to be setup for the program to run.
You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.
One very very important difference. Since Observable is just a function, it does not have any state, so for every new Observer, it executes the observable create code again and again. This results in:
The code is run for each observer . If its a HTTP call, it gets called for each observer
This causes major bugs and inefficiencies
BehaviorSubject (or Subject ) stores observer details, runs the code only once and gives the result to all observers .
Ex:
JSBin: http://jsbin.com/qowulet/edit?js,console
// --- Observable ---_x000D_
let randomNumGenerator1 = Rx.Observable.create(observer => {_x000D_
observer.next(Math.random());_x000D_
});_x000D_
_x000D_
let observer1 = randomNumGenerator1_x000D_
.subscribe(num => console.log('observer 1: '+ num));_x000D_
_x000D_
let observer2 = randomNumGenerator1_x000D_
.subscribe(num => console.log('observer 2: '+ num));_x000D_
_x000D_
_x000D_
// ------ BehaviorSubject/ Subject_x000D_
_x000D_
let randomNumGenerator2 = new Rx.BehaviorSubject(0);_x000D_
randomNumGenerator2.next(Math.random());_x000D_
_x000D_
let observer1Subject = randomNumGenerator2_x000D_
.subscribe(num=> console.log('observer subject 1: '+ num));_x000D_
_x000D_
let observer2Subject = randomNumGenerator2_x000D_
.subscribe(num=> console.log('observer subject 2: '+ num));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script>
_x000D_
Output :
"observer 1: 0.7184075243594013"
"observer 2: 0.41271850211336103"
"observer subject 1: 0.8034263165479893"
"observer subject 2: 0.8034263165479893"
Observe how using Observable.create
created different output for each observer, but BehaviorSubject
gave the same output for all observers. This is important.
Other differences summarized.
?????????????????????????????????????????????????????????????????????????????
? Observable ? BehaviorSubject/Subject ?
?????????????????????????????????????????????????????????????????????????????
? Is just a function, no state ? Has state. Stores data in memory ?
?????????????????????????????????????????????????????????????????????????????
? Code run for each observer ? Same code run ?
? ? only once for all observers ?
?????????????????????????????????????????????????????????????????????????????
? Creates only Observable ?Can create and also listen Observable?
? ( data producer alone ) ? ( data producer and consumer ) ?
?????????????????????????????????????????????????????????????????????????????
? Usage: Simple Observable with only ? Usage: ?
? one Obeserver. ? * Store data and modify frequently ?
? ? * Multiple observers listen to data ?
? ? * Proxy between Observable and ?
? ? Observer ?
?????????????????????????????????????????????????????????????????????????????
int a = srand(time(NULL))
arr[i] = a;
Should be
arr[i] = rand();
And put srand(time(NULL))
somewhere at the very beginning of your program.
It should be:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName
: the name of the table in the database.TableEntityInstance
: an instance of the table entity class.If your table is Orders
, then:
Order order = new Order();
context.Orders.AddObject(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is a live example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.AddObject(screenshot);
this.ObjectContext.SaveChanges();
}
}
Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:
create index arrival_year on reservations ( extract(year from arrival) );
That will open PostgreSQL with the possibility to use an index for
select *
FROM reservations
WHERE extract(year from arrival) = 2012;
Note that the expression in the index must be exactly the same expression as used in the where
clause to make this work.
Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.
Therefore, you can not use this variation
> sitemap: /sitemap.xml
Recommended syntax is
Sitemap: https://www.yourdomain.com/sitemap.xml
Note:
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
I had the same problem and I solved it by using an absolute import instead of a relative one.
for example in your case, you will write something like this:
from app.mymodule import myclass
You can see in the documentation.
Note that relative imports are based on the name of the current module. Since the name of the main module is always "
__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
Like Obediah Stane said, it's necessary to create your own format
method. But I would change a few things:
Create a subclass directly derived from Formatter
, not from SimpleFormatter
. The SimpleFormatter
has nothing to add anymore.
Be careful with creating a new Date
object! You should make sure to represent the date of the LogRecord
. When creating a new Date
with the default constructor, it will represent the date and time the Formatter
processes the LogRecord
, not the date that the LogRecord
was created.
The following class can be used as formatter in a Handler
, which in turn can be added to the Logger
. Note that it ignores all class and method information available in the LogRecord
.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public final class LogFormatter extends Formatter {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(new Date(record.getMillis()))
.append(" ")
.append(record.getLevel().getLocalizedName())
.append(": ")
.append(formatMessage(record))
.append(LINE_SEPARATOR);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
// ignore
}
}
return sb.toString();
}
}
For easy tasks I often simply do it like:
var undef;
// Fails on undefined variables
if (query !== undef) {
// variable is defined
} else {
// else do this
}
Or if you simply want to check for a nulled value too..
var undef;
// Fails on undefined variables
// And even fails on null values
if (query != undef) {
// variable is defined and not null
} else {
// else do this
}
Use the time.Now()
function and the time.Format()
method.
t := time.Now()
fmt.Println(t.Format("20060102150405"))
prints out 20110504111515
, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.
You can use time.Now().UTC()
if you'd rather have UTC than your local time zone.
In my case it was because it was being backed up my a background process which started before I opened Access. It isn't normally a problem if it have the database open when the backup starts.
f'{float(f"{i:.1g}"):g}'
# Or with Python <3.6,
'{:g}'.format(float('{:.1g}'.format(i)))
This solution is different from all of the others because:
For an arbitrary number n
of significant figures, you can use:
print('{:g}'.format(float('{:.{p}g}'.format(i, p=n))))
Test:
a = [1234, 0.12, 0.012, 0.062, 6253, 1999, -3.14, 0., -48.01, 0.75]
b = ['{:g}'.format(float('{:.1g}'.format(i))) for i in a]
# b == ['1000', '0.1', '0.01', '0.06', '6000', '2000', '-3', '0', '-50', '0.8']
Note: with this solution, it is not possible to adapt the number of significant figures dynamically from the input because there is no standard way to distinguish numbers with different numbers of trailing zeros (3.14 == 3.1400
). If you need to do so, then non-standard functions like the ones provided in the to-precision package are needed.
Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100
. But OpenCV uses H: 0-179, S: 0-255, V: 0-255
. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255)
.
Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:
cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)
Now run it. I got an output as follows:
Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.
EDIT:
As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2
module, so users can compare the easiness and flexibility of new cv2
module.
import cv2
import numpy as np
img = cv2.imread('sof.jpg')
ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)
It gives the same result as above. But code is much more simpler.
I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).
The code:
#!/usr/bin/env python
class Celsius:
def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0
class Temperature:
def __init__(self, initial_f): self.fahrenheit = initial_f
celsius = Celsius()
if __name__ == "__main__":
t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)
The result:
C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212
With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.
This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project
If you want add Custom method you can do it
(in this case, at least one checkbox selected)
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" onclick="test($(this))"/>
in Javascript
var tags = 0;
$(document).ready(function() {
$.validator.addMethod('arrayminimo', function(value) {
return tags > 0
}, 'Selezionare almeno un Opzione');
$.validator.addClassRules('check_secondario', {
arrayminimo: true,
});
validaFormRichiesta();
});
function validaFormRichiesta() {
$("#form").validate({
......
});
}
function test(n) {
if (n.prop("checked")) {
tags++;
} else {
tags--;
}
}
FUNCTION GETUNIQUEID_2 RETURN VARCHAR2
AS
v_curr_id NUMBER;
v_inc NUMBER;
v_next_val NUMBER;
pragma autonomous_transaction;
begin
CREATE SEQUENCE sequnce
START WITH YYMMDD0000000001
INCREMENT BY 1
NOCACHE
select sequence.nextval into v_curr_id from dual;
if(substr(v_curr_id,0,6)= to_char(sysdate,'yymmdd')) then
v_next_val := to_number(to_char(SYSDATE+1, 'yymmdd') || '0000000000');
v_inc := v_next_val - v_curr_id;
execute immediate ' alter sequence sequence increment by ' || v_inc ;
select sequence.nextval into v_curr_id from dual;
execute immediate ' alter sequence sequence increment by 1';
else
dbms_output.put_line('exception : file not found');
end if;
RETURN 'ID'||v_curr_id;
END;
scut, a cut-like utility (smarter but slower I made) that can use any perl regex as a breaking token. Breaking on whitespace is the default, but you can also break on multi-char regexes, alternative regexes, etc.
scut -f='6 2 8 7' < input.file > output.file
so the above command would break columns on whitespace and extract the (0-based) cols 6 2 8 7 in that order.
PSR-5: PHPDoc proposes a form of Generics-style notation.
Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>
Values in a Collection MAY even be another array and even another Collection.
Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>
<?php
$x = [new Name()];
/* @var $x Name[] */
$y = new Collection([new Name()]);
/* @var $y Collection<Name> */
$a = new Collection();
$a[] = new Model_User();
$a->resetChanges();
$a[0]->name = "George";
$a->echoChanges();
/* @var $a Collection<Model_User> */
Note: If you are expecting an IDE to do code assist then it's another question about if the IDE supports PHPDoc Generic-style collections notation.
From my answer to this question.
You want to use css float for this, you can put it directly in your code.
<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>
But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).
HTML:
<body>
<img src="website_art.png" class="myImage"/>
<h3 class="heading">The Art of Gaming</h3>
</body>
CSS:
.myImage {
float: left;
height: 75px;
width: 235px;
font-family: Veranda;
}
.heading {
float:right;
}
If you're using tcsh
(which is my default shell on Mac OS X), you probably just need to type rehash
into the shell just after the install completes:
npm install -g gulp
followed immediately by:
rehash
Otherwise, if this is your very first time installing gulp
, your shell may not recognize that there's a new executable installed -- so you either need to start a new shell, or type rehash
in the current shell.
(This is basically a one-time thing for each command you install globally.)
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
The way to go with javascript:
var data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({
type: 'POST',
url: '/your/url',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
})
If you call data.append('file', file) multiple times your request will contain an array of your files.
"The
append()
method of theFormData
interface appends a new value onto an existing key inside aFormData
object, or adds the key if it does not already exist. The difference betweenFormData.se
t andappend()
is that if the specified key already exists,FormData.set
will overwrite all existing values with the new one, whereasappend()
will append the new value onto the end of the existing set of values."
Myself using node.js and multipart handler middleware multer get the data as follows:
router.post('/trip/save', upload.array('file', 10), function(req, res){
// Your array of files is in req.files
}
First of all print
isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing ,
(comma). Now a space will be used instead of a newline.
Demo:
print 1,
print 2
output:
1 2
Or use Python 3's print()
function:
from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)
As you can clearly see print()
function is much more powerful as we can specify any string to be used as end
rather a fixed space.
Here is a simple clean implementation which is consistent with Pattern#split
and works with variable length patterns, which look behind cannot support, and it is easier to use. It is similar to the solution provided by @cletus.
public static String[] split(CharSequence input, String pattern) {
return split(input, Pattern.compile(pattern));
}
public static String[] split(CharSequence input, Pattern pattern) {
Matcher matcher = pattern.matcher(input);
int start = 0;
List<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(input.subSequence(start, matcher.start()).toString());
result.add(matcher.group());
start = matcher.end();
}
if (start != input.length()) result.add(input.subSequence(start, input.length()).toString());
return result.toArray(new String[0]);
}
I don't do null checks here, Pattern#split
doesn't, why should I. I don't like the if
at the end but it is required for consistency with the Pattern#split
. Otherwise I would unconditionally append, resulting in an empty string as the last element of the result if the input string ends with the pattern.
I convert to String[] for consistency with Pattern#split
, I use new String[0]
rather than new String[result.size()]
, see here for why.
Here are my tests:
@Test
public void splitsVariableLengthPattern() {
String[] result = Split.split("/foo/$bar/bas", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar", "/bas" }, result);
}
@Test
public void splitsEndingWithPattern() {
String[] result = Split.split("/foo/$bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar" }, result);
}
@Test
public void splitsStartingWithPattern() {
String[] result = Split.split("$foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "", "$foo", "/bar" }, result);
}
@Test
public void splitsNoMatchesPattern() {
String[] result = Split.split("/foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/bar" }, result);
}
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
In similar case I used: white-space: nowrap;
I'd like to point out. maybe this just happens to me, HOWEVER, when I use this.removeAllFiles() in dropzone, it fires the event COMPLETE and this blows, what I did was check if the fileData was empty or not so I could actually submit the form.
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
OpenSSL provides a passwd command that can encrypt but doesn't decrypt as it only does hashes. You could also download something like aesutil so you can use a capable and well-known symmetric encryption routine.
For example:
#!/bin/sh
# using aesutil
SALT=$(mkrand 15) # mkrand generates a 15-character random passwd
MYENCPASS="i/b9pkcpQAPy7BzH2JlqHVoJc2mNTBM=" # echo "passwd" | aes -e -b -B -p $SALT
MYPASS=$(echo "$MYENCPASS" | aes -d -b -p $SALT)
# and usage
serverControl.sh -u admin -p $MYPASS -c shutdown
I spent a long time looking for solutions, and found this answer.
It looks like, in order to get what you (and I) want, you need the combination of plt.ion()
, plt.show()
(not with block=False
) and, most importantly, plt.pause(.001)
(or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.
Here's an implementation that works for me on python 3.5:
import numpy as np
from matplotlib import pyplot as plt
def main():
plt.axis([-50,50,0,10000])
plt.ion()
plt.show()
x = np.arange(-50, 51)
for pow in range(1,5): # plot x^1, x^2, ..., x^4
y = [Xi**pow for Xi in x]
plt.plot(x, y)
plt.draw()
plt.pause(0.001)
input("Press [enter] to continue.")
if __name__ == '__main__':
main()
If you want to get an index about the similarity of the two pictures, I suggest you from the metrics the SSIM index. It is more consistent with the human eye. Here is an article about it: Structural Similarity Index
It is implemented in OpenCV too, and it can be accelerated with GPU: OpenCV SSIM with GPU
Try this CSS
input[type=checkbox] {width:100px; height:100px;}
A simple regular expression would work
$string = preg_replace("/,$/", "", $string)
Mr Hash had the best answer so far, but the solution below makes it ideal (for me) by adding the following benefits:
In the router:
.when '/proposals',
title: 'Proposals',
templateUrl: 'proposals/index.html'
controller: 'ProposalListCtrl'
resolve:
pageTitle: [ '$rootScope', '$route', ($rootScope, $route) ->
$rootScope.page.setTitle($route.current.params.filter + ' ' + $route.current.title)
]
In the run block:
.run(['$rootScope', ($rootScope) ->
$rootScope.page =
prefix: ''
body: ' | ' + 'Online Group Consensus Tool'
brand: ' | ' + 'Spokenvote'
setTitle: (prefix, body) ->
@prefix = if prefix then ' ' + prefix.charAt(0).toUpperCase() + prefix.substring(1) else @prifix
@body = if body then ' | ' + body.charAt(0).toUpperCase() + body.substring(1) else @body
@title = @prefix + @body + @brand
])
I think that the usage of @Html.LabelForModel()
should be explained in more detail.
The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.
You could refer to the following code:
Code in model:
using System.ComponentModel;
[DisplayName("MyModel")]
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
Code in view:
@Html.LabelForModel()
<div class="form-group">
@Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Test)
@Html.ValidationMessageFor(model => model.Test)
</div>
</div>
The output screenshot:
If you're not afraid of old java-style (non type safe generic) semantics, this also works and is simple'ish:
ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(subject.method(argument.capture()); // run your code
List<SomeType> list = argument.getValue(); // first captured List, etc.
You will have to read in all the data from the Stream object into a byte[]
buffer and then pass that into the MemoryStream
via its constructor. It may be better to be more specific about the type of stream object you are using. Stream
is very generic and may not implement the Length
attribute, which is rather useful when reading in data.
Here's some code for you:
public MyClass(Stream inputStream) {
byte[] inputBuffer = new byte[inputStream.Length];
inputStream.Read(inputBuffer, 0, inputBuffer.Length);
_ms = new MemoryStream(inputBuffer);
}
If the Stream
object doesn't implement the Length
attribute, you will have to implement something like this:
public MyClass(Stream inputStream) {
MemoryStream outputStream = new MemoryStream();
byte[] inputBuffer = new byte[65535];
int readAmount;
while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
outputStream.Write(inputBuffer, 0, readAmount);
_ms = outputStream;
}
SQL self-join simply is a normal join which is used to join a table to itself.
Example:
Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID
send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.
public class DialogSettingsCancel
{
WindowSettings parent;
public DialogSettingsCancel(WindowSettings settings)
{
this.parent = settings;
}
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
this.parent.Close();
this.Close();
}
}
In laravel 5.3 don't have AuthController.
to disable register route you should change in constructor of RegisterController
like this:
You can change form:
public function __construct()
{
$this->middleware('guest');
}
to:
use Illuminate\Support\Facades\Redirect;
public function __construct()
{
Redirect::to('/')->send();
}
Note: for use Redirect
don't forget to user Redirect;
So user access to https://host_name/register it's redirect to "/".
When we use php artisan make:auth
it's added Auth::route();
automatically.
Please Override Route in /routes/web.php.
You can change it's like this:
* you need to comment this line: Auth::routes();
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
// Auth::routes();
Route::get('/login', 'Auth\LoginController@showLoginForm' );
Route::post('/login', 'Auth\LoginController@login');
Route::post('/logout', 'Auth\LoginController@logout');
Route::get('/home', 'HomeController@index');
Thanks! I hope it's can solve your problems.
use :
socket.Disconnect() //ok
do not use :
socket.disconnect()
2019 Update (just for reference):
Starting with .NET Core 3.0, this feature is supported out of the box. To take advantage of the single-file executable publishing, just add the following line to the project configuration file:
<PropertyGroup>
<PublishSingleFile>true</PublishSingleFile>
</PropertyGroup>
Now, dotnet publish
should produce a single .exe file without using any external tool.
More documentation for this feature is available at https://github.com/dotnet/designs/blob/master/accepted/single-file/design.md.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
To read a whole line from a file into a string, use std::getline
like so:
std::ifstream file("my_file");
std::string temp;
std::getline(file, temp);
You can do this in a loop to until the end of the file like so:
std::ifstream file("my_file");
std::string temp;
while(std::getline(file, temp)) {
//Do with temp
}
http://en.cppreference.com/w/cpp/string/basic_string/getline
In order to get screen resolution you can also use jquery. This link help you very much to resolve.
The following sequence of commands does remove every name from the current module:
>>> import sys
>>> sys.modules[__name__].__dict__.clear()
I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).
Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:
>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
... if n[0]!='_': delattr(this, n)
...
>>>
This sequence leaves alone names that are private or magical, including the __builtins__
special name which houses all built-in names. So, built-ins still work -- for example:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>>
As you see, name n
(the control variable in that for
) also happens to stick around (as it's re-bound in the for
clause every time through), so it might be better to name that control variable _
, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _
is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).
Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).
IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.
You don't want to use terminal: false
since that's what's blocking the processing of inside the button. Instead, in your link
clear the attr.ngClick
to prevent the default behavior.
http://plnkr.co/edit/EySy8wpeQ02UHGPBAIvg?p=preview
app.directive('ngConfirmClick', [
function() {
return {
priority: 1,
link: function(scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.ngClick;
attr.ngClick = "";
element.bind('click', function(event) {
if (window.confirm(msg)) {
scope.$eval(clickAction)
}
});
}
};
}
]);
Note that the IEnumerable<T>
allready implemented by the System.Collections
so another approach is to derive your MyObjects
class from System.Collections
as a base class (documentation):
System.Collections: Provides the base class for a generic collection.
We can later make our own implemenation to override the virtual System.Collections
methods to provide custom behavior (only for ClearItems
, InsertItem
, RemoveItem
, and SetItem
along with Equals
, GetHashCode
, and ToString
from Object
). Unlike the List<T>
which is not designed to be easily extensible.
Example:
public class FooCollection : System.Collections<Foo>
{
//...
protected override void InsertItem(int index, Foo newItem)
{
base.InsertItem(index, newItem);
Console.Write("An item was successfully inserted to MyCollection!");
}
}
public static void Main()
{
FooCollection fooCollection = new FooCollection();
fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}
Please note that driving from collection
recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.
You can do something like this to count from a list of things.
IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
int count = methodNames.Where(x => names.Contains(x)).Count();
To count a single element
string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
int count = words.Where(x => x.Equals(occur)).Count();
just use mCheckedPosition
save status
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(v -> {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
notifyDataSetChanged();
}
});
}
the probleme of these array of function are not in the "array form" but in the way these functions are called... then... try this.. with a simple eval()...
array_of_function = ["fx1()","fx2()","fx3()",.."fxN()"]
var zzz=[];
for (var i=0; i<array_of_function.length; i++)
{ var zzz += eval( array_of_function[i] ); }
it work's here, where nothing upper was doing the job at home... hopes it will help
Run cat -v file.sh
.
You most likely have a carriage return or no-break space in your file. cat -v
will show them as ^M
and M-BM-
or M-
respectively. It will similarly show any other strange characters you might have gotten into your file.
Remove the Windows line breaks with
tr -d '\r' < file.sh > fixedfile.sh
You can use "break" to break the loop, which will not allow the loop to process more conditions
In case you cannot change the declaration for whatever reason, you can do:
char ch = 212;
printf("%d", (unsigned char) ch);
from MSDN for StringReader
string textReaderText = "TextReader is the abstract base " +
"class of StreamReader and StringReader, which read " +
"characters from streams and strings, respectively.\n\n" +
"Create an instance of TextReader to open a text file " +
"for reading a specified range of characters, or to " +
"create a reader based on an existing stream.\n\n" +
"You can also use an instance of TextReader to read " +
"text from a custom backing store using the same " +
"APIs you would use for a string or a stream.\n\n";
Console.WriteLine("Original text:\n\n{0}", textReaderText);
// From textReaderText, create a continuous paragraph
// with two spaces between each sentence.
string aLine, aParagraph = null;
StringReader strReader = new StringReader(textReaderText);
while(true)
{
aLine = strReader.ReadLine();
if(aLine != null)
{
aParagraph = aParagraph + aLine + " ";
}
else
{
aParagraph = aParagraph + "\n";
break;
}
}
Console.WriteLine("Modified text:\n\n{0}", aParagraph);
For other users getting this problem.
You may get this error if you are running a newer ElasticSearch (5.5 or later) while running Spring Boot <2 version.
Recommendation is to use the REST Client since the Java Client will be deprecated.
Other workaround would be to upgrade to Spring Boot 2, since that should be compatible.
See https://discuss.elastic.co/t/spring-data-elasticsearch-cant-connect-with-elasticsearch-5-5-0/94235 for more information.
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files
. Then you can use the geo location, provided you didn't turn it off in your settings.
Using Java 8 stream API:
String[] keys = new String[0];
// A map for keys and their count
Map<String, Long> keyCountMap = Arrays.stream(keys).
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();
By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language
).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.
This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.
For the complete API, however, I always use the Javadoc. I reference it constantly.
((ISomeInterface)Activator.CreateInstance(Assembly.LoadFile("somePath").GetTypes()[0])).SomeInterfaceMethod();
use library sh: the module du
does it:
pip install sh
import sh
print( sh.du("-s", ".") )
91154728 .
if you want to pass asterix, use glob
as described here.
to convert the values in human readables, use humanize:
pip install humanize
import humanize
print( humanize.naturalsize( 91157384 ) )
91.2 MB
You need to use CreateProcess [ http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx ]
For ex:
LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\Program Files\MyApp\" -L -S")); CreateProcess(NULL, szCmdline, /.../);
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
EDIT: The info and script below only applies to iMagick class - which is not added by default with ImageMagick!!!
If I want to know if imagemagick is installed and actually working as a php extension, I paste this snippet into a web accessible file
<?php
error_reporting(E_ALL);
ini_set( 'display_errors','1');
/* Create a new imagick object */
$im = new Imagick();
/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");
/* Create imagickdraw object */
$draw = new ImagickDraw();
/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);
/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);
/* Close the pattern */
$draw->popPattern();
/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');
/* Set font size to 52 */
$draw->setFontSize(52);
/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");
/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");
/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);
/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);
/* Set the format to PNG */
$canvas->setImageFormat('png');
/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>
You should see a hello world graphic: