As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
I would use submodules (as Pat Notz) or two distinct repositories. If you modify your binary files too often, then I would try to minimize the impact of the huge repository cleaning the history:
I had a very similar problem several months ago: ~21 GB of MP3 files, unclassified (bad names, bad id3's, don't know if I like that MP3 file or not...), and replicated on three computers.
I used an external hard disk drive with the main Git repository, and I cloned it into each computer. Then, I started to classify them in the habitual way (pushing, pulling, merging... deleting and renaming many times).
At the end, I had only ~6 GB of MP3 files and ~83 GB in the .git directory. I used git-write-tree
and git-commit-tree
to create a new commit, without commit ancestors, and started a new branch pointing to that commit. The "git log" for that branch only showed one commit.
Then, I deleted the old branch, kept only the new branch, deleted the ref-logs, and run "git prune": after that, my .git folders weighted only ~6 GB...
You could "purge" the huge repository from time to time in the same way: Your "git clone"'s will be faster.
If they are small files that will not need to be edited then option B is not a bad option. I prefer this to writing logic to store files and deal with crazy directory structure issues. Having a lot of files in one directory is bad. emkay?
If the files are large or require constant editing, especially from programs like office, then option A is your best bet.
For most cases, it's a matter of preference, but if you go option A, just make re the directories don't have too many files in them. If you choose option B, then make the table with the BLOBed data be in it's own database and/or file group. This will help with maintenance, especially backups/restores. Your regular data is probably fairly small, while your image data will be huge over time.
I found this interesting link how to solve your problem in PHP. I think you forgot to replace space
by +
as shown in the link.
I took this circle from http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png as sample which looks like:
Next I put it through http://www.greywyvern.com/code/php/binary2base64 which returned me:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAAAAACPAi4CAAAAB3RJTUUH1QEHDxEhOnxCRgAAAAlwSFlzAAAK8AAACvABQqw0mAAAAXBJREFUeNrtV0FywzAIxJ3+K/pZyctKXqamji0htEik9qEHc3JkWC2LRPCS6Zh9HIy/AP4FwKf75iHEr6eU6Mt1WzIOFjFL7IFkYBx3zWBVkkeXAUCXwl1tvz2qdBLfJrzK7ixNUmVdTIAB8PMtxHgAsFNNkoExRKA+HocriOQAiC+1kShhACwSRGAEwPP96zYIoE8Pmph9qEWWKcCWRAfA/mkfJ0F6dSoA8KW3CRhn3ZHcW2is9VOsAgoqHblncAsyaCgcbqpUZQnWoGTcp/AnuwCoOUjhIvCvN59UBeoPZ/AYyLm3cWVAjxhpqREVaP0974iVwH51d4AVNaSC8TRNNYDQEFdlzDW9ob10YlvGQm0mQ+elSpcCCBtDgQD7cDFojdx7NIeHJkqi96cOGNkfZOroZsHtlPYoR7TOp3Vmfa5+49uoSSRyjfvc0A1kLx4KC6sNSeDieD1AWhrJLe0y+uy7b9GjP83l+m68AJ72AwSRPN5g7uwUAAAAAElFTkSuQmCC
saved this string to base64
which I read from in my code.
var fs = require('fs'),
data = fs.readFileSync('base64', 'utf8'),
base64Data,
binaryData;
base64Data = data.replace(/^data:image\/png;base64,/, "");
base64Data += base64Data.replace('+', ' ');
binaryData = new Buffer(base64Data, 'base64').toString('binary');
fs.writeFile("out.png", binaryData, "binary", function (err) {
console.log(err); // writes out file without error, but it's not a valid image
});
I get a circle back, but the funny thing is that the filesize has changed :)...
When you read back image I think you need to setup headers
Take for example imagepng from PHP page:
<?php
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
I think the second line header('Content-Type: image/png');
, is important else your image will not be displayed in browser, but just a bunch of binary data is shown to browser.
In Express you would simply just use something like below. I am going to display your gravatar which is located at http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
and is a jpeg file when you curl --head http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
. I only request headers because else curl will display a bunch of binary stuff(Google Chrome immediately goes to download) to console:
curl --head "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 03 Aug 2011 12:11:25 GMT
Content-Type: image/jpeg
Connection: keep-alive
Last-Modified: Mon, 04 Oct 2010 11:54:22 GMT
Content-Disposition: inline; filename="cabf735ce7b8b4471ef46ea54f71832d.jpeg"
Access-Control-Allow-Origin: *
Content-Length: 1258
X-Varnish: 2356636561 2352219240
Via: 1.1 varnish
Expires: Wed, 03 Aug 2011 12:16:25 GMT
Cache-Control: max-age=300
Source-Age: 1482
$ mkdir -p ~/tmp/6922728
$ cd ~/tmp/6922728/
$ touch app.js
app.js
var app = require('express').createServer();
app.get('/', function (req, res) {
res.contentType('image/jpeg');
res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});
app.get('/binary', function (req, res) {
res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});
app.listen(3000);
$ wget "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
$ node app.js
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
If you want to compare files visually you can use:
git difftool
It will start your diff app automatically for each changed file.
PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):
git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false
well i actually have a very similar problem, but with a twist... say the top level site is a.foo.com - now i set document domain to a.foo.com
then in the iframe that i create / own,i also set it too a.foo.com
note that i cant set them too foo.com b/c there is another iframe in the page pointed to b.a.foo.com (which again uses a.foo.com but i cant change the script code there)
youll note that im essentially setting document.domain to what it already would be anyway...but i have to do that to access the other iframe i mentioned from b.a.foo.com
inside my frame, after i set the domain, eventhough all iframes have the same setting, i still get an error when reaching up into the parent in IE 6/7
there are other things that r really bizaree
in the outside / top level, if i wait for its onload event, and set a timer, eventually i can reach down into the frame i need to access....but i can never reach from bottom up... and i really need to be able to
also if i set everything to be foo.com (which as i said i cannot do) IT WORKS! but for some reason, when using the same value as location.host....it doesnt and its freaking killing me.....
Another way to rename the database or taking an image of the database is by using the reverse engineering option in the database tab. It will create an ER diagram for the database. Rename the schema there.
After that, go to the File menu and go to export and forward engineer the database.
Then you can import the database.
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire
accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon
instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d')
(or whatever format is required) and diffForHumans()
should work on your home page as well.
Hope this helps!
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:
dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]
It might be the root permission. I tried exit root login, use
sudo su -l root
pip <command>
that works for me
I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output --> Rogue One
From http://docs.python.org/tutorial/datastructures.html:
"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."
This seems like the appropriate place to share my utility class for loading and processing images with the community, you are welcome to use it and modify it freely.
package com.emil;
import java.io.IOException;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* A class to load and process images of various sizes from input streams and file paths.
*
* @author Emil http://stackoverflow.com/users/220710/emil
*
*/
public class ImageProcessing {
public static Bitmap getBitmap(InputStream stream, int sampleSize, Bitmap.Config bitmapConfig) throws IOException{
BitmapFactory.Options options=ImageProcessing.getOptionsForSampling(sampleSize, bitmapConfig);
Bitmap bm = BitmapFactory.decodeStream(stream,null,options);
if(ImageProcessing.checkDecode(options)){
return bm;
}else{
throw new IOException("Image decoding failed, using stream.");
}
}
public static Bitmap getBitmap(String imgPath, int sampleSize, Bitmap.Config bitmapConfig) throws IOException{
BitmapFactory.Options options=ImageProcessing.getOptionsForSampling(sampleSize, bitmapConfig);
Bitmap bm = BitmapFactory.decodeFile(imgPath,options);
if(ImageProcessing.checkDecode(options)){
return bm;
}else{
throw new IOException("Image decoding failed, using file path.");
}
}
public static Dimensions getDimensions(InputStream stream) throws IOException{
BitmapFactory.Options options=ImageProcessing.getOptionsForDimensions();
BitmapFactory.decodeStream(stream,null,options);
if(ImageProcessing.checkDecode(options)){
return new ImageProcessing.Dimensions(options.outWidth,options.outHeight);
}else{
throw new IOException("Image decoding failed, using stream.");
}
}
public static Dimensions getDimensions(String imgPath) throws IOException{
BitmapFactory.Options options=ImageProcessing.getOptionsForDimensions();
BitmapFactory.decodeFile(imgPath,options);
if(ImageProcessing.checkDecode(options)){
return new ImageProcessing.Dimensions(options.outWidth,options.outHeight);
}else{
throw new IOException("Image decoding failed, using file path.");
}
}
private static boolean checkDecode(BitmapFactory.Options options){
// Did decode work?
if( options.outWidth<0 || options.outHeight<0 ){
return false;
}else{
return true;
}
}
/**
* Creates a Bitmap that is of the minimum dimensions necessary
* @param bm
* @param min
* @return
*/
public static Bitmap createMinimalBitmap(Bitmap bm, ImageProcessing.Minimize min){
int newWidth, newHeight;
switch(min.type){
case WIDTH:
if(bm.getWidth()>min.minWidth){
newWidth=min.minWidth;
newHeight=ImageProcessing.getScaledHeight(newWidth, bm);
}else{
// No resize
newWidth=bm.getWidth();
newHeight=bm.getHeight();
}
break;
case HEIGHT:
if(bm.getHeight()>min.minHeight){
newHeight=min.minHeight;
newWidth=ImageProcessing.getScaledWidth(newHeight, bm);
}else{
// No resize
newWidth=bm.getWidth();
newHeight=bm.getHeight();
}
break;
case BOTH: // minimize to the maximum dimension
case MAX:
if(bm.getHeight()>bm.getWidth()){
// Height needs to minimized
min.minDim=min.minDim!=null ? min.minDim : min.minHeight;
if(bm.getHeight()>min.minDim){
newHeight=min.minDim;
newWidth=ImageProcessing.getScaledWidth(newHeight, bm);
}else{
// No resize
newWidth=bm.getWidth();
newHeight=bm.getHeight();
}
}else{
// Width needs to be minimized
min.minDim=min.minDim!=null ? min.minDim : min.minWidth;
if(bm.getWidth()>min.minDim){
newWidth=min.minDim;
newHeight=ImageProcessing.getScaledHeight(newWidth, bm);
}else{
// No resize
newWidth=bm.getWidth();
newHeight=bm.getHeight();
}
}
break;
default:
// No resize
newWidth=bm.getWidth();
newHeight=bm.getHeight();
}
return Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
}
public static int getScaledWidth(int height, Bitmap bm){
return (int)(((double)bm.getWidth()/bm.getHeight())*height);
}
public static int getScaledHeight(int width, Bitmap bm){
return (int)(((double)bm.getHeight()/bm.getWidth())*width);
}
/**
* Get the proper sample size to meet minimization restraints
* @param dim
* @param min
* @param multipleOf2 for fastest processing it is recommended that the sample size be a multiple of 2
* @return
*/
public static int getSampleSize(ImageProcessing.Dimensions dim, ImageProcessing.Minimize min, boolean multipleOf2){
switch(min.type){
case WIDTH:
return ImageProcessing.getMaxSampleSize(dim.width, min.minWidth, multipleOf2);
case HEIGHT:
return ImageProcessing.getMaxSampleSize(dim.height, min.minHeight, multipleOf2);
case BOTH:
int widthMaxSampleSize=ImageProcessing.getMaxSampleSize(dim.width, min.minWidth, multipleOf2);
int heightMaxSampleSize=ImageProcessing.getMaxSampleSize(dim.height, min.minHeight, multipleOf2);
// Return the smaller of the two
if(widthMaxSampleSize<heightMaxSampleSize){
return widthMaxSampleSize;
}else{
return heightMaxSampleSize;
}
case MAX:
// Find the larger dimension and go bases on that
if(dim.width>dim.height){
return ImageProcessing.getMaxSampleSize(dim.width, min.minDim, multipleOf2);
}else{
return ImageProcessing.getMaxSampleSize(dim.height, min.minDim, multipleOf2);
}
}
return 1;
}
public static int getMaxSampleSize(int dim, int min, boolean multipleOf2){
int add=multipleOf2 ? 2 : 1;
int size=0;
while(min<(dim/(size+add))){
size+=add;
}
size = size==0 ? 1 : size;
return size;
}
public static class Dimensions {
int width;
int height;
public Dimensions(int width, int height) {
super();
this.width = width;
this.height = height;
}
@Override
public String toString() {
return width+" x "+height;
}
}
public static class Minimize {
public enum Type {
WIDTH,HEIGHT,BOTH,MAX
}
Integer minWidth;
Integer minHeight;
Integer minDim;
Type type;
public Minimize(int min, Type type) {
super();
this.type = type;
switch(type){
case WIDTH:
this.minWidth=min;
break;
case HEIGHT:
this.minHeight=min;
break;
case BOTH:
this.minWidth=min;
this.minHeight=min;
break;
case MAX:
this.minDim=min;
break;
}
}
public Minimize(int minWidth, int minHeight) {
super();
this.type=Type.BOTH;
this.minWidth = minWidth;
this.minHeight = minHeight;
}
}
/**
* Estimates size of Bitmap in bytes depending on dimensions and Bitmap.Config
* @param width
* @param height
* @param config
* @return
*/
public static long estimateBitmapBytes(int width, int height, Bitmap.Config config){
long pixels=width*height;
switch(config){
case ALPHA_8: // 1 byte per pixel
return pixels;
case ARGB_4444: // 2 bytes per pixel, but depreciated
return pixels*2;
case ARGB_8888: // 4 bytes per pixel
return pixels*4;
case RGB_565: // 2 bytes per pixel
return pixels*2;
default:
return pixels;
}
}
private static BitmapFactory.Options getOptionsForDimensions(){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
return options;
}
private static BitmapFactory.Options getOptionsForSampling(int sampleSize, Bitmap.Config bitmapConfig){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inDither = false;
options.inSampleSize = sampleSize;
options.inScaled = false;
options.inPreferredConfig = bitmapConfig;
return options;
}
}
you can use
reader.GetInt32(3);
to read an 32 bit int from the data reader.
If you know the type of your data I think its better to read using the Get*
methods which are strongly typed rather than just reading an object and casting.
Have you considered using
reader.GetInt32(reader.GetOrdinal(columnName))
rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.
What is the difference between Git and GitHub?
Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)
In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).
Is Git saving every repository locally (in the user's machine) and in GitHub?
Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:
How does Git compare to a backup system such as Time Machine?
Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, this is a manual process.
If are not collaborating and you are already using a backup system why would you use Git?
For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.
Improvement over the accepted answer by explicitly checking for null
but with a simplified syntax:
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
}
// Test_x000D_
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test_x000D_
_x000D_
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {_x000D_
// your code here ..._x000D_
console.log ("Yayy! None of them are null");_x000D_
} else {_x000D_
console.log ("Oops! At-lease one of them is null");_x000D_
}
_x000D_
in your view blade change to
{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}
<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>
<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>
{{ Form::close() }}
actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.
reference: Laravel Blade Form
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
On my Mac:
/System/Library/Frameworks/JavaVM.framework/Home/
btw, did you tried which java
?
The difference are:
$(document).ready(function() {
is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.
$(window).load()
event is fired after whole content is loaded.
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
Okay I found the correct answer to this issue here
Here are the steps:
Now in the top row of your filtered data (just below the header) enter the following code:
=MAX($"Your Column Letter"$1:"Your Column Letter"$"The current row for the filter - 1") + 1
Ex:
=MAX($A$1:A26)+1
Which would be applied starting at cell A27.
Hold Ctrl and press enter.
Note this only works in a range, not in a table!
Git will automatically detect the move/rename if your modification is not too severe. Just git add
the new file, and git rm
the old file. git status
will then show whether it has detected the rename.
additionally, for moves around directories, you may need to:
git add -A .
git status
to verify that the "new file" is now a "renamed" fileIf git status still shows "new file" and not "renamed" you need to follow Hank Gay’s advice and do the move and modify in two separate commits.
Synchronous solution :
void DisplayProcessStatus(Process process)
{
process.Refresh(); // Important
if(process.HasExited)
{
Console.WriteLine("Exited.");
}
else
{
Console.WriteLine("Running.");
}
}
Asynchronous solution:
void RegisterProcessExit(Process process)
{
// NOTE there will be a race condition with the caller here
// how to fix it is left as an exercise
process.Exited += process_Exited;
}
static void process_Exited(object sender, EventArgs e)
{
Console.WriteLine("Process has exited.");
}
If you want to get a class name from inside a class method, class.name
or self.class.name
won't work. These will just output Class
, since the class of a class is Class
. Instead, you can just use name
:
module Foo
class Bar
def self.say_name
puts "I'm a #{name}!"
end
end
end
Foo::Bar.say_name
output:
I'm a Foo::Bar!
You can use both of these methods but there are differences:
SELECT ISNULL(col1, 0 ) FROM table1
SELECT COALESCE(col1, 0 ) FROM table1
Comparing COALESCE() and ISNULL():
The ISNULL function and the COALESCE expression have a similar purpose but can behave differently.
Because ISNULL is a function, it is evaluated only once. As described above, the input values for the COALESCE expression can be evaluated multiple times.
Data type determination of the resulting expression is different. ISNULL uses the data type of the first parameter, COALESCE follows the CASE expression rules and returns the data type of value with the highest precedence.
The NULLability of the result expression is different for ISNULL and COALESCE. The ISNULL return value is always considered NOT NULLable (assuming the return value is a non-nullable one) whereas COALESCE with non-null parameters is considered to be NULL. So the expressions ISNULL(NULL, 1) and COALESCE(NULL, 1) although equivalent have different nullability values. This makes a difference if you are using these expressions in computed columns, creating key constraints or making the return value of a scalar UDF deterministic so that it can be indexed as shown in the following example.
-- This statement fails because the PRIMARY KEY cannot accept NULL values -- and the nullability of the COALESCE expression for col2 -- evaluates to NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0) PRIMARY KEY,
col3 AS ISNULL(col1, 0)
);
-- This statement succeeds because the nullability of the -- ISNULL function evaluates AS NOT NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0),
col3 AS ISNULL(col1, 0) PRIMARY KEY
);
Validations for ISNULL and COALESCE are also different. For example, a NULL value for ISNULL is converted to int whereas for COALESCE, you must provide a data type.
ISNULL takes only 2 parameters whereas COALESCE takes a variable number of parameters.
if you need to know more here is the full document from msdn.
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
For cases where key can be null and we want to group them as others
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'},
{'make':'kia','model':'optima','year':'2033'},
{'make':null,'model':'zen','year':'2012'},
{'make':null,'model':'blue','year':'2017'},
];
result = cars.reduce(function (r, a) {
key = a.make || 'others';
r[key] = r[key] || [];
r[key].push(a);
return r;
}, Object.create(null));
If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.
Generate random varchars to use as image name.
function genhash($strlen) {
$h_len = $len;
$cstrong = TRUE;
$sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
return bin2hex($sslkey);
}
$randName = genhash(3);
#You can increase or decrease length of the image name (1, 2, 3 or more).
Get image data extension and base_64 part (part after data:image/png;base64,) from image .
$pos = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];
if(in_array($imgExten, $extens)) {
$imgNewName = $randName. '.' . $imgExten;
$filepath = "resources/images/govdoc/".$imgNewName;
$fileP = fopen($filepath, 'wb');
$imgCont = explode(',', $base64_img);
fwrite($fileP, base64_decode($imgCont[1]));
fclose($fileP);
}
# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.
# Please don't forget to up vote if you like my solution. :)
It's easy just add the name which you want to use in quotes before adding vector
a_matrix <- cbind(b_matrix,'Name-Change'= c_vector)
Assuming your file is named "myfile.ext"
If the file you're trying to load is not an R-script, for which you would use
source("myfile.ext")
you might try the readRDS
function and assign it to a variable-name:
my.data <- readRDS("myfile.ext")
If the message is "n commits behind master."
You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.
Steps:
git checkout master
git pull #this will update your local master
git checkout yourDevBranch
git rebase master
Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate
(or the equivalent Joda Time classes for Java 7 and older)
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}
I would thoroughly recommend using java.time
(or Joda Time) over the built-in Date
/Calendar
classes.
Several reasons:
String.Format()
is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.String.Format()
is often faster, as it uses a StringBuilder
and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.String.Format()
is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf()
function.Finally, don't forget StringBuilder.AppendFormat()
. String.Format()
actually uses this method behind the scenes*, and going to the StringBuilder
directly can give you a kind of hybrid approach: explicitly use .Append()
(analogous to concatenation) for some parts of a large string, and use .AppendFormat()
in others.
* [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.
I ended up using the schedule module. The API is nice.
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
char buffer[41];
memset(buffer, '-', 40); // initialize all with the '-' character<br /><br />
buffer[40] = 0; // put a NULL at the end<br />
printf("%s\n", buffer); // show 40 dashes<br />
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
this.dataSource = new MatTableDataSource<Element>(this.elements);
Add this line below your action of add or delete the particular row.
refresh() {
this.authService.getAuthenticatedUser().subscribe((res) => {
this.user = new MatTableDataSource<Element>(res);
});
}
Just a minor modification to the excellent answer above by Lessan Vaezi. I ran into a situation where I needed to include attributes in my option entries. The original implementation loses any tag attributes. This version of the above answer preserves the option tag attributes:
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({
value: $(this).val(),
text: $(this).text(),
attrs: this.attributes, // Preserve attributes.
});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search, "gi");
$.each(options, function(i) {
var option = options[i];
if (option.text.match(regex) !== null) {
var new_option = $('<option>').text(option.text).val(option.value);
if (option.attrs) // Add old element options to new entry
{
$.each(option.attrs, function () {
$(new_option).attr(this.name, this.value);
});
}
$(select).append(new_option);
}
});
});
});
};
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
You can force asynchronous JavaScript in NodeJS to be synchronous with sync-rpc.
It will definitely freeze your UI though, so I'm still a naysayer when it comes to whether what it's possible to take the shortcut you need to take. It's not possible to suspend the One And Only Thread in JavaScript, even if NodeJS lets you block it sometimes. No callbacks, events, anything asynchronous at all will be able to process until your promise resolves. So unless you the reader have an unavoidable situation like the OP (or, in my case, are writing a glorified shell script with no callbacks, events, etc.), DO NOT DO THIS!
But here's how you can do this:
./calling-file.js
var createClient = require('sync-rpc');
var mySynchronousCall = createClient(require.resolve('./my-asynchronous-call'), 'init data');
var param1 = 'test data'
var data = mySynchronousCall(param1);
console.log(data); // prints: received "test data" after "init data"
./my-asynchronous-call.js
function init(initData) {
return function(param1) {
// Return a promise here and the resulting rpc client will be synchronous
return Promise.resolve('received "' + param1 + '" after "' + initData + '"');
};
}
module.exports = init;
LIMITATIONS:
These are both a consequence of how sync-rpc
is implemented, which is by abusing require('child_process').spawnSync
:
JSON.stringify
, so functions and non-enumerable properties like prototype chains will be lost.If you want to force the issue, you can do:
git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07
send you back to how your git clone looked like at the time of the checkin
I know this is an old post, but I thought I would share my solution to help others.
This function will work if you want to valid 10 digits phone number "US number"
function getValidNumber(value)
{
value = $.trim(value).replace(/\D/g, '');
if (value.substring(0, 1) == '1') {
value = value.substring(1);
}
if (value.length == 10) {
return value;
}
return false;
}
Here how to use this method
var num = getValidNumber('(123) 456-7890');
if(num !== false){
alert('The valid number is: ' + num);
} else {
alert('The number you passed is not a valid US phone number');
}
document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;
This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
print_r() and var_dump() are Array debugging functions used in PHP for debugging purpose. print_r() function returns the array keys and its members as Array([key] = value) whereas var_dump() function returns array list with its array keys with data type and length as well e.g Array(array_length){[0] = string(1)'a'}.
The list from 2020-05-23 is:
31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22
The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:
whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.
You can do this,
User.query.filter_by(id=123).delete()
or
User.query.filter(User.id == 123).delete()
Make sure to commit
for delete()
to take effect.
Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
public byte[] loadBinaryFile (String name) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(name));
byte[] theBytes = new byte[dis.available()];
dis.read(theBytes, 0, dis.available());
dis.close();
return theBytes;
} catch (IOException ex) {
}
return null;
} // ()
if($("input:radio[name=test]").is(":checked")){
//Code to append goes here
}
How about writing your own concat method?
public static Stream<T> concat(Stream<? extends T> a,
Stream<? extends T> b,
Stream<? extends T> args)
{
Stream<T> concatenated = Stream.concat(a, b);
for (Stream<T> stream : args)
{
concatenated = Stream.concat(concatenated, stream);
}
return concatenated;
}
This at least makes your first example a lot more readable.
To Hugo:
You probably mean list
rather than array
, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.
Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all
try:
my_sequence.extend(o)
except TypeError:
my_sequence.append(o)
One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.
I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ]
around your single value when you pass it in if need be.
(Though this can cause errors with strings, as they do look like (are) sequences.)
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
you can use this:
new SolidBrush(color)
where color is something like this:
Color.Red
or
Color.FromArgb(36,97,121))
or ...
1 ) Only the copy of reference is sent as a value to the formal parameter. When the formal parameter variable is assigned other value ,the formal parameter's reference changes but the actual parameter's reference remain the same incase of this integer object.
public class UnderstandingObjects {
public static void main(String[] args) {
Integer actualParam = new Integer(10);
changeValue(actualParam);
System.out.println("Output " + actualParam); // o/p =10
IntObj obj = new IntObj();
obj.setVal(20);
changeValue(obj);
System.out.println(obj.a); // o/p =200
}
private static void changeValue(Integer formalParam) {
formalParam = 100;
// Only the copy of reference is set to the formal parameter
// this is something like => Integer formalParam =new Integer(100);
// Here we are changing the reference of formalParam itself not just the
// reference value
}
private static void changeValue(IntObj obj) {
obj.setVal(200);
/*
* obj = new IntObj(); obj.setVal(200);
*/
// Here we are not changing the reference of obj. we are just changing the
// reference obj's value
// we are not doing obj = new IntObj() ; obj.setValue(200); which has happend
// with the Integer
}
}
class IntObj { Integer a;
public void setVal(int a) {
this.a = a;
}
}
youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.
It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.
from datetime import date
startDate = date(2012, 12, 21)
# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)
If you're having problems creating one given your format, let us know.
i faced an issue something like this...
Actually, in two ways you can process find
command output in copy
command
If find
command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:
Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>
Example: find -mtime -1 -type f | xargs cp -t inner/
But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:
Syntax: find <path> <condition> -exec cp '{}' <copy path> \;
Example find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, last part i.e semi-colon is also considered as part of find
command, that should be escaped before press the enter button. Otherwise you will get an error something like this
find: missing argument to `-exec'
In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend
. The following command will work:
find /home/shantanu/processed/ -name '*2011*.xml' -exec cp {} /home/shantanu/tosend \;
following commands will do the same perfectly
rm -rf vendor
composer install
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
try {
String command = "Command here";
Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + command);
} catch (IOException e) {
e.printStackTrace();
}
Use Spotlight.
But only the last simulator will be opened. If you used iPad Air 2
last time, Spotlight will open it. If you wanna open iPhone 6s
this time, that's a problem.
This is the stupidest thing I've ever seen, but it works, and you can't argue with results.
SELECT *
FROM (
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) derivedTable
The interior of the derived table will not execute on its own, but as a derived table works perfectly fine. I've tried this on SS 2000, SS 2005, SS 2008 R2, and all three work.
For simply checking against Object or Array without additional function call (speed).
isArray()
isArray = function(a) {
return (!!a) && (a.constructor === Array);
};
console.log(isArray( )); // false
console.log(isArray( null)); // false
console.log(isArray( true)); // false
console.log(isArray( 1)); // false
console.log(isArray( 'str')); // false
console.log(isArray( {})); // false
console.log(isArray(new Date)); // false
console.log(isArray( [])); // true
isObject()
isObject = function(a) {
return (!!a) && (a.constructor === Object);
};
console.log(isObject( )); // false
console.log(isObject( null)); // false
console.log(isObject( true)); // false
console.log(isObject( 1)); // false
console.log(isObject( 'str')); // false
console.log(isObject( [])); // false
console.log(isObject(new Date)); // false
console.log(isObject( {})); // true
I used the following today - It works!
Add a value to an extensionAttribute
$ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
Set-ADUser –Identity $ThisUser -add @{"extensionattribute1"="MyString"}
Remove a value from an extensionAttribute
$ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
Set-ADUser –Identity $ThisUser -Clear "extensionattribute1"
An efficient command line tool, open source, free of any fee, available on both linux & windows : simply named pdftotext. This tool is a part of the xpdf library.
IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value
(percentage) and parameter
(parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return 0.7 * value.ToDouble();
string[] split = parameter.ToString().Split('.');
double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
return value.ToDouble() * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
}
XAML:
<UserControl.Resources>
<m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
if you have this kind of problem with ispconfig3 and got an error like this
open_basedir restriction in effect. File(/var/www/clients/client7/web15) is not within the allowed path(s):.........
To solve it (in my case) , just set PHP to SuPHP in the Website's panel of ispconfig3
Hope it helps someone :)
ADDITION :
Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.
TO FIX THIS:
FOR SETS
var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray
Result: ["a","b","c"]
Without sorted()
It can be:
["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"]
simple math : 3! = 6
console.log(_x000D_
new Date().toLocaleString().slice(9, -3)_x000D_
, new Date().toString().slice(16, -15)_x000D_
);
_x000D_
For GUI apps, you'll have to create and edit ~/.MacOSX/environment.plist
. More details here. You will need to log out for these to take effect. I'm not sure if they also affect applications launched from Terminal, but I assume they would.
For apps launched from Terminal, you can also edit the ~/.profile file.
The git interaction library part of StGit is actually pretty good. However, it isn't broken out as a separate package but if there is sufficient interest, I'm sure that can be fixed.
It has very nice abstractions for representing commits, trees etc, and for creating new commits and trees.
I had the same problem in Eclipse and I fixed it by changing the JRE from 64 bit to 32 bit:
Window > Preferences > Java > Installed JREs > Add... > Next > Directory > select "C:\Program Files (x86)\Java\jre1.8.0_65" instead of "C:\Program Files\Java\jre1.8.0_60"
Steps:
1)Add the required permissions in the Manifest.xml
file.
<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
2)Create a listener for the phone state changes.
public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
//wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
//when this state occurs, and your flag is set, restart your app
Intent i = context.getPackageManager().getLaunchIntentForPackage(
context.getPackageName());
//For resuming the application from the previous state
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//Uncomment the following if you want to restart the application instead of bring to front.
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
}
}
}
3)Initialize the listener in your OnCreate
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP
with FLAG_ACTIVITY_SINGLE_TOP
Reference this Answer
At a guess, you're initialising something before your initialize function:
var directionsService = new google.maps.DirectionsService();
Move that into the function, so it won't try and execute it before the page is loaded.
var directionsDisplay, directionsService;
var map;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
XML Copy Editor is perfect for this type of thing.
in my case using angular
in my HTTP interceptor , i set
with Credentials: true.
in the header of the request
os.homedir()
was added by this PR and is part of the public 4.0.0 release of nodejs.
Example usage:
const os = require('os');
console.log(os.homedir());
The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.
java 8 and above
StreamSupport.stream(data.spliterator(), false).count();
in case you have a variable :
$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';
Github's libgit2 binding, pygit2 provides a one-liner cloning a remote directory:
clone_repository(url, path,
bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)
You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.
I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig
.
To upgrade to matplotlib 1.1.0 with pip
, use this command:
pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'
EDIT (to respond to comment):
pylab
is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.
On my system, pylab
is just this:
from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__
You can see that pylab
is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab
or with matplotlib.pyplot
.
If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.
For not balanced searching tree, it takes O(n).
For balanced searching tree, it takes O(k + log n) in the worst case but just O(k) in Amortized sense.
Having and managing the extra integer for every node: the size of the sub-tree gives O(log n) time complexity. Such balanced searching tree is usually called RankTree.
In general, there are solutions (based not on tree).
Regards.
var depthead = (from s in db.M_Users
join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
select new {s.FullName,s.F_User_Type,s.userId,s.UserCode }
).OrderBy(d => d.userId).ToList();
Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });
Assuming the image data is already in the format you want, you don't need image ImageIO
at all - you just need to write the data to the file:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)
If the image data isn't in the format you want, you'll need to give more details.
Instances of the image constructor are not meant to be used anywhere. You simply set the src
, and the image preloads...and that's it, show's over. You can discard the object and move on.
document["pic1"].src = "XXXX/YYYY/search.png";
is what you should be doing. You can still use the image constructor, and perform the second action in the onload
handler of your searchPic
. This ensures the image is loaded before you set the src
on the real img
object.
Like so:
function LoadImages() {
searchPic = new Image();
searchPic.onload=function () {
document["pic1"].src = "XXXX/YYYY/search.png";
}
searchPic.src = "XXXX/YYYY/search.png"; // This is correct and the path is correct
}
Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.
# suppose we have a sample object as below
sampleObj.name #=> foo
sampleObj.last_name #=> bar
# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
json.name sampleObj.name
json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"
Array push and pop method can be used for sequence of promises. You can also push new promises when you need additional data. This is the code, I will use in React Infinite loader to load sequence of pages.
var promises = [Promise.resolve()];_x000D_
_x000D_
function methodThatReturnsAPromise(page) {_x000D_
return new Promise((resolve, reject) => {_x000D_
setTimeout(() => {_x000D_
console.log(`Resolve-${page}! ${new Date()} `);_x000D_
resolve();_x000D_
}, 1000);_x000D_
});_x000D_
}_x000D_
_x000D_
function pushPromise(page) {_x000D_
promises.push(promises.pop().then(function () {_x000D_
return methodThatReturnsAPromise(page)_x000D_
}));_x000D_
}_x000D_
_x000D_
pushPromise(1);_x000D_
pushPromise(2);_x000D_
pushPromise(3);
_x000D_
Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by tput
, slight misuse of printf
padding/filling and tr
printf "%0$(tput cols)d" 0|tr '0' '='
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.
css
thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}
html
<table>
<thead>
<tr><th>hey</th><th>ho</th></tr>
</thead>
<tbody>
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
</tbody>
Floated elements do not occupy the space inside of the parent element, As the name suggests they float! Thus if a height is explicitly not provided to an element having its child elements floated, then the parent element will appear to shrink & appear to not accepting dimensions of the child element, also if its given overflow:hidden;
its children may not appear on screen. There are multiple ways to deal with this problem:
Insert another element below the floated element with clear:both;
property, or use clear:both;
on :after
of the floated element.
Use display:inline-block;
or flex-box
instead of float
.
I think the best answer is actually explained on the vim wikia:
http://vim.wikia.com/wiki/Indenting_source_code
Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.
Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping settings icon then scroll down to developer options and tap it then you will see on the top right a on off switch select on and then tap ok, thats it you all done.
To use the environment virtualenv has created, you first need to source env/bin/activate
. After that, just install packages using pip install package-name
.
With POD you can also write
Snapshot s = {};
You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.
or like this:
struct init
{
template <typename T>
operator T * ()
{
return new T();
}
};
Snapshot* s = init();
Use this snippet:
@echo off
echo something
echo.
echo press enter to exit
pause >nul
exit
em.persist(abc);
em.refresh(abc);
return abc;
I had a similar problem but solved changing the direction of the slash sign:
For some reason when Atom copies Paths from the project folder it does so like background-image: url(img\image.jpg\)
instead of (img/image.jpeg)
While i can see it's not the case for OP may be useful for other people (I just wasted half the morning wondering why my stylesheet wasn´t loading)
Use jenv, it is like a Java environment manager. It is super easy to use and clean
For Mac, follow the steps:
brew install jenv
git clone https://github.com/gcuisinier/jenv.git ~/.jenv
Installation: If you are using bash follow these steps:
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ exec $SHELL -l
Add desired versions of JVM to jenv:
jenv add /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
jenv add /System/Library/Java/JavaVirtualMachines/1.8.0.jdk/Contents/Home
Check the installed versions:
jenv versions
Set the Java version you want to use by:
jenv global oracle64-1.6.0
You can find the solution here!
Install the service named 'Tomcat7'
C:\>Tomcat\bin\service.bat install
There is a 2nd optional parameter that lets you specify the name of the service, as displayed in Windows services.
Install the service named 'MyTomcatService'
C:\>Tomcat\bin\service.bat install MyTomcatService
Code below work.
- (id)ht_findFirstResponder
{
//ignore hit test fail view
if (self.userInteractionEnabled == NO || self.alpha <= 0.01 || self.hidden == YES) {
return nil;
}
if ([self isKindOfClass:[UIControl class]] && [(UIControl *)self isEnabled] == NO) {
return nil;
}
//ignore bound out screen
if (CGRectIntersectsRect(self.frame, [UIApplication sharedApplication].keyWindow.bounds) == NO) {
return nil;
}
if ([self isFirstResponder]) {
return self;
}
for (UIView *subView in self.subviews) {
id result = [subView ht_findFirstResponder];
if (result) {
return result;
}
}
return nil;
}
With ASP.NET Core 2.0, the ideal way to return object from Web API
(which is unified with MVC and uses same base class Controller
) is
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
Notice that
200 OK
status code (it's an Ok
type of ObjectResult
)Accept
header in request. If Accept: application/xml
is sent in request, it'll return as XML
. If nothing is sent, JSON
is default.If it needs to send with specific status code, use ObjectResult
or StatusCode
instead. Both does the same thing, and supports content negotiation.
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
or even more fine grained with ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
If you specifically want to return as JSON, there are couple of ways
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
Notice that
JSON
in two different ways.Json(object)
.Produces()
attribute (which is a ResultFilter
) with contentType = application/json
Read more about them in the official docs. Learn about filters here.
The simple model class that is used in the samples
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
You can't do that, because GetFiles
only accepts a single search pattern. Instead, you can call GetFiles
with no pattern, and filter the results in code:
string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };
FileInfo[] files =
dinfo.GetFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
If you're working with .NET 4, you can use the EnumerateFiles
method to avoid loading all FileInfo objects in memory at once:
string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };
FileInfo[] files =
dinfo.EnumerateFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
your class should be public
public class FBlock : IDesignRegionInserts, IFormRegionInserts, IAPIRegionInserts, IConfigurationInserts, ISoapProxyClientInserts, ISoapProxyServiceInserts
Modify Mysql encryption
ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
The $scope
that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope
and you can create a new child-scope using the $new()
method of any scope (including the $rootScope
).
The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope
into a service.
Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).
I am sure, various approaches would work for you. One is this:
Since the StudentService
is in charge of dealing with student data, you can have the StudentService
keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope
). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon).
Every time a new student is added (using the service's save()
method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well.
Based on the approach described above, your code could look like this:
angular.
module('cfd', []).
factory('StudentService', ['$http', '$q', function ($http, $q) {
var path = 'data/people/students.json';
var students = [];
// In the real app, instead of just updating the students array
// (which will be probably already done from the controller)
// this method should send the student data to the server and
// wait for a response.
// This method returns a promise to emulate what would happen
// when actually communicating with the server.
var save = function (student) {
if (student.id === null) {
students.push(student);
} else {
for (var i = 0; i < students.length; i++) {
if (students[i].id === student.id) {
students[i] = student;
break;
}
}
}
return $q.resolve(student);
};
// Populate the students array with students from the server.
$http.get(path).then(function (response) {
response.data.forEach(function (student) {
students.push(student);
});
});
return {
students: students,
save: save
};
}]).
controller('someCtrl', ['$scope', 'StudentService',
function ($scope, StudentService) {
$scope.students = StudentService.students;
$scope.saveStudent = function (student) {
// Do some $scope-specific stuff...
// Do the actual saving using the StudentService.
// Once the operation is completed, the $scope's `students`
// array will be automatically updated, since it references
// the StudentService's `students` array.
StudentService.save(student).then(function () {
// Do some more $scope-specific stuff,
// e.g. show a notification.
}, function (err) {
// Handle the error.
});
};
}
]);
One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break.
E.g. to clear the array in StudentService
:
/* DON'T DO THAT */
var clear = function () { students = []; }
/* DO THIS INSTEAD */
var clear = function () { students.splice(0, students.length); }
See, also, this short demo.
LITTLE UPDATE:
A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service()
function.
Quoting the docs on $provide
:
An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called
$get
, which holds the service factory function.
[...]
...the$provide
service has additional helper methods to register services without specifying a provider:
- provider(provider) - registers a service provider with the $injector
- constant(obj) - registers a value/object that can be accessed by providers and services.
- value(obj) - registers a value/object that can only be accessed by services, not providers.
- factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
- service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.
Basically, what it says is that every Angular service is registered using $provide.provider()
, but there are "shortcut" methods for simpler services (two of which are service()
and factory()
).
It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method).
BTW, provider
vs service
vs factory
is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.)
(I hope that clears it up - let me know if it doesn't.)
This is not specific to sqlite but you can just do
SELECT * FROM ... WHERE UPPER(name) = UPPER('someone')
Actually you need to include the JavaScript code at the moment, check this tutorial to do so.
but there is a tricky way to achieve this using a CSS code you must nest an anchor tag inside your div tag and you must apply this property to it,
display:block;
when you've done that,it will make the whole width area clickable (but within the height of the anchor tag),if you want to cover the whole div area you must set the height of the anchor tag exactly to the height of the div tag,for example:
height:60px;
this is gonna make the whole area clickable,then you can apply text-indent:-9999px
to anchor tag to achieve the goal.
this is really tricky and simple and it's just created using CSS code.
here is an example: http://jsfiddle.net/hbirjand/RG8wW/
Well, the simplest way using LINQ would be something like this:
list = list.OrderBy(x => x.AVC ? 0 : 1)
.ToList();
or
list = list.OrderByDescending(x => x.AVC)
.ToList();
I believe that the natural ordering of bool
values is false < true
, but the first form makes it clearer IMO, because everyone knows that 0 < 1
.
Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list
variable. If you want to sort in place, you should use the List<T>.Sort
method.
I know its late but this regex should solve your problem. This will match and return the number of words in your string. Rather then the one you marked as a solution, which would count space-space-word as 2 words even though its really just 1 word.
function countWords(str) {
var matches = str.match(/\S+/g);
return matches ? matches.length : 0;
}
its very simple... to add a vertical line in android xml...
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:rotation="90"
android:background="@android:color/darker_gray"/>
The other methods work fine, but you can also use the good old django.shortcut.redirect
.
The code below was taken from this answer.
In Django 2.x:
from django.shortcuts import redirect
from django.urls import path, include
urlpatterns = [
# this example uses named URL 'hola-home' from app named hola
# for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
path('', lambda request: redirect('hola/', permanent=True)),
path('hola/', include('hola.urls')),
]
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
import pylab as pl
pl.xticks(rotation = 90)
Take a look at docopt. It is a formal standard for documenting (and automatically parsing) command line arguments.
For example...
Usage:
my_program command --option <argument>
my_program [<optional-argument>]
my_program --another-option=<with-argument>
my_program (--either-that-option | <or-this-argument>)
my_program <repeating-argument> <repeating-argument>...
I encountered this padding error when i would manually edit the encrypted strings in the file (using notepad) because i wanted to test how decryption function will behave if my encrypted content was altered manually.
The solution for me was to place a
try
decryption stuff....
catch
inform decryption will not be carried out.
end try
Like i said my padding error was because i was manually typing over the decrypted text using notepad. May be my answer may guide you to your solution.
I like the solution for modern browsers, but the bullets are missing, so I add it a little trick:
http://jsfiddle.net/HP85j/419/
ul {
list-style-type: none;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}
li:before {
content: "• ";
}
Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })
@WebAppConfiguration
public class TestClass {
@Test
public void test() {
// test definition here..
}
}
I think this is the most portable:
abspath() {
cd "$(dirname "$1")"
printf "%s/%s\n" "$(pwd)" "$(basename "$1")"
cd "$OLDPWD"
}
It will fail if the path does not exist though.
That's because there was an error in your query. MySQli->query()
will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Add
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
In Swift 4 or Swift 5 you can use NSHomeDirectory()
.
The easiest way in Xcode 10 (or Xcode 11) is to pause your app (like when it hits a breakpoint) and run this line in the debugger console:
po NSHomeDirectory()
po
stands for print object and prints most things
If you need to brute force it for older browser compatibility, you can use Colllor to automatically select similar color variations.
Example (color: #a9dbb4):
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
I believe that should work for an uppercase, number pattern.
Just to document if someone has the same problem...
In my situation I've been using :uuid
fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint
instead :uuid
:
add_reference :uploads, :user, index: true, type: :uuid
Reference: Active Record Postgresql UUID
If you are on windows. Open your cmd at right folder then first
set node_env={your env name here}
hit enter then you can start your node with
node app.js
it will start with your env setting
Can you try the following:
float: right;
#!/usr/bin/env sh
# Searches a subset string in a string:
# 1st arg:reference string
# 2nd arg:subset string to be matched
if echo "$1" | grep -q "$2"
then
echo "$2 is in $1"
else
echo "$2 is not in $1"
fi
Make column B in sheet1 the dates but where the day of the month is always the first day of the month, e.g. in B2 put =DATE(YEAR(A2),MONTH(A2),1). Then make E5 on sheet 2 contain the first date of the month you need, e.g. Date(2013,4,1). After that, putting in F5 COUNTIF(Sheet1!B2:B50, E5) will give you the count for the month specified in E5.
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.
Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.
For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
For more info, see https://www.firebase.com/docs/transactions.html
UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.
If you want to count upvotes for example, you should create a structure similar to this one:
{
"posts" : {
"-JRHTHaIs-jNPLXOQivY" : {
"upvotes_count":5,
"upvotes" : {
"userX" : true,
"userY" : true,
"userZ" : true,
...
}
}
}
}
And then write a javascript function to increase the upvotes_count
when there is a new write to the upvotes
node.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});
You can read the Documentation to know how to Get Started with Cloud Functions.
Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js
The firebase docs have changed so instead of event
we now have change
and context
.
The given example throws an error complaining that event.data
is undefined. This pattern seems to work better:
exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
const data = change.after.val();
const count = Object.keys(data).length;
return change.after.ref.child('_count').set(count);
});
```
It's easy with git add -i
. Type a
(for "add untracked"), then *
(for "all"), then q
(to quit) and you're done.
To do it with a single command: echo -e "a\n*\nq\n"|git add -i
To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.
I had a small success by doing the following after creating the dialog on element $dlg
.
$dlg.closest('.ui-dialog').css('zIndex',adjustment);
Since each dialog has a different starting z-index
(they incrementally get larger) I make adjustment
a string with a boost value, like this:
const adjustment = "+=99";
However, jQuery just keeps increasing the zIndex
value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:
CoverAll = {};
CoverAll.modalDiv = null;
CoverAll.modalCloak = function(zIndex) {
var div = CoverAll.modalDiv;
if(!CoverAll.modalDiv) {
div = CoverAll.modalDiv = document.createElement('div');
div.style.background = '#aaaaaa';
div.style.opacity = '0.3';
div.style.position = 'fixed';
div.style.top = '0';
div.style.left = '0';
div.style.width = '100%';
div.style.height = '100%';
}
if(!div.parentElement) {
document.body.appendChild(div);
}
if(zIndex == null)
zIndex = 100;
div.style.zIndex = zIndex;
return div;
}
CoverAll.modalUncloak = function() {
var div = CoverAll.modalDiv;
if(div && div.parentElement) {
document.body.removeChild(div);
}
return div;
}
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Update 2018
You should be able to just set it using CSS like this..
.dropdown-menu {
min-width:???px;
}
This works in both Bootstrap 3 and Bootstrap 4.0.0 (demo).
A no extra CSS option in Bootstrap 4 is using the sizing utils to change the width. For example, here the w-100 (width:100%) class is used for the dropdown menu to fill the width of it's parent....
<ul class="dropdown-menu w-100">
<li><a class="nav-link" href="#">Choice1</a></li>
<li><a class="nav-link" href="#">Choice2</a></li>
<li><a class="nav-link" href="#">Choice3</a></li>
</ul>
To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook
However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.
Put these two lines before you import anything else from matplotlib:
import matplotlib
matplotlib.use('GTKAgg')
Of course, there are various options to use instead of GTKAgg
, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.
From you own project.
npx nodemon [your-app.js]
With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start
) or using npx nodemon
.
OR
Create a simple symbolik link
ln -s /Users/YourUsername/.npm-global/bin/nodemon /usr/local/bin
ln -s [from: where is you install 'nodemon'] [to: folder where are general module for node]
node : v12.1.0
npm : 6.9.0
You can remove illegal chars using Linq like this:
var invalidChars = Path.GetInvalidFileNameChars();
var invalidCharsRemoved = stringWithInvalidChars
.Where(x => !invalidChars.Contains(x))
.ToArray();
EDIT
This is how it looks with the required edit mentioned in the comments:
var invalidChars = Path.GetInvalidFileNameChars();
string invalidCharsRemoved = new string(stringWithInvalidChars
.Where(x => !invalidChars.Contains(x))
.ToArray());
Format 1 : $format1 = "2012-12-31";
Format 2 : $format2 = "31-12-2012";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$format1)) {
return true;
} else {
return false;
}
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{4}$/",$format2)) {
return true;
} else {
return false;
}
The functional way of achieving this is to unzip the list using:
sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)
(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)
you just open command prompt,
then enter in c:/>('cd../../')
then npm install -g cordova
The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.
To fix this I added the following to manually trigger the jquery validation event that gets added by the library:
$(".chosen-select").each(function() {
$(this).chosen().on("change", function() {
$(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
});
});
jquery.validate will now add the .valid
class to the underlying select list.
Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group
, and each input has .form-control
.
the Query Will be
db.mycollection.find({"IMAGE URL":{"$exists":"true"}})
it will return all documents having "IMAGE URL" as a key ...........
Several of the System.IO.Path methods will throw exceptions if the path or filename is invalid:
http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx
Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.
To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.
A brief excerpt:
The flag -XX:+PrintGC
(or the alias -verbose:gc
) activates the “simple” GC logging mode
By default the GC log is written to stdout. With -Xloggc:<file>
we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC
and -XX:+PrintGCTimeStamps
as well.
If we use -XX:+PrintGCDetails
instead of -XX:+PrintGC
, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.
With -XX:+PrintGCTimeStamps
a timestamp reflecting the real time passed in seconds since JVM start is added to every line.
If we specify -XX:+PrintGCDateStamps
each line starts with the absolute date and time.
If you want to delete a property deeply nested in the object then you can use the following recursive function with path to the property as the second argument:
var deepObjectRemove = function(obj, path_to_key){
if(path_to_key.length === 1){
delete obj[path_to_key[0]];
return true;
}else{
if(obj[path_to_key[0]])
return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
else
return false;
}
};
Example:
var a = {
level1:{
level2:{
level3: {
level4: "yolo"
}
}
}
};
deepObjectRemove(a, ["level1", "level2", "level3"]);
console.log(a);
//Prints {level1: {level2: {}}}
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).
You can use wireshark or tcpdump to look on any network traffic (http too).
You haven't actually asked a question, but assuming you have one, this could be your answer...
Assuming all characters, except the "Special Characters" are allowed you can write
String regex = "^[^<>'\"/;`%]*$";
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
HeaderText
for the GridViewColumn
and then find the column using that HeaderText
.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
If you use $window.localStorage.setItem(key,value)
to store,$window.localStorage.getItem(key)
to retrieve and $window.localStorage.removeItem(key)
to remove, then you can access the values in any page.
You have to pass the $window
service to the controller. Though in JavaScript, window
object is available globally.
By using $window.localStorage.xxXX()
the user has control over the localStorage
value. The size of the data depends upon the browser. If you only use $localStorage
then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a>
to navigate to other page then your $localStorage
value is lost in the next page.
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
I suggest using the Google Charts API because you can specify the text, text color, fill color and outline color, all using hex color codes, e.g. #FF0000 for red. You can call it as follows:
function getIcon(text, fillColor, textColor, outlineColor) {
if (!text) text = '•'; //generic map dot
var iconUrl = "http://chart.googleapis.com/chart?cht=d&chdp=mapsapi&chl=pin%27i\\%27[" + text + "%27-2%27f\\hv%27a\\]h\\]o\\" + fillColor + "%27fC\\" + textColor + "%27tC\\" + outlineColor + "%27eC\\Lauto%27f\\&ext=.png";
return iconUrl;
}
Then, when you create your marker you just set the icon property as such, where the myColor variables are hex values (minus the hash sign):
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map,
icon: getIcon(null, myColor, myColor2, myColor3)
});
You can use http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=•|FF0000
, which is a bit easier to decipher, as an alternate URL if you only need to set text and fill color.
khurram's answer refers to a 3rd party site that redirects to the Google Charts API. This means if that person takes down their server you're hosed. I prefer having the flexibility the Google API offers as well as the reliability of going directly to Google. Just make sure you specify a value for each of the colors or it won't work.
From a sqlite prompt:
sqlite> .read db.sql
Or:
cat db.sql | sqlite3 database.db
Also, your SQL is invalid - you need ;
on the end of your statements:
create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);
I've been using this functionality in node.js, this is my fastest implementation so far:
var nLength = function(n) {
return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}
It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.
The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.
Update: As noted in the comments, this solution has some issues :(
Update2 (workaround) : I believe that at some point precision issues kick in and the Math.log(...)*0.434...
just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10
function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;
and with Math.log10
it worked as expected. Please note that Math.log10
is not universally supported.
Try this:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
e.g @:
I encountered a lot of problems when using jaxb in Maven but i managed to solve your problem by doing the following
First create a schema.xjc file
<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.0">
<jaxb:bindings schemaLocation="YOUR_URL?wsdl#types?schema1">
<jaxb:schemaBindings>
<jaxb:package name="your.package.name.schema1"/>
</jaxb:schemaBindings>
</jaxb:bindings>
<jaxb:bindings schemaLocation="YOUR_URL??wsdl#types?schema2">
<jaxb:schemaBindings>
<jaxb:package name="your.package.name.schema2"/>
</jaxb:schemaBindings>
</jaxb:bindings>
</jaxb:bindings>
The package name can be anything you want it to be, as long as it doesn't contain any reserved keywords in Java
Next you have to create the wsimport.bat script to generate your packaged and code at the preferred location.
cd C:\YOUR\PATH\TO\PLACE\THE\PACKAGES
wsimport -keep -verbose -b "C:\YOUR\PATH\TO\schema.xjb" YOUR_URL?wsdl
pause
If you do not want to use cd, you can put the wsimport.bat in "C:\YOUR\PATH\TO\PLACE\THE\PACKAGES"
If you run it without -keep -verbose it will only generate the packages but not the .java files.
The -b will make sure the schema.xjc is used when generating
IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
This will iterate over all descendant files, not just the immediate children of the directory:
import os
for subdir, dirs, files in os.walk(rootdir):
for file in files:
#print os.path.join(subdir, file)
filepath = subdir + os.sep + file
if filepath.endswith(".asm"):
print (filepath)
This will work
@Cacheable(value="bookCache", key="#checkwarehouse.toString().append(#isbn.toString())")
find all tabs and replaced by 4 spaces in notepad ++ .It worked.
Let'e me give an example:
client connect to server, and send 1MB data to server every 1 second.
server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer
in the client side will be full.
Code in client side:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...) \
if (r) { \
printf(__VA_ARGS__); \
printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
exit(1); \
}
void setNonBlock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
exit_if(flags < 0, "fcntl failed");
int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
exit_if(r < 0, "fcntl failed");
}
void test_full_sock_buf_1(){
short port = 8000;
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
int fd = socket(AF_INET, SOCK_STREAM, 0);
exit_if(fd<0, "create socket error");
int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
exit_if(ret<0, "connect to server error");
setNonBlock(fd);
printf("connect to server success");
const int LEN = 1024 * 1000;
char msg[LEN]; // 1MB data
memset(msg, 'a', LEN);
for (int i = 0; i < 1000; ++i) {
int len = send(fd, msg, LEN, 0);
printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
sleep(1);
}
}
int main(){
test_full_sock_buf_1();
return 0;
}
Code in server side:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...) \
if (r) { \
printf(__VA_ARGS__); \
printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
exit(1); \
}
void test_full_sock_buf_1(){
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
exit_if(listenfd<0, "create socket error");
short port = 8000;
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
exit_if(r<0, "bind socket error");
r = listen(listenfd, 100);
exit_if(r<0, "listen socket error");
struct sockaddr_in raddr;
socklen_t rsz = sizeof(raddr);
int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
exit_if(cfd<0, "accept socket error");
sockaddr_in peer;
socklen_t alen = sizeof(peer);
getpeername(cfd, (sockaddr *) &peer, &alen);
printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));
printf("but now I will sleep 15 second, then exit");
sleep(15);
}
Start server side, then start client side.
server side may output:
accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0
client side may output:
connect to server successsend: 1024000, erron: 0, Success
send: 1024000, erron: 0, Success
send: 1024000, erron: 0, Success
send: 552190, erron: 0, Success
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 104, Connection reset by peer
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer
get full, but you still send data, so you may get Resource temporarily unavailable
error.
Apple switched their default shell to zsh, so the config files include ~/.zshenv
and ~/.zshrc
. This is just like ~/.bashrc
, but for zsh. Just edit the file and add what you need; it should be sourced every time you open a new terminal window:
nano ~/.zshenv
alias py=python
Then do ctrl+x, y, then enter to save.
This file seems to be executed no matter what (login, non-login, or script), so seems better than the ~/.zshrc
file.
The default shell is bash, and you can edit the file ~/.bash_profile
and add aliases:
nano ~/.bash_profile
alias py=python
Then ctrl+x, y, and enter to save. See this post for more on these configs. It's a little better to set it up with your alias in ~/.bashrc
, then source ~/.bashrc
from ~/.bash_profile
. In ~/.bash_profile
it would then look like:
source ~/.bashrc
LocalDate.of( 1985 , 1 , 1 )
…or…
LocalDate.of( 1985 , Month.JANUARY , 1 )
The java.util.Date
, java.util.Calendar
, and java.text.SimpleDateFormat
classes were rushed too quickly when Java first launched and evolved. The classes were not well designed or implemented. Improvements were attempted, thus the deprecations you’ve found. Unfortunately the attempts at improvement largely failed. You should avoid these classes altogether. They are supplanted in Java 8 by new classes.
A java.util.Date has both a date and a time portion. You ignored the time portion in your code. So the Date class will take the beginning of the day as defined by your JVM’s default time zone and apply that time to the Date object. So the results of your code will vary depending on which machine it runs or which time zone is set. Probably not what you want.
If you want just the date, without the time portion, such as for a birth date, you may not want to use a Date
object. You may want to store just a string of the date, in ISO 8601 format of YYYY-MM-DD
. Or use a LocalDate
object from Joda-Time (see below).
First thing to learn in Java: Avoid the notoriously troublesome java.util.Date & java.util.Calendar classes bundled with Java.
As correctly noted in the answer by user3277382, use either Joda-Time or the new java.time.* package in Java 8.
DateTimeZone timeZoneNorway = DateTimeZone.forID( "Europe/Oslo" );
DateTime birthDateTime_InNorway = new DateTime( 1985, 1, 1, 3, 2, 1, timeZoneNorway );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime birthDateTime_InNewYork = birthDateTime_InNorway.toDateTime( timeZoneNewYork );
DateTime birthDateTime_UtcGmt = birthDateTime_InNorway.toDateTime( DateTimeZone.UTC );
LocalDate birthDate = new LocalDate( 1985, 1, 1 );
Dump to console…
System.out.println( "birthDateTime_InNorway: " + birthDateTime_InNorway );
System.out.println( "birthDateTime_InNewYork: " + birthDateTime_InNewYork );
System.out.println( "birthDateTime_UtcGmt: " + birthDateTime_UtcGmt );
System.out.println( "birthDate: " + birthDate );
When run…
birthDateTime_InNorway: 1985-01-01T03:02:01.000+01:00
birthDateTime_InNewYork: 1984-12-31T21:02:01.000-05:00
birthDateTime_UtcGmt: 1985-01-01T02:02:01.000Z
birthDate: 1985-01-01
In this case the code for java.time is nearly identical to that of Joda-Time.
We get a time zone (ZoneId
), and construct a date-time object assigned to that time zone (ZonedDateTime
). Then using the Immutable Objects pattern, we create new date-times based on the old object’s same instant (count of nanoseconds since epoch) but assigned other time zone. Lastly we get a LocalDate
which has no time-of-day nor time zone though notice the time zone applies when determining that date (a new day dawns earlier in Oslo than in New York for example).
ZoneId zoneId_Norway = ZoneId.of( "Europe/Oslo" );
ZonedDateTime zdt_Norway = ZonedDateTime.of( 1985 , 1 , 1 , 3 , 2 , 1 , 0 , zoneId_Norway );
ZoneId zoneId_NewYork = ZonedId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt_Norway.withZoneSameInstant( zoneId_NewYork );
ZonedDateTime zdt_Utc = zdt_Norway.withZoneSameInstant( ZoneOffset.UTC ); // Or, next line is similar.
Instant instant = zdt_Norway.toInstant(); // Instant is always in UTC.
LocalDate localDate_Norway = zdt_Norway.toLocalDate();
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
<form>
<label for="company">
<span>Company Name</span>
<input type="text" id="company" />
</label>
<label for="contact">
<span>Contact Name</span>
<input type="text" id="contact" />
</label>
</form>
label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }
Illustrated at http://jsfiddle.net/H3y8j/
7 years later and this code has helped me. However, my times still were not showing up correctly.
Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I changed the format to (%H:%M) and the time displayed correctly.
All thanks to the community.
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
Why not use the built in events?
$('#checkbox').click(function(e){
if(e.target.checked) {
// code to run if checked
console.log('Checked');
} else {
//code to run if unchecked
console.log('Unchecked');
}
});
SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.
What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:
backup.bat:
sqlcmd -i backup.sql
backup.sql:
backup database TeamCity to disk = 'c:\backups\MyBackup.bak'
Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.
The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE
queries instead.
If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.
It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:
How do I get started with the SQL Server Maintenance Solution on SQL Server Express?
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
Download MaintenanceSolution.sql.
Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.
Create cmd files to execute the stored procedures; for example:
sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txtIn Windows Scheduled Tasks, create tasks to call the cmd files.
Schedule the tasks.
Start the tasks and verify that they are completing successfully.
Answering the additional question:
my following test code for typeid does not output the correct type name. what's wrong?
There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.
These are two different tools. typeof
returns the type of an expression, but it is not standard. In C++0x there is something called decltype
which does the same job AFAIK.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
Whereas typeid
is used with polymorphic types. For example, lets say that cat
derives animal
:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
you can use those function it's so easy the First one for encryption so you just call the function and send the text you wanna encrypt it and take the result from encryptWithAES function and send it to decrypt Function like this:
const CryptoJS = require("crypto-js");
//The Function Below To Encrypt Text
const encryptWithAES = (text) => {
const passphrase = "My Secret Passphrase";
return CryptoJS.AES.encrypt(text, passphrase).toString();
};
//The Function Below To Decrypt Text
const decryptWithAES = (ciphertext) => {
const passphrase = "My Secret Passphrase";
const bytes = CryptoJS.AES.decrypt(ciphertext, passphrase);
const originalText = bytes.toString(CryptoJS.enc.Utf8);
return originalText;
};
let encryptText = encryptWithAES("YAZAN");
//EncryptedText==> //U2FsdGVkX19GgWeS66m0xxRUVxfpI60uVkWRedyU15I=
let decryptText = decryptWithAES(encryptText);
//decryptText==> //YAZAN
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
With the use of jQuery to handle the document ready event,
<script type="text/javascript">
function onLoadAlert() {
alert('<%: TempData["Resultat"]%>');
}
$(document).ready(onLoadAlert);
</script>
Or, even simpler - put the <script>
at the end of body
, not in the head
.
You can make a class to extend FPDF and add this:
class utfFPDF extends FPDF {
function Cell($w, $h=0, $txt="", $border=0, $ln=0, $align='', $fill=false, $link='')
{
if (!empty($txt)){
if (mb_detect_encoding($txt, 'UTF-8', false)){
$txt = iconv('UTF-8', 'ISO-8859-5', $txt);
}
}
parent::Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
}
}
In Ubuntu it looks like this :
$ sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev
$ sudo pip install python-ldap
I've always thought keydown happened as soon as you press the key down, keypress is the action of pressing the key and releasing it.
I found this which gives a little different explanation: http://bytes.com/topic/net/answers/649131-difference-keypress-keydown-event
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
For those who use Mac, edit this file:
/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh
Mine had:
export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
and I changed it to 1.8 and it stopped complaining about java version.
I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot
is capable of plotting multiple lines with one command. If x
and y
are arrays, then plot
draws one line for every column.
In your case, you can do the following:
x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5, 1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')
Have a long list of x's and y's, and want to connect adjacent pairs?
xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])
Want a specified (different) color for the dots and the lines?
plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')
API and Web service serve as a means of communication.
The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which third-party vendors can write programs that interface easily with other programs. A Web service is designed to have an interface that is depicted in a machine-processable format usually specified in Web Service Description Language (WSDL)
All Web services are APIs but not all APIs are Web services.
A Web service is merely an API wrapped in HTTP.
This here article provides good knowledge regarding web service and API.
You can achieve this with the following snippet:
import java.lang.reflect.ParameterizedType;
public class SomeContainer<E> {
E createContents() throws InstantiationException, IllegalAccessException {
ParameterizedType genericSuperclass = (ParameterizedType)
getClass().getGenericSuperclass();
@SuppressWarnings("unchecked")
Class<E> clazz = (Class<E>)
genericSuperclass.getActualTypeArguments()[0];
return clazz.newInstance();
}
public static void main( String[] args ) throws Throwable {
SomeContainer< Long > scl = new SomeContainer<>();
Long l = scl.createContents();
System.out.println( l );
}
}
Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:
<a href="#" onClick="(function(e){
console.log(e);
alert('Hey i am calling');
return false;
})(arguments[0]);return false;">click here</a>
List<object> list = myArray.Cast<Object>().ToList();
If the type of the array elements is a reference type, you can leave out the .Cast<object>()
since C#4 added interface co-variance i.e. an IEnumerable<SomeClass>
can be treated as an IEnumerable<object>
.
List<object> list = myArray.ToList<object>();
I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).
In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!
As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.
import Tkinter as tk
class Window(tk.Frame):
def __init__(self, master=None, view=None ):
tk.Frame.__init__( self, master )
self.view_ = view
""" Setup window linking it to the view... """
class GuiView( MyViewSuperClass ):
def open( self ):
self.tkRoot_ = tk.Tk()
self.window_ = Window( master=None, view=self )
self.window_.pack()
self.refresh()
self.onOpen()
self.tkRoot_.mainloop()
def onOpen( self ):
""" Do some initial tasks... """
def refresh( self ):
self.tkRoot_.update()
By either escaping those characters with htmlspecialchars
, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.
Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>
.
Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).
I was solving a similar problem on codewars and devised the following solution which worked for me.
This gives the highest count of an integer in an array and also the integer itself. I think it can be applied to string array as well.
To properly sort Strings, remove the function(a, b){return a-b}
from inside the sort()
portion
function mostFrequentItemCount(collection) {
collection.sort(function(a, b){return a-b});
var i=0;
var ans=[];
var int_ans=[];
while(i<collection.length)
{
if(collection[i]===collection[i+1])
{
int_ans.push(collection[i]);
}
else
{
int_ans.push(collection[i]);
ans.push(int_ans);
int_ans=[];
}
i++;
}
var high_count=0;
var high_ans;
i=0;
while(i<ans.length)
{
if(ans[i].length>high_count)
{
high_count=ans[i].length;
high_ans=ans[i][0];
}
i++;
}
return high_ans;
}
you can create a file object of current database path and then delete it as we delete file from folder
File data = Environment.getDataDirectory();
String currentDBPath = "/data/com.example.demo/databases/" + DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
boolean deleted = SQLiteDatabase.deleteDatabase(currentDB);