Programs & Examples On #Spring batch

Spring Batch is a lightweight, comprehensive framework aimed at enabling the development of batch applications vital for the daily operations of enterprise systems. Batch applications in this context refers to automated offline systems targeted towards bulk data processing.

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

I think when importing modules you have imported another package, Go to modules and remove al of them. After that import modules from the package of the project

How does the data-toggle attribute work? (What's its API?)

The data-* attributes is used to store custom data private to the page or application

So Bootstrap uses these attributes for saving states of objects

W3School data-* description

What does value & 0xff do in Java?

It help to reduce lot of codes. It is occasionally used in RGB values which consist of 8bits.

where 0xff means 24(0's ) and 8(1's) like 00000000 00000000 00000000 11111111

It effectively masks the variable so it leaves only the value in the last 8 bits, and ignores all the rest of the bits

It’s seen most in cases like when trying to transform color values from a special format to standard RGB values (which is 8 bits long).

Great Explanation See here

T-SQL CASE Clause: How to specify WHEN NULL

CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END

How to make VS Code to treat other file extensions as certain language?

eg:

// .vscode/settings.json in workspace

{
  "files.associations": {
    "*Container.js": "javascriptreact",
    "**/components/*/*.js": "javascriptreact",
    "**/config/routes.js": "javascriptreact"
  }
}

Pandas KeyError: value not in index

please try this to clean and format your column names:

df.columns = (df.columns.str.strip().str.upper()
              .str.replace(' ', '_')
              .str.replace('(', '')
              .str.replace(')', ''))

How to move the layout up when the soft keyboard is shown android

Make use of Relative layout it will adjust the view so that you can see that view while typing the text

UIImage: Resize, then Crop

I needed the same thing - in my case, to pick the dimension that fits once scaled, and then crop each end to fit the rest to the width. (I'm working in landscape, so might not have noticed any deficiencies in portrait mode.) Here's my code - it's part of a categeory on UIImage. Target size in my code is always set to the full screen size of the device.

@implementation UIImage (Extras)

#pragma mark -
#pragma mark Scale and crop image

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;    
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) 
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor) 
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }   

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

Printing Batch file results to a text file

For showing result of batch file in text file, you can use

this command

chdir > test.txt

This command will redirect result to test.txt.

When you open test.txt you will found current path of directory in test.txt

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Using Java with Nvidia GPUs (CUDA)

First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.

This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.

The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.

You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.

This leads to another classification of problems. Namely whether problems are memory bound or compute bound.

The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.

The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.

As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....

Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.

So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors, ForkJoinPools etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.

However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.


A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.


You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev


However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.

(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )

(Byte)code translation and OpenCL code generation:

https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.

https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.

https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.

https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.

Language extensions

http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.

http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.

https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend

Java OpenCL/CUDA binding libraries

https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes

http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API

http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API

Miscellaneous

http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010

http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained


View the change history of a file using Git versioning

You can use

git log -p filename

to let git generate the patches for each log entry.

See

git help log

for more options - it can actually do a lot of nice things :) To get just the diff for a specific commit you can

git show HEAD 

or any other revision by identifier. Or use

gitk

to browse the changes visually.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Press F4 at the project root and select the the root source pressing the source button. It resolved my problem!

for(; ;){
  makeGoodCode();
}

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

How do I make flex box work in safari?

Giving flex a value solved the problem for me, e.g.

flex: 1 0 auto

React: why child component doesn't update when prop changes

I had the same problem. This is my solution, I'm not sure that is the good practice, tell me if not:

state = {
  value: this.props.value
};

componentDidUpdate(prevProps) {
  if(prevProps.value !== this.props.value) {
    this.setState({value: this.props.value});
  }
}

UPD: Now you can do the same thing using React Hooks: (only if component is a function)

const [value, setValue] = useState(propName);
// This will launch only if propName value has chaged.
useEffect(() => { setValue(propName) }, [propName]);

Iterating through a range of dates in Python

What about the following for doing a range incremented by days:

for d in map( lambda x: startDate+datetime.timedelta(days=x), xrange( (stopDate-startDate).days ) ):
  # Do stuff here
  • startDate and stopDate are datetime.date objects

For a generic version:

for d in map( lambda x: startTime+x*stepTime, xrange( (stopTime-startTime).total_seconds() / stepTime.total_seconds() ) ):
  # Do stuff here
  • startTime and stopTime are datetime.date or datetime.datetime object (both should be the same type)
  • stepTime is a timedelta object

Note that .total_seconds() is only supported after python 2.7 If you are stuck with an earlier version you can write your own function:

def total_seconds( td ):
  return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

Returning JSON from PHP to JavaScript?

There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

If you don't, here's the PECL library you can install.

<?php
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

How can I detect the encoding/codepage of a text file

I've done something similar in Python. Basically, you need lots of sample data from various encodings, which are broken down by a sliding two-byte window and stored in a dictionary (hash), keyed on byte-pairs providing values of lists of encodings.

Given that dictionary (hash), you take your input text and:

  • if it starts with any BOM character ('\xfe\xff' for UTF-16-BE, '\xff\xfe' for UTF-16-LE, '\xef\xbb\xbf' for UTF-8 etc), I treat it as suggested
  • if not, then take a large enough sample of the text, take all byte-pairs of the sample and choose the encoding that is the least common suggested from the dictionary.

If you've also sampled UTF encoded texts that do not start with any BOM, the second step will cover those that slipped from the first step.

So far, it works for me (the sample data and subsequent input data are subtitles in various languages) with diminishing error rates.

Is there a destructor for Java?

In Java, the garbage collector automatically deletes the unused objects to free up the memory. So it’s sensible Java has no destructors available.

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

Updating a java map entry

If key is present table.put(key, val) will just overwrite the value else it'll create a new entry. Poof! and you are done. :)

you can get the value from a map by using key is table.get(key); That's about it

How to make connection to Postgres via Node.js

Here is an example I used to connect node.js to my Postgres database.

The interface in node.js that I used can be found here https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

var client = new pg.Client(conString);
client.connect();

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
    x = x - 1;
}

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row', function(row) {
    console.log(row);
});

query.on('end', function() {
    client.end();
});



//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
    name: 'insert beatle',
    text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
    values: ['George', 70, new Date(1946, 02, 14)]
});

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
    name: 'insert beatle',
    values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);

//can stream row results back 1 at a time
query.on('row', function(row) {
    console.log(row);
    console.log("Beatle name: %s", row.name); //Beatle name: John
    console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});

//fired after last row is emitted
query.on('end', function() {
    client.end();
});

UPDATE:- THE query.on function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function

Android: Bitmaps loaded from gallery are rotated in ImageView

Use the following code to rotate an image correctly:

private Bitmap rotateImage(Bitmap bitmap, String filePath)
{
    Bitmap resultBitmap = bitmap;

    try
    {
        ExifInterface exifInterface = new ExifInterface(filePath);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

        Matrix matrix = new Matrix();

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_90);
        }
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_180);
        }
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_270);
        }

        // Rotate the bitmap
        resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
    catch (Exception exception)
    {
        Logger.d("Could not rotate the image");
    }
    return resultBitmap;
}

C# : changing listbox row color?

How about

      MyLB is a listbox

        Label ll = new Label();
        ll.Width = MyLB.Width;
        ll.Content = ss;
        if(///<some condition>///)
            ll.Background = Brushes.LightGreen;
        else
            ll.Background = Brushes.LightPink;
        MyLB.Items.Add(ll);

How to get key names from JSON using jq

To get the keys on a deeper node in an JSON:

echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"

java.net.UnknownHostException: Invalid hostname for server: local

Connect your mobile with different wifi connection with different service provider. I don't know the exact issue but i could not connect to server with a specific service provider but it work when i connected to other service provider. So try it!

Get selected row item in DataGrid WPF

This is pretty simple in this DataGrid dg and item class is populated in datagrid and listblock1 is a basic frame.

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            var row_list = (Item)dg.SelectedItem;
            listblock1.Content = "You Selected: " + row_list.FirstName + " " + row_list.LastName;
        }
        catch { }

    }
    public class Item
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

Why does ++[[]][+[]]+[+[]] return the string "10"?

The following is adapted from a blog post answering this question that I posted while this question was still closed. Links are to (an HTML copy of) the ECMAScript 3 spec, still the baseline for JavaScript in today's commonly used web browsers.

First, a comment: this kind of expression is never going to show up in any (sane) production environment and is only of any use as an exercise in just how well the reader knows the dirty edges of JavaScript. The general principle that JavaScript operators implicitly convert between types is useful, as are some of the common conversions, but much of the detail in this case is not.

The expression ++[[]][+[]]+[+[]] may initially look rather imposing and obscure, but is actually relatively easy break down into separate expressions. Below I’ve simply added parentheses for clarity; I can assure you they change nothing, but if you want to verify that then feel free to read up about the grouping operator. So, the expression can be more clearly written as

( ++[[]][+[]] ) + ( [+[]] )

Breaking this down, we can simplify by observing that +[] evaluates to 0. To satisfy yourself why this is true, check out the unary + operator and follow the slightly tortuous trail which ends up with ToPrimitive converting the empty array into an empty string, which is then finally converted to 0 by ToNumber. We can now substitute 0 for each instance of +[]:

( ++[[]][0] ) + [0]

Simpler already. As for ++[[]][0], that’s a combination of the prefix increment operator (++), an array literal defining an array with single element that is itself an empty array ([[]]) and a property accessor ([0]) called on the array defined by the array literal.

So, we can simplify [[]][0] to just [] and we have ++[], right? In fact, this is not the case because evaluating ++[] throws an error, which may initially seem confusing. However, a little thought about the nature of ++ makes this clear: it’s used to increment a variable (e.g. ++i) or an object property (e.g. ++obj.count). Not only does it evaluate to a value, it also stores that value somewhere. In the case of ++[], it has nowhere to put the new value (whatever it may be) because there is no reference to an object property or variable to update. In spec terms, this is covered by the internal PutValue operation, which is called by the prefix increment operator.

So then, what does ++[[]][0] do? Well, by similar logic as +[], the inner array is converted to 0 and this value is incremented by 1 to give us a final value of 1. The value of property 0 in the outer array is updated to 1 and the whole expression evaluates to 1.

This leaves us with

1 + [0]

... which is a simple use of the addition operator. Both operands are first converted to primitives and if either primitive value is a string, string concatenation is performed, otherwise numeric addition is performed. [0] converts to "0", so string concatenation is used, producing "10".

As a final aside, something that may not be immediately apparent is that overriding either one of the toString() or valueOf() methods of Array.prototype will change the result of the expression, because both are checked and used if present when converting an object into a primitive value. For example, the following

Array.prototype.toString = function() {
  return "foo";
};
++[[]][+[]]+[+[]]

... produces "NaNfoo". Why this happens is left as an exercise for the reader...

Access to the path is denied

Make sure you that your target in System.IO.Delete(string file) is a file which is existed. Maybe there is a mistake in your code ;Like you don't pass the correct file name to the method , or your target is a folder. In these cases you'll see the : "access to the path is denied error".

Laravel 5.1 API Enable Cors

just use this as a middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');

        return $response;
    }
}

and register the middleware in your kernel file on this path app/Http/Kernel.php in which group that you prefer and everything will be fine

IF statement: how to leave cell blank if condition is false ("" does not work)

To Validate data in column A for Blanks

Step 1: Step 1: B1=isblank(A1)

Step 2: Drag the formula for the entire column say B1:B100; This returns Ture or False from B1 to B100 depending on the data in column A

Step 3: CTRL+A (Selct all), CTRL+C (Copy All) , CRTL+V (Paste all as values)

Step4: Ctrl+F ; Find and replace function Find "False", Replace "leave this blank field" ; Find and Replace ALL

There you go Dude!

How to set image to UIImage

UIImage *img = [UIImage imageNamed@"aImageName"];

When is a CDATA section necessary within a script tag?

It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.

XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.

With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.

Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned).

You can learn more about CDATA here, and more about XHTML here.

What is a serialVersionUID and why should I use it?

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.

Specifying one gives more control, though JVM does generate one if you don't specify. The value generated can differ between different compilers. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects [backward incompatibility], and in this case you just have to change the serialVersionUID.

The javadocs for Serializable say:

the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Therefore, you must declare serialVersionUID because it give us more control.

This article has some good points on the topic.

Check play state of AVPlayer

For Swift:

AVPlayer:

let player = AVPlayer(URL: NSURL(string: "http://www.sample.com/movie.mov"))
if (player.rate != 0 && player.error == nil) {
   println("playing")
}

Update:
player.rate > 0 condition changed to player.rate != 0 because if video is playing in reverse it can be negative thanks to Julian for pointing out.
Note: This might look same as above(Maz's) answer but in Swift '!player.error' was giving me a compiler error so you have to check for error using 'player.error == nil' in Swift.(because error property is not of 'Bool' type)

AVAudioPlayer:

if let theAudioPlayer =  appDelegate.audioPlayer {
   if (theAudioPlayer.playing) {
       // playing
   }
}

AVQueuePlayer:

if let theAudioQueuePlayer =  appDelegate.audioPlayerQueue {
   if (theAudioQueuePlayer.rate != 0 && theAudioQueuePlayer.error == nil) {
       // playing
   }
}

Count immediate child div elements using jQuery

$("#foo > div").length

Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.

Bootstrap row class contains margin-left and margin-right which creates problems

Old topic, but I was recently affected by this.

Using a class "row-fluid" instead of "row" worked fine for me but I'm not sure if it's fully supported going forward.

So after reading Why does the bootstrap .row has a default margin-left of -30px I just used the <div> (without any row class) and it behaved exactly like <div class="row-fluid">

How to trigger a click on a link using jQuery

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.

<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>

Jquery:

$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works

This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:

document.getElementById('test1').click(); // Works!

Or by accessing the jQuery object as an array

$('#test1')[0].click(); // Works too!!!

How to add leading zeros?

Here's a generalizable base R function:

pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){

    unlist(lapply(x, function(x) {
        paste0(
            paste(rep(char, len - nchar(x)), collapse = ''),
            x
        )
    }))
}

pad_left(1:100)

I like sprintf but it comes with caveats like:

however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

How to convert QString to int?

You can use:

QString str = "10";
int n = str.toInt();

Output:

n = 10

'Property does not exist on type 'never'

Because you are assigning instance to null. The compiler infers that it can never be anything other than null. So it assumes that the else block should never be executed so instance is typed as never in the else block.

Now if you don't declare it as the literal value null, and get it by any other means (ex: let instance: Foo | null = getFoo();), you will see that instance will be null inside the if block and Foo inside the else block.

Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never

Edit:

The issue in the updated example is actually an open issue with the compiler. See:

https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176

how to do bitwise exclusive or of two strings in python?

def xor_strings(s1, s2):
    max_len = max(len(s1), len(s2))
    s1 += chr(0) * (max_len - len(s1))
    s2 += chr(0) * (max_len - len(s2))
    return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(s1, s2)])

Dart SDK is not configured

Perhaps you can try to sync up the dependencies by executing 'flutter pub get' in terminal.

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

Remote debugging Tomcat with Eclipse

Just run ./catalina.sh jpda start (forks) or ./catalina.sh jpda run (does not fork, not mentioned in help). All options mentioned here default to sane values.

Bitwise and in place of modulus operator

Using bitwise_and, bitwise_or, and bitwise_not you can modify any bit configurations to another bit configurations (i.e. these set of operators are "functionally complete"). However, for operations like modulus, the general formula would be necessarily be quite complicated, I wouldn't even bother trying to recreate it.

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

How to convert an image to base64 encoding?

<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

I was trying to use this resource but kept getting an error, I found the code above worked perfectly.

Just replaced IMAGE URL HERE with the URL of your image - http://www.website.com/image.jpg

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

How to setup Main class in manifest file in jar produced by NetBeans project

It looks like you are running into a bug in the way NetBeans 6.8 creates the jar for a Java Library Project.

The issue implies that there is a work-around.

I have not been able to verify that with NB 6.8 and/or NetBeans 6.9-dev...

You may want to register with the NetBeans.org website/issue tracker and update the issue and add your 'vote'.

Position: absolute and parent height?

You can do that with a grid:

article {
    display: grid;
}

.one {
    grid-area: 1 / 1 / 2 / 2;
}

.two {
    grid-area: 1 / 1 / 2 / 2;
}

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

How to plot two columns of a pandas data frame using points?

For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:

import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.

and remember that you can access a NumPy array of the column's values with df.col_name_1.values for example.

I ran into trouble using this with Pandas default plotting in the case of a column of Timestamp values with millisecond precision. In trying to convert the objects to datetime64 type, I also discovered a nasty issue: < Pandas gives incorrect result when asking if Timestamp column values have attr astype >.

How is CountDownLatch used in Java Multithreading?

package practice;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch c= new CountDownLatch(3);  // need to decrements the count (3) to zero by calling countDown() method so that main thread will wake up after calling await() method 
        Task t = new Task(c);
        Task t1 = new Task(c);
        Task t2 = new Task(c);
        t.start();
        t1.start();
        t2.start();
        c.await(); // when count becomes zero main thread will wake up 
        System.out.println("This will print after count down latch count become zero");
    }
}

class Task extends Thread{
    CountDownLatch c;

    public Task(CountDownLatch c) {
        this.c = c;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
            c.countDown();   // each thread decrement the count by one 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Bootstrap 3.0 Popovers and tooltips

For some reason the only way I was able to get my code to work is by switching couple of things. If nothing worked for you so far, please give a whirl to this:

$('body').popover({ 
    selector: '[data-toggle="popover"]', 
    trigger: 'hover',
    placement: 'right'
});

What does "wrong number of arguments (1 for 0)" mean in Ruby?

You passed an argument to a function which didn't take any. For example:

def takes_no_arguments
end

takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)

How to use JavaScript regex over multiple lines?

[.\n] does not work because . has no special meaning inside of [], it just means a literal .. (.|\n) would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r as well to include Windows and classic Mac OS style line endings: (.|[\r\n]).

That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S], which will match everything, and is faster and simpler.

In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.

Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre") with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

Stop form refreshing page on submit

I hope this will be the last answer


_x000D_
_x000D_
$('#the_form').submit(function(e){_x000D_
  e.preventDefault()_x000D_
  alert($(this).serialize())_x000D_
  // var values = $(this).serialize()_x000D_
  // logic...._x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form id="the_form">_x000D_
   Label-A <input type="text" name='a'required><br>_x000D_
   Label-B <input type="text" name="b" required><br>_x000D_
   Label-C <input type="password" name="c" required><br>_x000D_
   Label-D <input type="number" name="d" required><br>_x000D_
   <input type="submit" value="Save without refresh">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Maven Could not resolve dependencies, artifacts could not be resolved

My EAR project had 2 modules *.ear and *.war and I got this dependency error on *.war project when trying mvn eclipse:eclipse. Resolved it by fixing utf-8 encoding issue in the *.war project. mvn -X or -e options weren't of help here.

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

How to get the nvidia driver version from the command line?

Using nvidia-smi should tell you that:

bwood@mybox:~$ nvidia-smi 
Mon Oct 29 12:30:02 2012       
+------------------------------------------------------+                       
| NVIDIA-SMI 3.295.41   Driver Version: 295.41         |                       
|-------------------------------+----------------------+----------------------+
| Nb.  Name                     | Bus Id        Disp.  | Volatile ECC SB / DB |
| Fan   Temp   Power Usage /Cap | Memory Usage         | GPU Util. Compute M. |
|===============================+======================+======================|
| 0.  GeForce GTX 580           | 0000:25:00.0  N/A    |       N/A        N/A |
|  54%   70 C  N/A   N/A /  N/A |  25%  383MB / 1535MB |  N/A      Default    |
|-------------------------------+----------------------+----------------------|
| Compute processes:                                               GPU Memory |
|  GPU  PID     Process name                                       Usage      |
|=============================================================================|
|  0.           Not Supported                                                 |
+-----------------------------------------------------------------------------+

IIS Express Windows Authentication

This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx (even though there is no such file on your site).

Add the following two lines to the appSettingssection of your site's Web.config.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'

simply separate the casting of date and time

cmd line rename file with date and time

ls | xargs -I % mv % %_`date +%d%b%Y`

One line is enough. ls all files/dirs under current dir and append date to each file.

How do I make the text box bigger in HTML/CSS?

.textbox {
    height: 40px;
}

<div id=signin>  
    <input type="text" class="textbox" size="25%" height="50"/></br>
<input type="text" class="textbox" size="25%" height="50"/>

Make the font size larger and add height (or line height to the input boxes) I would not recommend adding those size and height attributes in the HTML as that can be handled by CSS. I have made a class text-box that can be used for multiple input boxes

What is w3wp.exe?

  • A worker process runs as an executables file named W3wp.exe
  • A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.

  • The worker process is controlled by the www service.

  • worker processes also run application code, Such as ASP .NET applications and XML web Services.

  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.

  • When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.htmlenter image description here

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Django - after login, redirect user to his custom page --> mysite.com/username

You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in

This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.

Random alpha-numeric string in JavaScript?

var randomString = function(length) {
  var str = '';
  var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
      '');
  var charsLen = chars.length;
  if (!length) {
    length = ~~(Math.random() * charsLen);
  }
  for (var i = 0; i < length; i++) {
    str += chars[~~(Math.random() * charsLen)];
  }
  return str;
};

Activating Anaconda Environment in VsCode

Simply use

  1. shift + cmd + P
  2. Search Select Interpreter

pyhton : Select Interpreter

  1. Select it and it will show you the list of your virtual environment created via conda and other python versions

Activating conda virtual environment

  1. select the environment and you are ready to go.

Quoting the 'Select and activate an environment' docs

Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.

sqlalchemy: how to join several tables by one query?

As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...

If you're interested in writing a query along the lines of:

SELECT
    user.email,
    user.name,
    document.name,
    documents_permissions.readAllowed,
    documents_permissions.writeAllowed
FROM
    user, document, documents_permissions
WHERE
    user.email = "[email protected]";

Then you should go for something like:

session.query(
    User, 
    Document, 
    DocumentsPermissions
).filter(
    User.email == Document.author
).filter(
    Document.name == DocumentsPermissions.document
).filter(
    User.email == "[email protected]"
).all()

If instead, you want to do something like:

SELECT 'all the columns'
FROM user
JOIN document ON document.author_id = user.id AND document.author == User.email
JOIN document_permissions ON document_permissions.document_id = document.id AND document_permissions.document = document.name

Then you should do something along the lines of:

session.query(
    User
).join(
    Document
).join(
    DocumentsPermissions
).filter(
    User.email == "[email protected]"
).all()

One note about that...

query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses)                    # specify relationship from left to right
query.join(Address, User.addresses)           # same, with explicit target
query.join('addresses')                       # same, using a string

For more information, visit the docs.

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

You can use vim programmatically with the option -c {command} :

Dos to Unix:

vim file.txt -c "set ff=unix" -c ":wq"

Unix to dos:

vim file.txt -c "set ff=dos" -c ":wq"

"set ff=unix/dos" means change fileformat (ff) of the file to Unix/DOS end of line format

":wq" means write file to disk and quit the editor (allowing to use the command in a loop)

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you use Python 3.6 (possibly 3.5 or later), it doesn't give that error to me anymore. I had a similar issue, because I was using v3.4, but it went away after I uninstalled and reinstalled.

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

Use '=' or LIKE to compare strings in SQL?

For pattern matching use LIKE. For exact match =.

how to use jQuery ajax calls with node.js

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);

and client side JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.

enter image description here

CKEditor automatically strips classes from div

Please refer to the official Advanced Content Filter guide and plugin integration tutorial.

You'll find much more than this about this powerful feature. Also see config.extraAllowedContent that seems suitable for your needs.

Check if String / Record exists in DataTable

Use the Find method if item_manuf_id is a primary key:

var result = dtPs.Rows.Find("some value");

If you only want to know if the value is in there then use the Contains method.

if (dtPs.Rows.Contains("some value"))
{
  ...
}

Primary key restriction applies to Contains aswell.

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

How to select the first row for each group in MySQL?

Best performance and easy to use:

SELECT id, code,
SUBSTRING_INDEX( GROUP_CONCAT(price ORDER BY id DESC), ',', 1) first_found_price
FROM stocks
GROUP BY code
ORDER BY id DESC

Disable browser's back button

Even I faced the same situation before...and didn't have any help. try these things maybe these will work for you

in login page <head> tag:

<script type="text/javascript">
    window.history.forward();
</script>

in Logout Button I did this:

protected void Btn_Logout_Click(object sender, EventArgs e)      
{
    connObj.Close();
    Session.Abandon();
    Session.RemoveAll();
    Session.Clear();
    HttpContext.Current.Session.Abandon();
}

and on login page I have put the focus on Username textbox like this:

protected void Page_Load(object sender, EventArgs e)
{
    _txtUsername.Focus();
}

hope this helps... :) someone plz teach me how to edit this page...

Can an ASP.NET MVC controller return an Image?

I see two options:

1) Implement your own IViewEngine and set the ViewEngine property of the Controller you are using to your ImageViewEngine in your desired "image" method.

2) Use a view :-). Just change the content type etc.

Hive: Filtering Data between Specified Dates when Date is a String

Just like SQL, Hive supports BETWEEN operator for more concise statement:

SELECT *
  FROM your_table
  WHERE your_date_column BETWEEN '2010-09-01' AND '2013-08-31';

pandas python how to count the number of records or rows in a dataframe

Simply, row_num = df.shape[0] # gives number of rows, here's the example:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

How do I make an image smaller with CSS?

Here's what I've done:

.resize {
    width: 400px;
    height: auto;
}

.resize {
    width: 300px;
    height: auto;
}

<img class="resize" src="example.jpg"/>

This will keep the image aspect ratio the same.

What is the use of printStackTrace() method in Java?

printStackTrace() prints the locations where the exception occurred in the source code, thus allowing the author who wrote the program to see what went wrong. But since it shows problems in the source code, the user(s) who may or may not have any coding experience may not be able to understand what went wrong, so if the program allows the user to send error messages to the authors, the users may not be able to give good data on what went wrong.

You should consider the Logger.getLogger() method, it offers a better exception handling (logging) facility, and besides printStackTrace() without arguments is considered to be obsolete and should ONLY be used for debugging purposes, not for user display.

ComboBox- SelectionChanged event has old value, not new value

Following event is fired for any change of the text in the ComboBox (when the selected index is changed and when the text is changed by editing too).

<ComboBox IsEditable="True" TextBoxBase.TextChanged="cbx_TextChanged" />

Create hive table using "as select" or "like" and also specify delimiter

Let's say we have an external table called employee

hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
  id string,
  fname string,
  lname string, 
  salary double)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'colelction.delim'=':',
  'field.delim'=',',
  'line.delim'='\n',
  'serialization.format'=',')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='false',
  'numFiles'='0',
  'numRows'='-1',
  'rawDataSize'='-1',
  'totalSize'='0',
  'transient_lastDdlTime'='1487884795')
  1. To create a person table like employee

    CREATE TABLE person LIKE employee;

  2. To create a person external table like employee

    CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';

  3. then use DESC person; to see the newly created table schema.

Confirm deletion using Bootstrap 3 modal box

$('.launchConfirm').on('click', function (e) {
    $('#confirm')
        .modal({ backdrop: 'static', keyboard: false })
        .one('click', '#delete', function (e) {
            //delete function
        });
});

FIDDLE

For your button:

<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>

How to get number of rows inserted by a transaction

You can use @@trancount in MSSQL

From the documentation:

Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Define a fixed-size list in Java

The public java.util.List subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List specification.
You could find it only in Queue subclasses (for example ArrayBlockingQueue, a bounded blocking queue backed by an array for example) that handle very specific requirements.

In Java, with a List type, you could implement it according to two scenarios :

1) The fixed list size is always both the actual and the maximum size.

It sounds as an array definition. So Arrays.asList() that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.

For example :

Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception

It works also with a collection as input while first we convert it into an array :

Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList(foosInput.stream().toArray(Foo[]::new)); // Java 8 way

2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.

You could use inheritance (extends ArrayList) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.

With Guava Forwarding classes you could do :

import com.google.common.collect.ForwardingList;

public class FixedSizeList<T> extends ForwardingList<T> {

  private final List<T> delegate;
  private final int maxSize;

  public FixedSizeList(List<T> delegate, int maxSize) {
    this.delegate = delegate;
    this.maxSize = maxSize;
  }

  @Override protected List<T> delegate() {
    return delegate;
  }

  @Override public boolean add(T element) {
    assertMaxSizeNotReached(1);
    return super.add(element);
  }

  @Override public void add(int index, T element) {
    assertMaxSizeNotReached(1);
    super.add(index, element);
  }

  @Override public boolean addAll(Collection<? extends T> collection) {
    assertMaxSizeNotReached(collection.size());
    return super.addAll(collection);
  }

  @Override public boolean addAll(int index, Collection<? extends T> elements) {
    assertMaxSizeNotReached(elements.size());
    return super.addAll(index, elements);
  }    

  private void assertMaxSizeNotReached(int size) {
    if (delegate.size() + size >= maxSize) {
      throw new RuntimeException("size max reached");
    }
  }

}

And use it :

List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3); 
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4");  // throws an Exception

Note that with composition, you could use it with any List implementation :

List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3); 
//...

Which is not possible with inheritance.

jQuery select element in parent window

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}

Absolute positioning ignoring padding of parent

1.) you cannot use big border on parent -- in case you want to have a specific border

2.) you cannot add margin -- in case your parent is a part of some other container and you want your parent to take the full width of that grand parent.

The Only Solution that should be applicable is to wrap your children's in an another container so that your parent becomes the grandparent and then apply padding to the new children's Wrapper / Parent. Or you can directly apply padding to the children.

In your case:

.css-sux{
  padding: 0px 10px 10px 10px;
}

Jetty: HTTP ERROR: 503/ Service Unavailable

Actually, I solved the problem. I run it by eclipse jetty plugin.

  1. I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.

  2. I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Get month name from number

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

Returns: December

Some more info on the Python doc website


[EDIT : great comment from @GiriB] You can also use %b which returns the short notation for month name.

mydate.strftime("%b")

For the example above, it would return Dec.

Remove all git files from a directory?

You can use git-archive, for example:

git archive master | bzip2 > project.tar.bz2

Where master is the desired branch.

jQuery ajax success error

You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

Add json_encdoe in validate.php in last

mail($to, $subject, $message, $headers); 
echo json_encode(array('success'=>'true'));

JS Code

success: function(data){ 
     if(data.success == true){ 
       alert('success'); 
    } 

Hope it works

how to sort an ArrayList in ascending order using Collections and Comparator

Sort By Value

  public Map sortByValue(Map map, final boolean ascending) {
            Map result = new LinkedHashMap();
            try {
                List list = new LinkedList(map.entrySet());

                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object object1, Object object2) {
                        if (ascending)
                            return ((Comparable) ((Map.Entry) (object1)).getValue())
                                    .compareTo(((Map.Entry) (object2)).getValue());
                        else
                            return ((Comparable) ((Map.Entry) (object2)).getValue())
                                    .compareTo(((Map.Entry) (object1)).getValue());

                    }
                });

                for (Iterator it = list.iterator(); it.hasNext();) {
                    Map.Entry entry = (Map.Entry) it.next();
                    result.put(entry.getKey(), entry.getValue());
                }

            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            return result;
        }

String comparison in bash. [[: not found

I had this problem when installing Heroku Toolbelt

This is how I solved the problem

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 ago 15  2012 /bin/sh -> dash

As you can see, /bin/sh is a link to "dash" (not bash), and [[ is bash syntactic sugarness. So I just replaced the link to /bin/bash. Careful using rm like this in your system!

$ sudo rm /bin/sh
$ sudo ln -s /bin/bash /bin/sh

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

Embedding VLC plugin on HTML page

I found this:

<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2"  width="100%"        
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>

I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...

and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object

Another thing to check is that the address for the video file is correct....

Check if argparse optional argument is set or not

Here is my solution to see if I am using an argparse variable

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False) 
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something

This might give more insight to the above answer which I used and adapted to work for my program.

What's the difference between JPA and Hibernate?

JPA is just a specification which needs concrete implementation. The default implementation oracle provide is "Eclipselink" now. (Toplink is donated by Oracle to Eclipse foundation to merge with eclipselink)

(Reference : http://www.oracle.com/technetwork/middleware/toplink/index-085257.html http://www.eclipse.org/org/press-release/20080317_Eclipselink.php )

Using Eclipselink, one can be sure that the code is portable to any implementation if need arises. Hibernate is also a full JPA implementation + MORE ( Sort of JPA Plus). Hibernate is super set of JPA with some extra Hibernate specific functionality. So app developed in Hibernate may not be compatible when switched to other implementation. Still hibernate is choice of majority of developers as JPA implementation and widely used.

Another JPA implementation is OpenJPA (openjpa.apache.org) which is an extension of Kodo implementation.

How to set variable from a SQL query?

Use TOP 1 if the query returns multiple rows.

SELECT TOP 1 @ModelID = m.modelid 
  FROM MODELS m
 WHERE m.areaid = 'South Coast'

Assign a synthesizable initial value to a reg in Verilog

When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.

This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.

always @(posedge clk) begin
    if (reset == 1) begin // For an active high reset
        data_reg = 8'b10101011;
    end else begin
        data_reg = next_data_reg;
    end
end

Apache and IIS side by side (both listening to port 80) on windows2003

I see this is quite an old post, but came across this looking for an answer for this problem. After reading some of the answers they seem very long winded, so after about 5 mins I managed to solve the problem very simply as follows:

httpd.conf for Apache leave the listen port as 80 and 'Server Name' as FQDN/IP :80.

Now for IIS go to Administrative Services > IIS Manager > 'Sites' in the Left hand nav drop down > in the right window select the top line (default web site) then bindings on the right.

Now select http > edit and change to 81 and enter your local IP for the server/pc and in domain enter either your FQDN (www.domain.com) or external IP close.

Restart both servers ensure your ports are open on both router and firewall, done.

This sounds long winded but literally took 5 mins of playing about. works perfectly.

System: Windows 8, IIS 8, Apache 2.2

What does localhost:8080 mean?

http: //localhost:8080/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • 8080 ( port ) is the address of the port on which the host server is listening for requests.

http ://localhost/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • host server listening to default port 80.

HashSet vs. List performance

It depends. If the exact answer really matters, do some profiling and find out. If you're sure you'll never have more than a certain number of elements in the set, go with a List. If the number is unbounded, use a HashSet.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

Why does javascript map function return undefined?

Since ES6 filter supports pointy arrow notation (like LINQ):

So it can be boiled down to following one-liner.

['a','b',1].filter(item => typeof item ==='string');

Codeigniter $this->input->post() empty while $_POST is working correctly

Finally got the issue resolved today. The issue was with the .htaccess file.

Learning to myself: MUST READ THE CODEIGNITER DOCUMENTATION more thoroughly.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Not really. This is normally done using javascript.

there is a good discussion of ways of doing this here...

Autosizing textarea using Prototype

What does the following Oracle error mean: invalid column index

I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How do I set up Eclipse/EGit with GitHub?

Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:

http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial

You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.

Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.

Python regex findall

Try this :

   for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject):
        # match start: match.start()
        # match end (exclusive): match.end()
        # matched text: match.group()

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

How to convert answer into two decimal point

Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.

        Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal

            ' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
            If Input < 0 Then Input = 0
            if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
            Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.

        End Function

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

How to jump to a particular line in a huge text file?

If you're dealing with a text file & based on linux system, you could use the linux commands.
For me, this worked well!

import commands

def read_line(path, line=1):
    return commands.getoutput('head -%s %s | tail -1' % (line, path))

line_to_jump = 141978
read_line("path_to_large_text_file", line_to_jump)

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

How do I push a new local branch to a remote Git repository and track it too?

edit Outdated, just use git push -u origin $BRANCHNAME


Use git publish-branch from William's miscellaneous Git tools.

OK, no Ruby, so - ignoring the safeguards! - take the last three lines of the script and create a bash script, git-publish-branch:

#!/bin/bash
REMOTE=$1 # Rewrite this to make it optional...
BRANCH=$2
# Uncomment the following line to create BRANCH locally first
#git checkout -b ${BRANCH}
git push ${ORIGIN} ${BRANCH}:refs/heads/${BRANCH} &&
git config branch.${BRANCH}.remote ${REMOTE} &&
git config branch.${BRANCH}.merge refs/heads/${BRANCH}

Then run git-publish-branch REMOTENAME BRANCHNAME, where REMOTENAME is usually origin (you may modify the script to take origin as default, etc...)

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

How to refresh a Page using react-route Link

If you just put '/' in the href it will reload the current window.

_x000D_
_x000D_
<a href="/">
  Reload the page
</a>
_x000D_
_x000D_
_x000D_

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Here's a way to pass a dynamic object to a view (or partial view)

Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -

    namespace System
    {
        public static class ExpandoHelper
        {
            public static ExpandoObject ToExpando(this object anonymousObject)
            {
                IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
                IDictionary<string, object> expando = new ExpandoObject();
                foreach (var item in anonymousDictionary)
                    expando.Add(item);
                return (ExpandoObject)expando;
            }

        }
    }

When you send the model to the view, convert it to Expando :

    return View(new {x=4, y=6}.ToExpando());

Cheers

SVN undo delete before commit

To make it into a one liner you can try something like:

svn status | cut -d ' ' -f 8 | xargs svn revert

How do I check if string contains substring?

Like this:

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or:

if (/yes/i.test(str))

How do I tell a Python script to use a particular version

I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

C compiling - "undefined reference to"?

seems you need to link with the obj file that implements tolayer5()

Update: your function declaration doesn't match the implementation:

      void tolayer5(int AorB, struct msg msgReceived)
      void tolayer5(int, char data[])

So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

Iterate over values of object

No, there's no direct method to do that with objects.

The Map type does have a values() method that returns an iterator for the values

How to calculate moving average without keeping the count and data-total?

You can simply do:

double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;
}

Where N is the number of samples where you want to average over. Note that this approximation is equivalent to an exponential moving average. See: Calculate rolling / moving average in C++

Where will log4net create this log file?

FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
    logger.DebugFormat("log file located at : {0}", appender.File);
else
    logger.Error("Could not locate fileAppender");

How to create a list of objects?

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

class myClass():
    myInstances = []
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02
        self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
    thisStep += 1
    if "myClass object at" in thisLocalsLine:
        print(thisLocalsLine)
        print(myLocals[(thisStep - 2)])
        #myInstances.append(myLocals[(thisStep - 2)])
        print(myInstances)
        myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Another more 'clever' hack:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myInstances = []
myClasses = {
    "myObj01": ["Foo", "Bar"],
    "myObj02": ["FooBar",  "Baz"]
    }

for thisClass in myClasses.keys():
    exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
    myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Getting the location from an IP address

PHP has an extension for that.

From PHP.net:

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.

For example:

$record = geoip_record_by_name($ip);
echo $record['city'];

C++ getters/setters coding style

I think the C++11 approach would be more like this now.

#include <string>
#include <iostream>
#include <functional>

template<typename T>
class LambdaSetter {
public:
    LambdaSetter() :
        getter([&]() -> T { return m_value; }),
        setter([&](T value) { m_value = value; }),
        m_value()
    {}

    T operator()() { return getter(); }
    void operator()(T value) { setter(value); }

    LambdaSetter operator=(T rhs)
    {
        setter(rhs);
        return *this;
    }

    T operator=(LambdaSetter rhs)
    {
        return rhs.getter();
    }

    operator T()
    { 
        return getter();
    }


    void SetGetter(std::function<T()> func) { getter = func; }
    void SetSetter(std::function<void(T)> func) { setter = func; }

    T& GetRawData() { return m_value; }

private:
    T m_value;
    std::function<const T()> getter;
    std::function<void(T)> setter;

    template <typename TT>
    friend std::ostream & operator<<(std::ostream &os, const LambdaSetter<TT>& p);

    template <typename TT>
    friend std::istream & operator>>(std::istream &is, const LambdaSetter<TT>& p);
};

template <typename T>
std::ostream & operator<<(std::ostream &os, const LambdaSetter<T>& p)
{
    os << p.getter();
    return os;
}

template <typename TT>
std::istream & operator>>(std::istream &is, const LambdaSetter<TT>& p)
{
    TT value;
    is >> value;
    p.setter(value);
    return is;
}


class foo {
public:
    foo()
    {
        myString.SetGetter([&]() -> std::string { 
            myString.GetRawData() = "Hello";
            return myString.GetRawData();
        });
        myString2.SetSetter([&](std::string value) -> void { 
            myString2.GetRawData() = (value + "!"); 
        });
    }


    LambdaSetter<std::string> myString;
    LambdaSetter<std::string> myString2;
};

int _tmain(int argc, _TCHAR* argv[])
{
    foo f;
    std::string hi = f.myString;

    f.myString2 = "world";

    std::cout << hi << " " << f.myString2 << std::endl;

    std::cin >> f.myString2;

    std::cout << hi << " " << f.myString2 << std::endl;

    return 0;
}

I tested this in Visual Studio 2013. Unfortunately in order to use the underlying storage inside the LambdaSetter I needed to provide a "GetRawData" public accessor which can lead to broken encapsulation, but you can either leave it out and provide your own storage container for T or just ensure that the only time you use "GetRawData" is when you are writing a custom getter/setter method.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

Go through this and remove corresponding cache files in selected db then after you can drop your database

First find Your MySQL Data Directory Containing Your selected DB

Linux

  • Open up MySQL's configuration file: less /etc/my.cnf
  • Search for the term "datadir": /datadir

  • If it exists, it will highlight a line that reads: datadir = [path]

  • You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.

  • If that line does not exist, then MySQL will default to: /var/lib/mysql.

Windows 1. Open up MySQL's configuration file into Notepad: my.ini

The my.ini will be located in the MySQL program folder, which would be wherever it got installed. If you did not install MySQL, then use the Windows "search" feature to look for my.ini. You could also manually search for it by browsing to [drive]:\Program Files\MySQL\MySQL Server 5.5.

  1. Do a search in Notepad to find the term "datadir".

  2. If it exists, it will highlight a line that reads: datadir = [path]

  3. You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.

  4. If that line does not exist, then you'll probably find it under [drive]:\ProgramData\MySQL\MySQL Server 5.5\data.

NOTE: The "ProgramData" folder may be hidden. You may have to type the explicit path into Windows Explore

Complex JSON nesting of objects and arrays

First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example

Json is very compact, but no human being can read it easily, very hard do debug,

Xml is very large, but everyone can easily read/debug it,

Yaml is in between Xml and json.

But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.

Hope this helps.

How to send password using sftp batch file

You'll want to install the sshpass program. Then:

sshpass -p YOUR_PASSWORD sftp -oBatchMode=no -b YOUR_COMMAND_FILE_PATH USER@HOST

Obviously, it's better to setup public key authentication. Only use this if that's impossible to do, for whatever reason.

Callback functions in Java

Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:

http://code.google.com/p/lambdaj/wiki/Closures

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement

Attached file may help you.

How can I delete one element from an array by value

I improved Niels's solution

class Array          
  def except(*values)
    self - values
  end    
end

Now you can use

[1, 2, 3, 4].except(3, 4) # return [1, 2]
[1, 2, 3, 4].except(4)    # return [1, 2, 3]

How can I find WPF controls by name or type?

You can also find an element by name using FrameworkElement.FindName(string).

Given:

<UserControl ...>
    <TextBlock x:Name="myTextBlock" />
</UserControl>

In the code-behind file, you could write:

var myTextBlock = (TextBlock)this.FindName("myTextBlock");

Of course, because it's defined using x:Name, you could just reference the generated field, but perhaps you want to look it up dynamically rather than statically.

This approach is also available for templates, in which the named item appears multiple times (once per usage of the template).

How to order events bound with jQuery

JQuery 1.5 introduces promises, and here's the simplest implementation I've seen to control order of execution. Full documentation at http://api.jquery.com/jquery.when/

$.when( $('#myDiv').css('background-color', 'red') )
 .then( alert('hi!') )
 .then( myClickFunction( $('#myID') ) )
 .then( myThingToRunAfterClick() );

Could not resolve '...' from state ''

I had a case where the error was thrown by a

$state.go('');

Which is obvious. I guess this can help someone in future.

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

What's the main difference between int.Parse() and Convert.ToInt32

The difference is this:

Int32.Parse() and Int32.TryParse() can only convert strings. Convert.ToInt32() can take any class that implements IConvertible. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse() is probably the better option.

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

Text to speech(TTS)-Android

    package com.example.text_to_speech;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Toast;

import com.example.fyp.R;

import java.util.Locale;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class textTospeech_class extends AppCompatActivity {
    TextToSpeech textToSpeech;
    String text;
    int result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_tospeech);
        textToSpeech = new TextToSpeech(textTospeech_class.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if (i == TextToSpeech.SUCCESS) {
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                } else {
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    public void tts(View view)
    {
        switch (view.getId()) {
            case R.id.speechid:
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();

                } else {
                    textToSpeech.speak("a for apple", TextToSpeech.QUEUE_FLUSH, null);
                }
                break;
            case R.id.bid:
            {
                if(result==TextToSpeech.LANG_MISSING_DATA || result== TextToSpeech.LANG_NOT_SUPPORTED)
                {
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();

                }
                else
                {
                    textToSpeech.speak("b for ball",TextToSpeech.QUEUE_FLUSH,null);
                }
                break;
            }
}

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

To check for DIRECTORIES you should not use something like:

if exist c:\windows\

To work properly use:

if exist c:\windows\\.

note the "." at the end.

Click outside menu to close in jquery

$("html").click( onOutsideClick );
onOutsideClick = function( e )
{
    var t = $( e.target );
    if ( !(
        t.is("#mymenu" ) ||     //Where #mymenu - is a div container of your menu
        t.parents( "#mymenu" ).length > 0
        )   )
    {
        //TODO: hide your menu
    }
};

And better to set the listener only when your menu is being visible and always remove the listener after menu becomes hidden.

how to play video from url

It has something to do with your link and content. Try the following two links:

    String path="http://www.ted.com/talks/download/video/8584/talk/761";
    String path1="http://commonsware.com/misc/test2.3gp";

    Uri uri=Uri.parse(path1);

    VideoView video=(VideoView)findViewById(R.id.VideoView01);
    video.setVideoURI(uri);
    video.start();

Start with "path1", it is a small light weight video stream and then try the "path", it is a higher resolution than "path1", a perfect high resolution for the mobile phone.

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

tl;dr / quick fix

  • Don't decode/encode willy nilly
  • Don't assume your strings are UTF-8 encoded
  • Try to convert strings to Unicode strings as soon as possible in your code
  • Fix your locale: How to solve UnicodeDecodeError in Python 3.6?
  • Don't be tempted to use quick reload hacks

Unicode Zen in Python 2.x - The Long Version

Without seeing the source it's difficult to know the root cause, so I'll have to speak generally.

UnicodeDecodeError: 'ascii' codec can't decode byte generally happens when you try to convert a Python 2.x str that contains non-ASCII to a Unicode string without specifying the encoding of the original string.

In brief, Unicode strings are an entirely separate type of Python string that does not contain any encoding. They only hold Unicode point codes and therefore can hold any Unicode point from across the entire spectrum. Strings contain encoded text, beit UTF-8, UTF-16, ISO-8895-1, GBK, Big5 etc. Strings are decoded to Unicode and Unicodes are encoded to strings. Files and text data are always transferred in encoded strings.

The Markdown module authors probably use unicode() (where the exception is thrown) as a quality gate to the rest of the code - it will convert ASCII or re-wrap existing Unicodes strings to a new Unicode string. The Markdown authors can't know the encoding of the incoming string so will rely on you to decode strings to Unicode strings before passing to Markdown.

Unicode strings can be declared in your code using the u prefix to strings. E.g.

>>> my_u = u'my ünicôdé string'
>>> type(my_u)
<type 'unicode'>

Unicode strings may also come from file, databases and network modules. When this happens, you don't need to worry about the encoding.

Gotchas

Conversion from str to Unicode can happen even when you don't explicitly call unicode().

The following scenarios cause UnicodeDecodeError exceptions:

# Explicit conversion without encoding
unicode('€')

# New style format string into Unicode string
# Python will try to convert value string to Unicode first
u"The currency is: {}".format('€')

# Old style format string into Unicode string
# Python will try to convert value string to Unicode first
u'The currency is: %s' % '€'

# Append string to Unicode
# Python will try to convert string to Unicode first
u'The currency is: ' + '€'         

Examples

In the following diagram, you can see how the word café has been encoded in either "UTF-8" or "Cp1252" encoding depending on the terminal type. In both examples, caf is just regular ascii. In UTF-8, é is encoded using two bytes. In "Cp1252", é is 0xE9 (which is also happens to be the Unicode point value (it's no coincidence)). The correct decode() is invoked and conversion to a Python Unicode is successfull: Diagram of a string being converted to a Python Unicode string

In this diagram, decode() is called with ascii (which is the same as calling unicode() without an encoding given). As ASCII can't contain bytes greater than 0x7F, this will throw a UnicodeDecodeError exception:

Diagram of a string being converted to a Python Unicode string with the wrong encoding

The Unicode Sandwich

It's good practice to form a Unicode sandwich in your code, where you decode all incoming data to Unicode strings, work with Unicodes, then encode to strs on the way out. This saves you from worrying about the encoding of strings in the middle of your code.

Input / Decode

Source code

If you need to bake non-ASCII into your source code, just create Unicode strings by prefixing the string with a u. E.g.

u'Zürich'

To allow Python to decode your source code, you will need to add an encoding header to match the actual encoding of your file. For example, if your file was encoded as 'UTF-8', you would use:

# encoding: utf-8

This is only necessary when you have non-ASCII in your source code.

Files

Usually non-ASCII data is received from a file. The io module provides a TextWrapper that decodes your file on the fly, using a given encoding. You must use the correct encoding for the file - it can't be easily guessed. For example, for a UTF-8 file:

import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
     my_unicode_string = my_file.read() 

my_unicode_string would then be suitable for passing to Markdown. If a UnicodeDecodeError from the read() line, then you've probably used the wrong encoding value.

CSV Files

The Python 2.7 CSV module does not support non-ASCII characters . Help is at hand, however, with https://pypi.python.org/pypi/backports.csv.

Use it like above but pass the opened file to it:

from backports import csv
import io
with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file:
    for row in csv.reader(my_file):
        yield row

Databases

Most Python database drivers can return data in Unicode, but usually require a little configuration. Always use Unicode strings for SQL queries.

MySQL

In the connection string add:

charset='utf8',
use_unicode=True

E.g.

>>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")
PostgreSQL

Add:

psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)

HTTP

Web pages can be encoded in just about any encoding. The Content-type header should contain a charset field to hint at the encoding. The content can then be decoded manually against this value. Alternatively, Python-Requests returns Unicodes in response.text.

Manually

If you must decode strings manually, you can simply do my_string.decode(encoding), where encoding is the appropriate encoding. Python 2.x supported codecs are given here: Standard Encodings. Again, if you get UnicodeDecodeError then you've probably got the wrong encoding.

The meat of the sandwich

Work with Unicodes as you would normal strs.

Output

stdout / printing

print writes through the stdout stream. Python tries to configure an encoder on stdout so that Unicodes are encoded to the console's encoding. For example, if a Linux shell's locale is en_GB.UTF-8, the output will be encoded to UTF-8. On Windows, you will be limited to an 8bit code page.

An incorrectly configured console, such as corrupt locale, can lead to unexpected print errors. PYTHONIOENCODING environment variable can force the encoding for stdout.

Files

Just like input, io.open can be used to transparently convert Unicodes to encoded byte strings.

Database

The same configuration for reading will allow Unicodes to be written directly.

Python 3

Python 3 is no more Unicode capable than Python 2.x is, however it is slightly less confused on the topic. E.g the regular str is now a Unicode string and the old str is now bytes.

The default encoding is UTF-8, so if you .decode() a byte string without giving an encoding, Python 3 uses UTF-8 encoding. This probably fixes 50% of people's Unicode problems.

Further, open() operates in text mode by default, so returns decoded str (Unicode ones). The encoding is derived from your locale, which tends to be UTF-8 on Un*x systems or an 8-bit code page, such as windows-1251, on Windows boxes.

Why you shouldn't use sys.setdefaultencoding('utf8')

It's a nasty hack (there's a reason you have to use reload) that will only mask problems and hinder your migration to Python 3.x. Understand the problem, fix the root cause and enjoy Unicode zen. See Why should we NOT use sys.setdefaultencoding("utf-8") in a py script? for further details

How to make circular background using css?

Keep it simple:

.circle
  {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
  }

Width and height can be anything, as long as they're equal

What is Gradle in Android Studio?

Gradle is to the Groovy JVM language what ant is to Java. Basically, it's Groovy's build tool. Unlike Ant, it's based on the full Groovy language. You can, for example, write Groovy script code in the Gradle script to do something rather than relying on a specific domain language.

I don't know IntelliJ's specific integration, but imagine you could "extend" Groovy such that you could write specific "build" language primitives and they just became part of the Groovy language. (Groovy's metaprogramming is a whole discussion unto itself.) IntelliJ/Google could use Gradle to build a very high-level build language, yet, it's a language build on an expandable, open standard.

How to add bootstrap to an angular-cli project

At first, you have to install tether, jquery and bootstrap with these commands

npm i -S tether
npm i -S jquery
npm i -S [email protected] 

After add these lines in your angular-cli.json (angular.json from version 6 onwards) file

  "styles": [
    "styles.scss",
    "../node_modules/bootstrap/scss/bootstrap-flex.scss"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/tether/dist/js/tether.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js"
  ]

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

Find Active Tab using jQuery and Twitter Bootstrap

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active")

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
  activeTab = e.target;
})

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had similar problem while using in postman. for POST request under header section add these as

key:valuepair

Content-Type:application/json Accept:application/json

i hope it will work.

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

Initializing entire 2D array with one value

Use vector array instead:

vector<vector<int>> array(ROW, vector<int>(COLUMN, 1));

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

null terminating a string

From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

Is there a way that I can check if a data attribute exists?

You can create an extremely simple jQuery-plugin to query an element for this:

$.fn.hasData = function(key) {
  return (typeof $(this).data(key) != 'undefined');
};

Then you can simply use $("#dataTable").hasData('timer')

Gotchas:

  • Will return false only if the value does not exist (is undefined); if it's set to false/null it hasData() will still return true.
  • It's different from the built-in $.hasData() which only checks if any data on the element is set.

bypass invalid SSL certificate in .net core

I solve with this:

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            }
        });

YourService.cs

public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
        _clientFactory = clientFactory;
    }

var request = new HttpRequestMessage(...

var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");

HttpResponseMessage response = await client.SendAsync(request);