Programs & Examples On #Help files

Laravel Carbon subtract days from current date

From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

Select elements by attribute

if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}

In a URL, should spaces be encoded using %20 or +?

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20" or "+". From the section "Query strings" under "Recommendations":

Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:

3.4. Query Component The query component is a string of information to be interpreted by the resource.

   query         = *uric

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+" characters.

As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode() is to then call replaceAll("\\+","%20") on the return value.

Programmatically saving image to Django ImageField

What I did was to create my own storage that will just not save the file to the disk:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I've used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

Example to use shared_ptr?

The boost documentation provides a pretty good start example: shared_ptr example (it's actually about a vector of smart pointers) or shared_ptr doc The following answer by Johannes Schaub explains the boost smart pointers pretty well: smart pointers explained

The idea behind(in as few words as possible) ptr_vector is that it handles the deallocation of memory behind the stored pointers for you: let's say you have a vector of pointers as in your example. When quitting the application or leaving the scope in which the vector is defined you'll have to clean up after yourself(you've dynamically allocated ANDgate and ORgate) but just clearing the vector won't do it because the vector is storing the pointers and not the actual objects(it won't destroy but what it contains).

 // if you just do
 G.clear() // will clear the vector but you'll be left with 2 memory leaks
 ...
// to properly clean the vector and the objects behind it
for (std::vector<gate*>::iterator it = G.begin(); it != G.end(); it++)
{
  delete (*it);
}

boost::ptr_vector<> will handle the above for you - meaning it will deallocate the memory behind the pointers it stores.

SLF4J: Class path contains multiple SLF4J bindings

Check mvn dependency:tree and see if there are multiple repos from where slf4j belongs to two different JARs.

If so, add exclusion in one of the dependencies:

<exclusions>
    <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
</exclusions>

T-sql - determine if value is integer

Had the same question. I finally used

where ATTRIBUTE != round(ATTRIBUTE)

and it worked for me

Undefined function mysql_connect()

I was getting this error because the project I was working on was developed on php 5.6 and after install, the project was unable to run on php7.1.

Just for anyone that uses Vagrant with ubuntu/nginx, in the nginx directory(/etc/nginx/), there is a directory named "sites-available" which contains a file named like the url configured for the vagrant maschine. In my case was homestead.app. Within this file there is a line that says something like

    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;

There you can change the php version to the desired for that particular site.

Googled this but wasnt really able to find a simple answer that said where to look and what to change.

Hope that this helps anyone. Thanks.

How do you convert a DataTable into a generic list?

You can use a generic method like that for datatable to generic list

public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
    try
    {
        List<T> list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    if (propertyInfo.PropertyType.IsEnum)
                    {
                        propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));
                    }
                    else
                    {
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }                          
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}

Checking if an object is a number in C#

There are some great answers above. Here is an all-in-one solution. Three overloads for different circumstances.

// Extension method, call for any object, eg "if (x.IsNumeric())..."
public static bool IsNumeric(this object x) { return (x==null ? false : IsNumeric(x.GetType())); }

// Method where you know the type of the object
public static bool IsNumeric(Type type) { return IsNumeric(type, Type.GetTypeCode(type)); }

// Method where you know the type and the type code of the object
public static bool IsNumeric(Type type, TypeCode typeCode) { return (typeCode == TypeCode.Decimal || (type.IsPrimitive && typeCode != TypeCode.Object && typeCode != TypeCode.Boolean && typeCode != TypeCode.Char)); }

Get list of passed arguments in Windows batch script (.bat)

You can use For Commad,to get list of Arg.

Help : For /? Help : Setlocal /?

Here is my way =

@echo off
::For Run Use This = cmd /c ""Args.cmd" Hello USER Scientist etc"
setlocal EnableDelayedExpansion
set /a Count=0
for %%I IN (%*) DO (
 Echo Arg_!Count! = %%I
 set /a Count+=1 
)
Echo Count Of Args = !Count!
Endlocal

Do not need Shift command.

Nginx fails to load css files

add this to your ngnix conf file

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

Does Django scale?

What's the "largest" site that's built on Django today? (I measure size mostly by user traffic)

In the US, it was Mahalo. I'm told they handle roughly 10 million uniques a month. Now, in 2019, Mahalo is powered by Ruby on Rails.

Abroad, the Globo network (a network of news, sports, and entertainment sites in Brazil); Alexa ranks them in to top 100 globally (around 80th currently).

Other notable Django users include PBS, National Geographic, Discovery, NASA (actually a number of different divisions within NASA), and the Library of Congress.

Can Django deal with 100k users daily, each visiting the site for a couple of hours?

Yes -- but only if you've written your application right, and if you've got enough hardware. Django's not a magic bullet.

Could a site like StackOverflow run on Django?

Yes (but see above).

Technology-wise, easily: see soclone for one attempt. Traffic-wise, compete pegs StackOverflow at under 1 million uniques per month. I can name at least dozen Django sites with more traffic than SO.

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You have a couple of options:

  1. Scope the domain down (see document.domain) in both the containing page and the iframe to the same thing. Then they will not be bound by 'same origin' constraints.

  2. Use postMessage which is supported by all HTML5 browsers for cross-domain communication.

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

How to add List<> to a List<> in asp.net

Use List.AddRange(collection As IEnumerable(Of T)) method.

It allows you to append at the end of your list another collection/list.

Example:

List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);

What is the meaning of "this" in Java?

In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.

public class MyDialog extends JDialog implements ActionListener
{
    public MyDialog()
    {
        JButton myButton = new JButton("Hello");
        myButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Hurdy Gurdy!");
    }

}

Remove Backslashes from Json Data in JavaScript

tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).


I assume that your actual JSON looks like

{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}

I.e. you have a top level object with one key, data. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. This lets the parser know that " is to be treated literally and doesn't terminate the string.

So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.

var data = JSON.parse(JSON.parse(json).data));

declaring a priority_queue in c++ with a custom comparator

One can also use a lambda function.

auto Compare = [](Node &a, Node &b) { //compare };
std::priority_queue<Node, std::vector<Node>, decltype(Compare)> openset(Compare);

CSS scale height to match width - possibly with a formfactor

You could try using vw for height. https://developer.mozilla.org/en/docs/Web/CSS/length

Something like

div#map {
     width: 100%;
     height: 60vw;
}

This would set the width of the div to 60% of the viewport width. You will probably need to use calc to adjust to take padding into account …

How to parse JSON and access results

The main problem with your example code is that the $result variable you use to store the output of curl_exec() does not contain the body of the HTTP response - it contains the value true. If you try to print_r() that, it will just say "1".

The curl_exec() reference explains:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

So if you want to get the HTTP response body in your $result variable, you must first run

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

After that, you can call json_decode() on $result, as other answers have noted.

On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GET some resource or even POST to some URL, and read the response - then file_get_contents() is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.

How to remove indentation from an unordered list item?

Add this to your CSS:

ul { list-style-position: inside; }

This will place the li elements in the same indent as other paragraphs and text.

Ref: http://www.w3schools.com/cssref/pr_list-style-position.asp

Entity Framework and SQL Server View

We had the same problem and this is the solution:

To force entity framework to use a column as a primary key, use ISNULL.

To force entity framework not to use a column as a primary key, use NULLIF.

An easy way to apply this is to wrap the select statement of your view in another select.

Example:

SELECT
  ISNULL(MyPrimaryID,-999) MyPrimaryID,
  NULLIF(AnotherProperty,'') AnotherProperty
  FROM ( ... ) AS temp

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

Differences between "java -cp" and "java -jar"?

Like already said, the -cp is just for telling the jvm in the command line which class to use for the main thread and where it can find the libraries (define classpath). In -jar it expects the class-path and main-class to be defined in the jar file manifest. So other is for defining things in command line while other finding them inside the jar manifest. There is no difference in performance. You can't use them at the same time, -jar will override the -cp.

Though even if you use -cp, it will still check the manifest file. So you can define some of the class-paths in the manifest and some in the command line. This is particularly useful when you have a dependency on some 3rd party jar, which you might not provide with your build or don't want to provide (expecting it to be found already in the system where it's to be installed for example). So you can use it to provide external jars. It's location may vary between systems or it may even have a different version on different system (but having the same interfaces). This way you can build the app with other version and add the actual 3rd party dependency to class-path on the command line when running it on different systems.

How to install a node.js module without using npm?

Step-by-step:

  • let's say you are working on a project use-gulp which uses(requires) node_modules like gulp and gulp-util.
  • Now you want to make some modifications to gulp-util lib and test it locally with your use-gulp project...
  • Fork gulp-util project on github\bitbucket etc.
  • Switch to your project: cd use-gulp/node_modules
  • Clone gulp-util as gulp-util-dev : git clone https://.../gulp-util.git gulp-util-dev
  • Run npm install to ensure dependencies of gulp-util-dev are available.
  • Now you have a mirror of gulp-util as gulp-util-dev. In your use-gulp project, you can now replace: require('gulp-util')...; call with : require('gulp-util-dev') to test your changes you made to gulp-util-dev

HTML if image is not found

If you want an alternative image instead of a text, you can as well use php:

$file="smiley.gif";
$alt_file="alt.gif";
if(file_exist($file)){
     echo "<img src='".$file."' border="0" />";
}else if($alt_file){
     // the alternative file too might not exist not exist
     echo "<img src='".$alt_file."' border="0" />";
}else{
  echo "smily face";
}

How do I iterate through children elements of a div using jQuery?

children() is a loop in itself.

$('.element').children().animate({
'opacity':'0'
});

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

How to insert DECIMAL into MySQL database

Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.

Append a single character to a string or char array in java?

just add them like this :

        String character = "a";
        String otherString = "helen";
        otherString=otherString+character;
        System.out.println(otherString);

Get value of a specific object property in C# without knowing the class behind

Reflection can help you.

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);

Setting PHP tmp dir - PHP upload not working

I was also facing the same issue for 2 days but now finally it is working.

Step 1 : create a php script file with this content.

<?php 
 echo 'username : ' . `whoami`;
 phpinfo();
?>

note down the username. note down open_basedir under core section of phpinfo. also note down upload_tmp_dir under core section of phpinfo.

Here two things are important , see if upload_tmp_dir value is inside one of open_basedir directory. ( php can not upload files outside open_basedir directory ).

Step 2 : Open terminal with root access and go to upload_tmp_dir location. ( In my case "/home/admin/tmp". )

  => cd /home/admin/tmp

But it was not found in my case so I created it and added chown for php user which I get in step 1 ( In my case "admin" ).

  => mkdir /home/admin/tmp
  => chown admin /home/admin/tmp

That is all you have to do to fix the file upload problem.

Android: Expand/collapse animation

combined solutions from @Tom Esterez and @Geraldo Neto

public static void expandOrCollapseView(View v,boolean expand){

    if(expand){
        v.measure(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();
        v.getLayoutParams().height = 0;
        v.setVisibility(View.VISIBLE);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(targetHeight);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(500);
        valueAnimator.start();
    }
    else
    {
        final int initialHeight = v.getMeasuredHeight();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(initialHeight,0);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
                if((int)animation.getAnimatedValue() == 0)
                    v.setVisibility(View.GONE);
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(500);
        valueAnimator.start();
    }
}

//sample usage
expandOrCollapseView((Your ViewGroup),(Your ViewGroup).getVisibility()!=View.VISIBLE);

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

Android Gradle Could not reserve enough space for object heap

I tried several solutions, nothing seemed to work. Setting my system JDK to match Android Studio's solved the problem.

Ensure your system java

java -version

Is the same as Androids

File > Project Structure > JDK Location

Difference between id and name attributes in HTML

<form action="demo_form.asp">
<label for="male">Male</label>
<input type="radio" name="sex" id="male" value="male"><br>
<label for="female">Female</label>
<input type="radio" name="sex" id="female" value="female"><br>
<input type="submit" value="Submit">
</form>

What are metaclasses in Python?

A class, in Python, is an object, and just like any other object, it is an instance of "something". This "something" is what is termed as a Metaclass. This metaclass is a special type of class that creates other class's objects. Hence, metaclass is responsible for making new classes. This allows the programmer to customize the way classes are generated.

To create a metaclass, overriding of new() and init() methods is usually done. new() can be overridden to change the way objects are created, while init() can be overridden to change the way of initializing the object. Metaclass can be created by a number of ways. One of the ways is to use type() function. type() function, when called with 3 parameters, creates a metaclass. The parameters are :-

  1. Class Name
  2. Tuple having base classes inherited by class
  3. A dictionary having all class methods and class variables

Another way of creating a metaclass comprises of 'metaclass' keyword. Define the metaclass as a simple class. In the parameters of inherited class, pass metaclass=metaclass_name

Metaclass can be specifically used in the following situations :-

  1. when a particular effect has to be applied to all the subclasses
  2. Automatic change of class (on creation) is required
  3. By API developers

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

Solution for per-app deployments

This is a listener I wrote to solve the problem: it autodetects if the driver has registered itself and acts accordingly.it

Important: it is meant to be used ONLY when the driver jar is deployed in WEB-INF/lib, not in the Tomcat /lib, as many suggest, so that each application can take care of its own driver and run on a untouched Tomcat. That is the way it should be IMHO.

Just configure the listener in your web.xml before any other and enjoy.

add near the top of web.xml:

<listener>
    <listener-class>utils.db.OjdbcDriverRegistrationListener</listener-class>    
</listener>

save as utils/db/OjdbcDriverRegistrationListener.java:

package utils.db;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import oracle.jdbc.OracleDriver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Registers and unregisters the Oracle JDBC driver.
 * 
 * Use only when the ojdbc jar is deployed inside the webapp (not as an
 * appserver lib)
 */
public class OjdbcDriverRegistrationListener implements ServletContextListener {

    private static final Logger LOG = LoggerFactory
            .getLogger(OjdbcDriverRegistrationListener.class);

    private Driver driver = null;

    /**
     * Registers the Oracle JDBC driver
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.driver = new OracleDriver(); // load and instantiate the class
        boolean skipRegistration = false;
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            if (driver instanceof OracleDriver) {
                OracleDriver alreadyRegistered = (OracleDriver) driver;
                if (alreadyRegistered.getClass() == this.driver.getClass()) {
                    // same class in the VM already registered itself
                    skipRegistration = true;
                    this.driver = alreadyRegistered;
                    break;
                }
            }
        }

        try {
            if (!skipRegistration) {
                DriverManager.registerDriver(driver);
            } else {
                LOG.debug("driver was registered automatically");
            }
            LOG.info(String.format("registered jdbc driver: %s v%d.%d", driver,
                    driver.getMajorVersion(), driver.getMinorVersion()));
        } catch (SQLException e) {
            LOG.error(
                    "Error registering oracle driver: " + 
                            "database connectivity might be unavailable!",
                    e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Deregisters JDBC driver
     * 
     * Prevents Tomcat 7 from complaining about memory leaks.
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        if (this.driver != null) {
            try {
                DriverManager.deregisterDriver(driver);
                LOG.info(String.format("deregistering jdbc driver: %s", driver));
            } catch (SQLException e) {
                LOG.warn(
                        String.format("Error deregistering driver %s", driver),
                        e);
            }
            this.driver = null;
        } else {
            LOG.warn("No driver to deregister");
        }

    }

}

Can you force a React component to rerender without calling setState?

I Avoided forceUpdate by doing following

WRONG WAY : do not use index as key

this.state.rows.map((item, index) =>
   <MyComponent cell={item} key={index} />
)

CORRECT WAY : Use data id as key, it can be some guid etc

this.state.rows.map((item) =>
   <MyComponent item={item} key={item.id} />
)

so by doing such code improvement your component will be UNIQUE and render naturally

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

How to remove all non-alpha numeric characters from a string in MySQL?

Based on the answer by Ryan Shillington, modified to work with strings longer than 255 characters and preserving spaces from the original string.

FYI there is lower(str) in the end.

I used this to compare strings:

DROP FUNCTION IF EXISTS spacealphanum;
DELIMITER $$
CREATE FUNCTION `spacealphanum`( str TEXT ) RETURNS TEXT CHARSET utf8
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret TEXT DEFAULT ''; 
  DECLARE c CHAR(1); 
  SET len = CHAR_LENGTH( str ); 
  REPEAT 
    BEGIN 
      SET c = MID( str, i, 1 ); 
      IF c REGEXP '[[:alnum:]]' THEN 
        SET ret=CONCAT(ret,c); 
      ELSEIF  c = ' ' THEN
          SET ret=CONCAT(ret," ");
      END IF; 
      SET i = i + 1; 
    END; 
  UNTIL i > len END REPEAT; 
  SET ret = lower(ret);
  RETURN ret; 
  END $$
  DELIMITER ;

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

how do I check in bash whether a file was created more than x time ago?

Consider the outcome of the tool 'stat':

  File: `infolog.txt'
  Size: 694         Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 11635578    Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/     fdr)   Gid: ( 1000/     fdr)
Access: 2009-01-01 22:04:15.000000000 -0800
Modify: 2009-01-01 22:05:05.000000000 -0800
Change: 2009-01-01 22:05:05.000000000 -0800

You can see here the three dates for Access/modify/change. There is no created date. You can only really be sure when the file contents were modified (the "modify" field) or its inode changed (the "change" field).

Examples of when both fields get updated:

"Modify" will be updated if someone concatenated extra information to the end of the file.

"Change" will be updated if someone changed permissions via chmod.

jQuery javascript regex Replace <br> with \n

True jQuery way if you want to change directly the DOM without messing with inner HTML:

$('#text').find('br').prepend(document.createTextNode('\n')).remove();

Prepend inserts inside the element, before() is the method we need here:

$('#text').find('br').before(document.createTextNode('\n')).remove();

Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.

This should be faster if you work with long texts since there are no string operations here.

To display the new lines:

$('#text').css('white-space', 'pre-line');

How to start anonymous thread class

Since anonymous classes extend the given class you can store them in a variable.

eg.

Thread t = new Thread()
{
    public void run() {
        System.out.println("blah");
    }
};
t.start();

Alternatively, you can just call the start method on the object you have immediately created.

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();
// similar to new Thread().start();

Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).

eg

new Thread(new Runnable()
{
    @Override
    public void run() {
        System.out.println("blah");
    }
}).start();

Mockito: Inject real objects into private @Autowired fields

Use @Spy annotation

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case 'RealServiceImpl' instance will get injected into the 'demo'

For more details refer

Mockito-home

@Spy

@Mock

Changing Node.js listening port

There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

If you're having problems finding a port that's open, you can go to the command line and type:

netstat -ano

To see a list of all ports in use per adapter.

ReferenceError: fetch is not defined

The fetch API is not implemented in Node.

You need to use an external module for that, like node-fetch.

Install it in your Node application like this

npm i node-fetch --save

then put the line below at the top of the files where you are using the fetch API:

const fetch = require("node-fetch");

How do I pass options to the Selenium Chrome driver using Python?

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')

# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())

Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.

Is it possible to pull just one file in Git?

@Mawardy's answer worked for me, but my changes were on the remote so I had to specify the origin

git checkout origin/master -- {filename}

Convert negative data into positive data in SQL Server

Use the absolute value function ABS. The syntax is

ABS ( numeric_expression )

How to get process ID of background process?

You can use the jobs -l command to get to a particular jobL

^Z
[1]+  Stopped                 guard

my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18           guard

In this case, 46841 is the PID.

From help jobs:

-l Report the process group ID and working directory of the jobs.

jobs -p is another option which shows just the PIDs.

Search for "does-not-contain" on a DataFrame in pandas

You can use the invert (~) operator (which acts like a not for boolean data):

new_df = df[~df["col"].str.contains(word)]

, where new_df is the copy returned by RHS.

contains also accepts a regular expression...


If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False:

new_df = df[~df["col"].str.contains(word, na=False)]

Or,

new_df = df[df["col"].str.contains(word) == False]

"Fade" borders in CSS

Add this class css to your style sheet

.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}

set width to the width of your image. and use this html for image

<div class="border_gradient">
        <img src="image.png" />
</div>

though it may not give the same exact border, it will some gradient looks on the border.

source: CSS3 Borders

Centering controls within a form in .NET (Winforms)?

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centered in that direction when resizing.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)

Using C# regular expressions to remove HTML tags

Regex regex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);

Source

Load image from resources

Try this for WPF

StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How to reset sequence in postgres and fill id column with new data?

To retain order of the rows:

UPDATE thetable SET rowid=col_serial FROM 
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1 
WHERE thetable.rowid=t1.rowid;

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

How to round an average to 2 decimal places in PostgreSQL?

SELECT ROUND(SUM(amount)::numeric, 2) AS total_amount
FROM transactions

Gives: 200234.08

How to sort an array in Bash

a=(e b 'c d')
shuf -e "${a[@]}" | sort >/tmp/f
mapfile -t g </tmp/f

Get SELECT's value and text in jQuery

$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value

How to read a line from the console in C?

This function should do what you want:

char* readLine( FILE* file )
 {
 char buffer[1024];
 char* result = 0;
 int length = 0;

 while( !feof(file) )
  {
  fgets( buffer, sizeof(buffer), file );
  int len = strlen(buffer);
  buffer[len] = 0;

  length += len;
  char* tmp = (char*)malloc(length+1);
  tmp[0] = 0;

  if( result )
   {
   strcpy( tmp, result );
   free( result );
   result = tmp;
   }

  strcat( result, buffer );

  if( strstr( buffer, "\n" ) break;
  }

 return result;
 }

char* line = readLine( stdin );
/* Use it */
free( line );

I hope this helps.

Getting the last element of a split string array

And if you don't want to construct an array ...

var str = "how,are you doing, today?";
var res = str.replace(/(.*)([, ])([^, ]*$)/,"$3");

The breakdown in english is:

/(anything)(any separator once)(anything that isn't a separator 0 or more times)/

The replace just says replace the entire string with the stuff after the last separator.

So you can see how this can be applied generally. Note the original string is not modified.

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

I solved this problem by creating a new object every time I want to add anything to the database.

MetadataException when using Entity Framework Entity Connection

There are several possible catches. I think that the most common error is in this part of the connection string:

res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;

This is no magic. Once you understand what is stands for you'll get the connection string right.

First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.

Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.

Your final EF connection string may look like this:

res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;

how to set imageview src?

Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.

Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html

e.g.:

imageView.setImageResource(R.drawable.myimage);

C# Macro definitions in Preprocessor

Turn the C Macro into a C# static method in a class.

How to zoom div content using jquery?

 $('image').animate({ 'zoom': 1}, 400);

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

Why catch and rethrow an exception in C#?

A point that people haven't mentioned is that while .NET languages don't really make a proper distinction, the question of whether one should take action when an exception occurs, and whether one will resolve it, are actually distinct questions. There are many cases where one should take action based upon exceptions one has no hope of resolving, and there are some cases where all that is necessary to "resolve" an exception is to unwind the stack to a certain point--no further action required.

Because of the common wisdom that one should only "catch" things one can "handle", a lot of code which should take action when exceptions occur, doesn't. For example, a lot of code will acquire a lock, put the guarded object "temporarily" into a state which violates its invariants, then put it object into a legitimate state, and then release the lock back before anyone else can see the object. If an exception occurs while the object is in a dangerously-invalid state, common practice is to release the lock with the object still in that state. A much better pattern would be to have an exception that occurs while the object is in a "dangerous" condition expressly invalidate the lock so any future attempt to acquire it will immediately fail. Consistent use of such a pattern would greatly improve the safety of so-called "Pokemon" exception handling, which IMHO gets a bad reputation primarily because of code which allows exceptions to percolate up without taking appropriate action first.

In most .NET languages, the only way for code to take action based upon an exception is to catch it (even though it knows it's not going to resolve the exception), perform the action in question and then re-throw). Another possible approach if code doesn't care about what exception is thrown is to use an ok flag with a try/finally block; set the ok flag to false before the block, and to true before the block exits, and before any return that's within the block. Then, within finally, assume that if ok isn't set, an exception must have occurred. Such an approach is semantically better than a catch/throw, but is ugly and is less maintainable than it should be.

How can I delete multiple lines in vi?

If you want to delete a range AFTER a specific line trigger you can use something like this

:g/^TMPDIR/ :.,+11d

That deletes 11 lines (inclusive) after every encounter of ^TMPDIR.

Call a "local" function within module.exports from another function in module.exports?

Starting with Node.js version 13 you can take advantage of ES6 Modules.

export function foo() {
    return 'foo';
}

export function bar() {
    return foo();
}

Following the Class approach:

class MyClass {

    foo() {
        return 'foo';
    }

    bar() {
        return this.foo();
    }
}

module.exports = new MyClass();

This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching

How do I dynamically set HTML5 data- attributes using react?

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

refresh leaflet map: map container is already initialized

use the redrawAll() function rather than renderAll().

What's the fastest way to read a text file line-by-line?

If you're using .NET 4, simply use File.ReadLines which does it all for you. I suspect it's much the same as yours, except it may also use FileOptions.SequentialScan and a larger buffer (128 seems very small).

How to "crop" a rectangular image into a square with CSS?

Use CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}

How do I create dynamic properties in C#?

I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!

You cannot add properties to a class after it has been JITed.

The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.

You also wouldn't be able to access those properties at compile time.

Something like:

public class Dynamic
{
    public Dynamic Add<T>(string key, T value)
    {
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
        TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
        typeBuilder.SetParent(this.GetType());
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);

        MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
        ILGenerator getter = getMethodBuilder.GetILGenerator();
        getter.Emit(OpCodes.Ldarg_0);
        getter.Emit(OpCodes.Ldstr, key);
        getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
        getter.Emit(OpCodes.Ret);
        propertyBuilder.SetGetMethod(getMethodBuilder);

        Type type = typeBuilder.CreateType();

        Dynamic child = (Dynamic)Activator.CreateInstance(type);
        child.dictionary = this.dictionary;
        dictionary.Add(key, value);
        return child;
    }

    protected T Get<T>(string key)
    {
        return (T)dictionary[key];
    }

    private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}

I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)

Now you can use it:

Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));

You could also use it like a normal property in a language that supports late binding (for example, VB.NET)

How to effectively work with multiple files in Vim

If you are going to use multiple buffers, I think the most important thing is to set hidden so that it will let you switch buffers even if you have unsaved changes in the one you are leaving.

What is the format specifier for unsigned short int?

From the Linux manual page:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol-
       lowing n conversion corresponds to a pointer to a short int argument.

So to print an unsigned short integer, the format string should be "%hu".

How to run cron once, daily at 10pm

Here are some more examples

  • Run every 6 hours at 46 mins past the hour:

    46 */6 * * *

  • Run at 2:10 am:

    10 2 * * *

  • Run at 3:15 am:

    15 3 * * *

  • Run at 4:20 am:

    20 4 * * *

  • Run at 5:31 am:

    31 5 * * *

  • Run at 5:31 pm:

    31 17 * * *

Symbolicating iPhone App Crash Reports

I did this successfully, using the following steps.

Step 1: Create a folder in desktop, I give name it to "CrashReport" and put three files ("MYApp.app", "MyApp.app.dSYM", "MYApp_2013-07-18.crash") in it.

Step 2: Open Finder and go to Applications, where you will find the Xcode application, right click on this and Click "Show Package Contents", after this follow this simple path. "Contents->Developer->Platforms->iPhoneOS.platform->Developer->Library->PrivateFrameworks->DTDeviceKit.framework->Versions->A->Resources"

OR

"Contents->Developer->Platforms->iPhoneOS.platform->Developer->Library->PrivateFrameworks->DTDeviceKitBase.framework->Versions->A->Resources"

OR

For Xcode 6 and above the path is Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources

Where you find "symbolicatecrash" file, copy this and paste it to "CrashReport" folder.

Step 3: launch the terminal, run these 3 Command

  1. cd /Users/mac38/Desktop/CrashReport and press Enter button

  2. export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer" and press Enter

  3. ./symbolicatecrash -A -v MYApp_2013-07-18.crash MyApp.app.dSYM and press Enter Now its Done.. (NOTE: versions around 6.4 or later do not have the -A option -- just leave it out).

How to initialize an array in Java?

Syntax

 Datatype[] variable = new Datatype[] { value1,value2.... }

 Datatype variable[]  = new Datatype[] { value1,value2.... }

Example :

int [] points = new int[]{ 1,2,3,4 };

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

The bug has been fixed in the latest androidx version. And the famous workaround will cause crash now. so we need not it now.

Combating AngularJS executing controller twice

For those using the ControllerAs syntax, just declare the controller label in the $routeprovider as follows:

$routeprovider
        .when('/link', {
            templateUrl: 'templateUrl',
            controller: 'UploadsController as ctrl'
        })

or

$routeprovider
        .when('/link', {
            templateUrl: 'templateUrl',
            controller: 'UploadsController'
            controllerAs: 'ctrl'
        })

After declaring the $routeprovider, do not supply the controller as in the view. Instead use the label in the view.

Are there constants in JavaScript?

JavaScript ES6 (re-)introduced the const keyword which is supported in all major browsers.

Variables declared via const cannot be re-declared or re-assigned.

Apart from that, const behaves similar to let.

It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):

const x = 1;
x = 2;
console.log(x); // 1 ...as expected, re-assigning fails

Attention: Be aware of the pitfalls regarding objects:

const o = {x: 1};
o = {x: 2};
console.log(o); // {x: 1} ...as expected, re-assigning fails

o.x = 2;
console.log(o); // {x: 2} !!! const does not make objects immutable!

const a = [];
a = [1];
console.log(a); // 1 ...as expected, re-assigning fails

a.push(1);
console.log(a); // [1] !!! const does not make objects immutable

If you really need an immutable and absolutely constant object: Just use const ALL_CAPS to make your intention clear. It is a good convention to follow for all const declarations anyway, so just rely on it.

Converting List<Integer> to List<String>

What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformer and the collect method from Apache Commons, e.g.:

public class IntegerToStringTransformer implements Transformer<Integer, String> {
   public String transform(final Integer i) {
      return (i == null ? null : i.toString());
   }
}

..and then..

CollectionUtils.collect(
   collectionOfIntegers, 
   new IntegerToStringTransformer(), 
   newCollectionOfStrings);

assign function return value to some variable using javascript

The result is undefined since $.ajax runs an asynchronous operation. Meaning that return status gets executed before the $.ajax operation finishes with the request.

You may use Promise to have a syntax which feels synchronous.

function doSomething() { 
    return new Promise((resolve, reject) => {
        $.ajax({
            url:'action.php',
            type: "POST",
            data: dataString,
            success: function (txtBack) { 
                if(txtBack==1) {
                    resolve(1);
                } else {
                    resolve(0);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                reject(textStatus);
            }
        });
    });
}

You can call the promise like this

doSomething.then(function (result) {
    console.log(result);
}).catch(function (error) {
    console.error(error);
});

or this

(async () => {
    try {
        let result = await doSomething();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();

error_log per Virtual Host?

Yes, you can try,

php_value error_log "/var/log/php_log" 

in .htaccess or you can have users use ini_set() in the beginning of their scripts if they want to have logging.

Another option would be to enable scripts to default to the php.ini in the folder with the script, then go to the user/host's root folder, then to the server's root, or something similar. This would allow hosts to add their own php.ini values and their own error_log locations.

How do I check CPU and Memory Usage in Java?

JConsole is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the NetBeans Profiler for this.

Setting Icon for wpf application (VS 08)

You can try this also:

private void Page_Loaded_1(object sender, RoutedEventArgs e)
    {
        Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
        (this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
    }

Maven Java EE Configuration Marker with Java Server Faces 1.2

I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Change it to

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                        version="3.0">
    <display-name>Archetype Created Web Application</display-name>

</web-app>

save the project, and your error would gone.

After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.

Hopefully error would be gone then.

Thanks

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

AngularJS - value attribute for select

You could modify you model to look like this:

$scope.options = {
    "AL" : "Alabama",
    "AK" : "Alaska",
    "AS" : "American Samoa"
  };

Then use

<select ng-options="k as v for (k,v) in options"></select>

how do you insert null values into sql server

INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)

Concatenating Column Values into a Comma-Separated List

You can do this using stuff:

SELECT Stuff(
    (
    SELECT ', ' + CARS.CarName
    FROM CARS
    FOR XML PATH('')
    ), 1, 2, '') AS CarNames

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

How to execute AngularJS controller function on page load?

Try this?

$scope.$on('$viewContentLoaded', function() {
    //call it here
});

Open a PDF using VBA in Excel

If it's a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

Why does an onclick property set with setAttribute fail to work in IE?

This is an amazing function for cross-browser compatible event binding.

Got it from http://js.isite.net.au/snippets/addevent

With it you can just do Events.addEvent(element, event, function); and be worry free!

For example: (http://jsfiddle.net/Zxeka/)

function hello() {
    alert('Hello');
}

var button = document.createElement('input');
button.value = "Hello";
button.type = "button";

Events.addEvent(input_0, "click", hello);

document.body.appendChild(button);

Here's the function:

// We create a function which is called immediately,
// returning the actual function object.  This allows us to
// work in a separate scope and only return the functions
// we require.
var Events = (function() {

  // For DOM2-compliant browsers.
  function addEventW3C(el, ev, f) {
    // Since IE only supports bubbling, for
    // compatibility we can't use capturing here.
    return el.addEventListener(ev, f, false);
  }

  function removeEventW3C(el, ev, f) {
    el.removeEventListener(ev, f, false);
  }

  // The function as required by IE.
  function addEventIE(el, ev, f) {
    // This is to work around a bug in IE whereby the
    // current element doesn't get passed as context.
    // We pass it via closure instead and set it as the
    // context using call().
    // This needs to be stored for removeEvent().
    // We also store the original wrapped function as a
    // property, _w.
    ((el._evts = el._evts || [])[el._evts.length]
        = function(e) { return f.call(el, e); })._w = f;

    // We prepend "on" to the event name.
    return el.attachEvent("on" + ev,
        el._evts[el._evts.length - 1]);
  }

  function removeEventIE(el, ev, f) {
    for (var evts = el._evts || [], i = evts.length; i--; )
      if (evts[i]._w === f)
        el.detachEvent("on" + ev, evts.splice(i, 1)[0]);
  }

  // A handler to call all events we've registered
  // on an element for legacy browsers.
  function addEventLegacyHandler(e) {
    var evts = this._evts[e.type];
    for (var i = 0; i < evts.length; ++i)
      if (!evts[i].call(this, e || event))
        return false;
  }

  // For older browsers.  We basically reimplement
  // attachEvent().
  function addEventLegacy(el, ev, f) {
    if (!el._evts)
      el._evts = {};

    if (!el._evts[ev])
      el._evts[ev] = [];

    el._evts[ev].push(f);

    return true;
  }

  function removeEventLegacy(el, ev, f) {
    // Loop through the handlers for this event type
    // and remove them if they match f.
    for (var evts = el._evts[ev] || [], i = evts.length; i--; )
      if (evts[i] === f)
        evts.splice(i, 1);
  }

  // Select the appropriate functions based on what's
  // available on the window object and return them.
  return window.addEventListener
      ? {addEvent: addEventW3C, removeEvent: removeEventW3C}
      : window.attachEvent
          ? {addEvent: addEventIE, removeEvent: removeEventIE}
          : {addEvent: addEventLegacy, removeEvent: removeEventLegacy};
})();

If you don't want to use such a big function, this should work for almost all browsers, including IE:

if (el.addEventListener) { 
    el.addEventListener('click', function, false); 
} else if (el.attachEvent) { 
    el.attachEvent('onclick', function); 
} 

In response to Craig's question. You're going to have to make a new element and copy over the attributes of the old element. This function should do the job: (source)

function changeInputType(oldObject, oType) {
  var newObject = document.createElement('input');
  newObject.type = oType;
  if(oldObject.size) newObject.size = oldObject.size;
  if(oldObject.value) newObject.value = oldObject.value;
  if(oldObject.name) newObject.name = oldObject.name;
  if(oldObject.id) newObject.id = oldObject.id;
  if(oldObject.className) newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild(newObject,oldObject);
  return newObject;
}

MVC 4 Razor File Upload

I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.

File properties you can find here:

MVC3 How to check if HttpPostedFileBase is an image

For example ImageApi:

[HttpPost]
[Route("api/image")]  
public ActionResult Index(HttpPostedFileBase file)  
{  
    if (file != null && file.ContentLength > 0)  
        try 
        {  
            string path = Path.Combine(Server.MapPath("~/Images"),  
               Path.GetFileName(file.FileName));

            file.SaveAs(path);  
            ViewBag.Message = "Your message for success";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = "ERROR:" + ex.Message.ToString();  
        }  
    else 
    {  
        ViewBag.Message = "Please select file";  
    }  
    return View();  
}

Hope it help.

What does "./" (dot slash) refer to in terms of an HTML file path location?

Yes, ./ means the current working directory. You can just reference the file directly by name, without it.

How do I use namespaces with TypeScript external modules?

Candy Cup Analogy

Version 1: A cup for every candy

Let's say you wrote some code like this:

Mod1.ts

export namespace A {
    export class Twix { ... }
}

Mod2.ts

export namespace A {
    export class PeanutButterCup { ... }
}

Mod3.ts

export namespace A {
     export class KitKat { ... }
}

You've created this setup: enter image description here

Each module (sheet of paper) gets its own cup named A. This is useless - you're not actually organizing your candy here, you're just adding an additional step (taking it out of the cup) between you and the treats.


Version 2: One cup in the global scope

If you weren't using modules, you might write code like this (note the lack of export declarations):

global1.ts

namespace A {
    export class Twix { ... }
}

global2.ts

namespace A {
    export class PeanutButterCup { ... }
}

global3.ts

namespace A {
     export class KitKat { ... }
}

This code creates a merged namespace A in the global scope:

enter image description here

This setup is useful, but doesn't apply in the case of modules (because modules don't pollute the global scope).


Version 3: Going cupless

Going back to the original example, the cups A, A, and A aren't doing you any favors. Instead, you could write the code as:

Mod1.ts

export class Twix { ... }

Mod2.ts

export class PeanutButterCup { ... }

Mod3.ts

export class KitKat { ... }

to create a picture that looks like this:

enter image description here

Much better!

Now, if you're still thinking about how much you really want to use namespace with your modules, read on...


These Aren't the Concepts You're Looking For

We need to go back to the origins of why namespaces exist in the first place and examine whether those reasons make sense for external modules.

Organization: Namespaces are handy for grouping together logically-related objects and types. For example, in C#, you're going to find all the collection types in System.Collections. By organizing our types into hierarchical namespaces, we provide a good "discovery" experience for users of those types.

Name Conflicts: Namespaces are important to avoid naming collisions. For example, you might have My.Application.Customer.AddForm and My.Application.Order.AddForm -- two types with the same name, but a different namespace. In a language where all identifiers exist in the same root scope and all assemblies load all types, it's critical to have everything be in a namespace.

Do those reasons make sense in external modules?

Organization: External modules are already present in a file system, necessarily. We have to resolve them by path and filename, so there's a logical organization scheme for us to use. We can have a /collections/generic/ folder with a list module in it.

Name Conflicts: This doesn't apply at all in external modules. Within a module, there's no plausible reason to have two objects with the same name. From the consumption side, the consumer of any given module gets to pick the name that they will use to refer to the module, so accidental naming conflicts are impossible.


Even if you don't believe that those reasons are adequately addressed by how modules work, the "solution" of trying to use namespaces in external modules doesn't even work.

Boxes in Boxes in Boxes

A story:

Your friend Bob calls you up. "I have a great new organization scheme in my house", he says, "come check it out!". Neat, let's go see what Bob has come up with.

You start in the kitchen and open up the pantry. There are 60 different boxes, each labelled "Pantry". You pick a box at random and open it. Inside is a single box labelled "Grains". You open up the "Grains" box and find a single box labelled "Pasta". You open the "Pasta" box and find a single box labelled "Penne". You open this box and find, as you expect, a bag of penne pasta.

Slightly confused, you pick up an adjacent box, also labelled "Pantry". Inside is a single box, again labelled "Grains". You open up the "Grains" box and, again, find a single box labelled "Pasta". You open the "Pasta" box and find a single box, this one is labelled "Rigatoni". You open this box and find... a bag of rigatoni pasta.

"It's great!" says Bob. "Everything is in a namespace!".

"But Bob..." you reply. "Your organization scheme is useless. You have to open up a bunch of boxes to get to anything, and it's not actually any more convenient to find anything than if you had just put everything in one box instead of three. In fact, since your pantry is already sorted shelf-by-shelf, you don't need the boxes at all. Why not just set the pasta on the shelf and pick it up when you need it?"

"You don't understand -- I need to make sure that no one else puts something that doesn't belong in the 'Pantry' namespace. And I've safely organized all my pasta into the Pantry.Grains.Pasta namespace so I can easily find it"

Bob is a very confused man.

Modules are Their Own Box

You've probably had something similar happen in real life: You order a few things on Amazon, and each item shows up in its own box, with a smaller box inside, with your item wrapped in its own packaging. Even if the interior boxes are similar, the shipments are not usefully "combined".

Going with the box analogy, the key observation is that external modules are their own box. It might be a very complex item with lots of functionality, but any given external module is its own box.


Guidance for External Modules

Now that we've figured out that we don't need to use 'namespaces', how should we organize our modules? Some guiding principles and examples follow.

Export as close to top-level as possible

  • If you're only exporting a single class or function, use export default:

MyClass.ts

export default class SomeType {
  constructor() { ... }
}

MyFunc.ts

function getThing() { return 'thing'; }
export default getThing;

Consumption

import t from './MyClass';
import f from './MyFunc';
var x = new t();
console.log(f());

This is optimal for consumers. They can name your type whatever they want (t in this case) and don't have to do any extraneous dotting to find your objects.

  • If you're exporting multiple objects, put them all at top-level:

MyThings.ts

export class SomeType { ... }
export function someFunc() { ... }

Consumption

import * as m from './MyThings';
var x = new m.SomeType();
var y = m.someFunc();
  • If you're exporting a large number of things, only then should you use the module/namespace keyword:

MyLargeModule.ts

export namespace Animals {
  export class Dog { ... }
  export class Cat { ... }
}
export namespace Plants {
  export class Tree { ... }
}

Consumption

import { Animals, Plants} from './MyLargeModule';
var x = new Animals.Dog();

Red Flags

All of the following are red flags for module structuring. Double-check that you're not trying to namespace your external modules if any of these apply to your files:

  • A file whose only top-level declaration is export module Foo { ... } (remove Foo and move everything 'up' a level)
  • A file that has a single export class or export function that isn't export default
  • Multiple files that have the same export module Foo { at top-level (don't think that these are going to combine into one Foo!)

GroupBy pandas DataFrame and select most common value

A slightly clumsier but faster approach for larger datasets involves getting the counts for a column of interest, sorting the counts highest to lowest, and then de-duplicating on a subset to only retain the largest cases. The code example is following:

>>> import pandas as pd
>>> source = pd.DataFrame(
        {
            'Country': ['USA', 'USA', 'Russia', 'USA'], 
            'City': ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
            'Short name': ['NY', 'New', 'Spb', 'NY']
        }
    )
>>> grouped_df = source\
        .groupby(['Country','City','Short name'])[['Short name']]\
        .count()\
        .rename(columns={'Short name':'count'})\
        .reset_index()\
        .sort_values('count', ascending=False)\
        .drop_duplicates(subset=['Country', 'City'])\
        .drop('count', axis=1)
>>> print(grouped_df)
  Country              City Short name
1     USA          New-York         NY
0  Russia  Sankt-Petersburg        Spb

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

How do I call a non-static method from a static method in C#?

Static method never allows a non-static method call directly.

Reason: Static method belongs to its class only, and to nay object or any instance.

So, whenever you try to access any non-static method from static method inside the same class: you will receive:

"An object reference is required for the non-static field, method or property".

Solution: Just declare a reference like:

public class <classname>
{
static method()
{
   new <classname>.non-static();
}

non-static method()
{

}


}

How to recognize vehicle license / number plate (ANPR) from an image?

High performance ANPR Library - http://www.dtksoft.com/dtkanpr.php. This is commercial, but they provide trial key.

include antiforgerytoken in ajax post ASP.NET MVC

Feel free to use the function below:

function AjaxPostWithAntiForgeryToken(destinationUrl, successCallback) {
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
    type: "POST",
    url: destinationUrl,
    data: { __RequestVerificationToken: token }, // Your other data will go here
    dataType: "json",
    success: function (response) {
        successCallback(response);
    },
    error: function (xhr, status, error) {
       // handle failure
    }
});

}

Can comments be used in JSON?

If your context is Node.js configuration, you might consider JavaScript via module.exports as an alternative to JSON:

module.exports = {
    "key": "value",

    // And with comments!
    "key2": "value2"
};

The require syntax will still be the same. Being JavaScript, the file extension should be .js.

How to make an ng-click event conditional?

I had this issue also and I simply found out that if you simply remove the "#" the issue goes off. Like this :

<a href="" class="disabled" ng-click="doSomething(object)">Do something</a>

How can I get the current date and time in UTC or GMT in Java?

Use this Class to get ever the right UTC Time from a Online NTP Server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NTP_UTC_Time
{
private static final String TAG = "SntpClient";

private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;

private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

private long mNtpTime;

public boolean requestTime(String host, int timeout) {
    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
        return false;
    }

    return true;
}


public long getNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */
private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */    
private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */    
private void writeTimeStamp(byte[] buffer, int offset) {        
    int ofs =  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

And use it with:

        long now = 0;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

If you need UTC Time "now" as DateTimeString use function:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

and use it with:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

How to remove an item from an array in AngularJS scope?

$scope.removeItem = function() {
    $scope.items.splice($scope.toRemove, 1);
    $scope.toRemove = null;
};

this works for me!

Codeigniter - multiple database connections

The best way is to use different database groups. If you want to keep using the master database as usual ($this->db) just turn off persistent connexion configuration option to your secondary database(s). Only master database should work with persistent connexion :

Master database

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Secondary database (notice pconnect is set to false)

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

Then you can use secondary databases as database objects while using master database as usual :

// use master dataabse
$users = $this->db->get('users');

// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());

// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

The term 'ng' is not recognized as the name of a cmdlet

Changing the policy to Unrestricted worked for me:

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

At the moment you're calling ToUniversalTime() - just get rid of that:

private long ConvertToTimestamp(DateTime value)
{
    long epoch = (value.Ticks - 621355968000000000) / 10000000;
    return epoch;
}

Alternatively, and rather more readably IMO:

private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...

private static long ConvertToTimestamp(DateTime value)
{
    TimeSpan elapsedTime = value - Epoch;
    return (long) elapsedTime.TotalSeconds;
}

EDIT: As noted in the comments, the Kind of the DateTime you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind of Utc for this to work. Unfortunately, DateTime is a bit broken in this respect - see my blog post (a rant about DateTime) for more details.

You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

React JS - Uncaught TypeError: this.props.data.map is not a function

It happens because the component is rendered before the async data arrived, you should control before to render.

I resolved it in this way:

render() {
    let partners = this.props && this.props.partners.length > 0 ?
        this.props.partners.map(p=>
            <li className = "partners" key={p.id}>
                <img src={p.img} alt={p.name}/> {p.name} </li>
        ) : <span></span>;

    return (
        <div>
            <ul>{partners}</ul>
        </div>
    );
}
  • Map can not resolve when the property is null/undefined, so I did a control first

this.props && this.props.partners.length > 0 ?

Pandas - Get first row value of a given column

In a general way, if you want to pick up the first N rows from the J column from pandas dataframe the best way to do this is:

data = dataframe[0:N][:,J]

Getting the number of filled cells in a column (VBA)

You may also use:

UsedRange.Rows.Count

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
str.codePoints().forEachOrdered(i -> System.out.print((char)i));

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

The method codePoints() also returns an IntStream as per doc:

Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

How is char and code point different? As mentioned in this article:

Unicode 3.1 added supplementary characters, bringing the total number of characters to more than the 2^16 = 65536 characters that can be distinguished by a single 16-bit char. Therefore, a char value no longer has a one-to-one mapping to the fundamental semantic unit in Unicode. JDK 5 was updated to support the larger set of character values. Instead of changing the definition of the char type, some of the new supplementary characters are represented by a surrogate pair of two char values. To reduce naming confusion, a code point will be used to refer to the number that represents a particular Unicode character, including supplementary ones.

Finally why forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

For difference between a character, a code point, a glyph and a grapheme check this question.

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

Add xmlns context with http as shown below

xmlns:context="http://www.springframework.org/schema/context"

How can I escape a double quote inside double quotes?

Check out printf...

#!/bin/bash
mystr="say \"hi\""

Without using printf

echo -e $mystr

Output: say "hi"

Using printf

echo -e $(printf '%q' $mystr)

Output: say \"hi\"

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

ng-change not working on a text input

ng-change requires ng-model,

<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">

How do I include a JavaScript script file in Angular and call a function from that script?

You can either

import * as abc from './abc';
abc.xyz();

or

import { xyz } from './abc';
xyz()

Import Libraries in Eclipse?

If you want to get this library into your library and use it, follow these steps:

  1. You can create a new folder within Eclipse by right-clicking on your project, and selecting New Folder. The library folder is traditionally called lib.

  2. Drag and drop your jar folder into the new lib folder, and when prompted select Copy Files.

  3. Selecting the Project tab at the top of the screen, and click Properties.

  4. Select Java Build Path followed by the Libraries tab.

  5. Click the Add JARs… button and select your JAR file from within the lib folder.

  6. Your JAR file will now appear in both the lib and Referenced Libraries folders. You can explore the JAR's resources by clicking Referenced Libraries.

CRON command to run URL address every 5 minutes

Nothing worked for me on my linux hosting. The only possible commands they provide are:

/usr/local/bin/php absolute/path/to/cron/script

and

/usr/local/bin/ea-php56 absolute/domain_path/path/to/cron/script 

This is how I made it to work: 1. I created simple test.php file with the following content:

echo file_get_contents('http://example.com/check/');

2. I set the cronjob with the option server gived me using absolute inner path :)

/usr/local/bin/php absolute/path/to/public_html/test.php

error: ORA-65096: invalid common user or role name in oracle

Might be, more safe alternative to "_ORACLE_SCRIPT"=true is to change "_common_user_prefix" from C## to an empty string. When it's null - any name can be used for common user. Found there.

During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).

So for me worked that:

alter system set _common_user_prefix = ''; scope=spfile;

Print debugging info from stored procedure in MySQL

Quick way to print something is:

select '** Place your mesage here' AS '** DEBUG:';

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

Where is the list of predefined Maven properties

Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}

you would find the related XML in the effective POM, such as: <project> <build> <sourceDirectory>/my/path</sourceDirectory>

Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate while in the same dir as the POM.

Setting a JPA timestamp column to be generated by the database?

I realize this is a bit late, but I've had success with annotating a timestamp column with

@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

This should also work with CURRENT_DATE and CURRENT_TIME. I'm using JPA/Hibernate with Oracle, so YMMV.

How to get a Static property with Reflection

Or just look at this...

Type type = typeof(MyClass); // MyClass is static class with static properties
foreach (var p in type.GetProperties())
{
   var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
}

Regular expression for number with length of 4, 5 or 6

Be aware that, as written, Peter's solution will "accept" 0000. If you want to validate numbers between 1000 and 999999, then that is another problem :-)

^[1-9][0-9]{3,5}$

for example will block inserting 0 at the beginning of the string.

If you want to accept 0 padding, but only up to a lengh of 6, so that 001000 is valid, then it becomes more complex. If we use look-ahead then we can write something like

^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$

This first checks if the string is long 4-6 (?=[0-9]{4,6}$), then skips the 0s 0*and search for a non-zero [1-9] followed by at least 3 digits [0-9]{3,}.

Force file download with php using header()

Based on Farhan Sahibole's answer:

        header('Content-Disposition: attachment; filename=Image.png');
        header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
        ob_clean();

        readfile($file);

This is all I needed for this to work. I stripped off anything that isn't required for this to work.

Key is to use ob_clean();

How can I call a shell command in my Perl script?

You might want to look into open2 and open3 in case you need bidirectional communication.

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

What's the easiest way to install a missing Perl module?

2 ways that I know of :

USING PPM :

With Windows (ActivePerl) I've used ppm

from the command line type ppm. At the ppm prompt ...

ppm> install foo

or

ppm> search foo

to get a list of foo modules available. Type help for all the commands

USING CPAN :

you can also use CPAN like this (*nix systems) :

perl -MCPAN -e 'shell'

gets you a prompt

cpan>

at the prompt ...

cpan> install foo  (again to install the foo module)

type h to get a list of commands for cpan

How to identify numpy types in python?

Use the builtin type function to get the type, then you can use the __module__ property to find out where it was defined:

>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True

How can I create an object based on an interface file definition in TypeScript?

Here is another approach:

You can simply create an ESLint friendly object like this

const modal: IModal = {} as IModal;

Or a default instance based on the interface and with sensible defaults, if any

const defaultModal: IModal = {
    content: "",
    form: "",
    href: "",
    $form: {} as JQuery,
    $message: {} as JQuery,
    $modal: {} as JQuery,
    $submits: {} as JQuery
};

Then variations of the default instance simply by overriding some properties

const confirmationModal: IModal = {
    ...defaultModal,     // all properties/values from defaultModal
    form: "confirmForm"  // override form only
}

How to find a number in a string using JavaScript?

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

If a reboot does not correct the problem (as suggested by Greg Hegwill's answer) then check your PATH for conflicting installation(s) of the msys-1.0.dll (and possibly other related DLLs).

In my particular situation MinGW's installation of msys has a copy of that DLL in its bin directory (<MinGW_Install_Path>\msys\1.0\bin), and it was listed in the PATH. Git's cmd directory was listed in the PATH, but its bin was not. (Git's version of msys-1.0.dll is in the bin directory. Apparently the default installation of MSys-Git does not add its bin to the PATH.)

A temporary fix was to add Git's bin directory to the PATH so that it appears before MinGW's paths. (A more permanent fix will likely involve sorting out the path conflicts between MinGW's msys and Git's and/or removing the duplicate msys installations.)

Why have header files and .cpp files?

Often you will want to have a definition of an interface without having to ship the entire code. For example, if you have a shared library, you would ship a header file with it which defines all the functions and symbols used in the shared library. Without header files, you would need to ship the source.

Within a single project, header files are used, IMHO, for at least two purposes:

  • Clarity, that is, by keeping the interfaces separate from the implementation, it is easier to read the code
  • Compile time. By using only the interface where possible, instead of the full implementation, the compile time can be reduced because the compiler can simply make a reference to the interface instead of having to parse the actual code (which, idealy, would only need to be done a single time).

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

How to add a hook to the application context initialization event?

Please follow below step to do some processing after Application Context get loaded i.e application is ready to serve.

  1. Create below annotation i.e

    @Retention(RetentionPolicy.RUNTIME) @Target(value= {ElementType.METHOD, ElementType.TYPE}) public @interface AfterApplicationReady {}

2.Create Below Class which is a listener which get call on application ready state.

    @Component
    public class PostApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {

    public static final Logger LOGGER = LoggerFactory.getLogger(PostApplicationReadyListener.class);
    public static final String MODULE = PostApplicationReadyListener.class.getSimpleName();

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            ApplicationContext context = event.getApplicationContext();
            String[] beans = context.getBeanNamesForAnnotation(AfterAppStarted.class);

            LOGGER.info("bean found with AfterAppStarted annotation are : {}", Arrays.toString(beans));

            for (String beanName : beans) {
                Object bean = context.getBean(beanName);
                Class<?> targetClass = AopUtils.getTargetClass(bean);
                Method[] methods = targetClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterAppStartedComplete.class)) {

                        LOGGER.info("Method:[{} of Bean:{}] found with AfterAppStartedComplete Annotation.", method.getName(), beanName);

                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());

                        LOGGER.info("Going to invoke method:{} of bean:{}", method.getName(), beanName);

                        currentMethod.invoke(bean);

                        LOGGER.info("Invocation compeleted method:{} of bean:{}", method.getName(), beanName);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Exception occured : ", e);
        }
    }
}

Finally when you start your Spring application just before log stating application started your listener will be called.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

This solution builds upon previous solutions, but takes into account both metric and binary units:

function formatBytes(bytes, decimals, binaryUnits) {
    if(bytes == 0) {
        return '0 Bytes';
    }
    var unitMultiple = (binaryUnits) ? 1024 : 1000; 
    var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
        ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']: 
        ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
    return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}

Examples:

formatBytes(293489203947847, 1);    // 293.5 TB
formatBytes(1234, 0);   // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true));  // 3.84 ZiB
formatBytes(4566744, 1);    // 4.6 MB
formatBytes(534, 0);    // 534 Bytes
formatBytes(273403407, 0);  // 273 MB

How can I turn a List of Lists into a List in Java 8?

Just as @Saravana mentioned:

flatmap is better but there are other ways to achieve the same

 listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
 });

To sum up, there are several ways to achieve the same as follows:

private <T> List<T> mergeOne(Stream<List<T>> listStream) {
    return listStream.flatMap(List::stream).collect(toList());
}

private <T> List<T> mergeTwo(Stream<List<T>> listStream) {
    List<T> result = new ArrayList<>();
    listStream.forEach(result::addAll);
    return result;
}

private <T> List<T> mergeThree(Stream<List<T>> listStream) {
    return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
    });
}

private <T> List<T> mergeFour(Stream<List<T>> listStream) {
    return listStream.reduce((l1, l2) -> {
        List<T> l = new ArrayList<>(l1);
        l.addAll(l2);
        return l;
    }).orElse(new ArrayList<>());
}

private <T> List<T> mergeFive(Stream<List<T>> listStream) {
    return listStream.collect(ArrayList::new, List::addAll, List::addAll);
}

Do not want scientific notation on plot axis

You can use format or formatC to, ahem, format your axis labels.

For whole numbers, try

x <- 10 ^ (1:10)
format(x, scientific = FALSE)
formatC(x, digits = 0, format = "f")

If the numbers are convertable to actual integers (i.e., not too big), you can also use

formatC(x, format = "d")

How you get the labels onto your axis depends upon the plotting system that you are using.

Detecting request type in PHP (GET, POST, PUT or DELETE)

By using

$_SERVER['REQUEST_METHOD']

Example

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request is using the POST method
}

For more details please see the documentation for the $_SERVER variable.

Constants in Kotlin -- what's a recommended way to create them?

Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.

public class DbConstants {
    companion object {
        val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        val TABLE_USER_ATTRIBUTE_DATA = "data"
    }

Instead define the constants in object.

Recommended practice :

object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
}

and access them globally like this: DbConstants.TABLE_USER_ATTRIBUTE_EMPID

Get all object attributes in Python?

I use __dict__

Example:

class MyObj(object):
  def __init__(self):
    self.name = 'Chuck Norris'
    self.phone = '+6661'

obj = MyObj()
print(obj.__dict__)

# Output:  
# {'phone': '+6661', 'name': 'Chuck Norris'}

Javascript: How to loop through ALL DOM elements on a page?

i think this is really quick

document.querySelectorAll('body,body *').forEach(function(e) {

Why does SSL handshake give 'Could not generate DH keypair' exception?

You can installing the provider dynamically:

1) Download these jars:

  • bcprov-jdk15on-152.jar
  • bcprov-ext-jdk15on-152.jar

2) Copy jars to WEB-INF/lib (or your classpath)

3) Add provider dynamically:

import org.bouncycastle.jce.provider.BouncyCastleProvider;

...

Security.addProvider(new BouncyCastleProvider());

How to use variables in SQL statement in Python?

Many ways. DON'T use the most obvious one (%s with %) in real code, it's open to attacks.

Here copy-paste'd from pydoc of sqlite3:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

More examples if you need:

# Multiple values single statement/execution
c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO'))
print c.fetchall()
c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO'))
print c.fetchall()
# This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice.
c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO')
print c.fetchall()
# Insert a single item
c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00))

How do I write output in same place on the console?

Python 2

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python 3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

PyCharm Debugger Console with Python 3

# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6

import time

print('Start.')
for i in range(100):
    time.sleep(0.02)
    print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')

vertical-align: middle with Bootstrap 2

Try removing the float attribute from span6:

{ float:none !important; }

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

onActivityResult() of MAinActivity will call , onActivityResult() of Fragement wont call because fragment is placed in Activity so obviously it come back to MainActivity

how do you increase the height of an html textbox

Don't the height and font-size CSS properties work for you ?

How to concatenate two MP4 files using FFmpeg?

I ended up using mpg as the intermediate format and it worked (NOTE this is a dangerous example, -qscale 0 will re-encode the video...)

ffmpeg -i 1.mp4 -qscale 0 1.mpg
ffmpeg -i 2.mp4 -qscale 0 2.mpg
cat 1.mpg 2.mpg | ffmpeg -f mpeg -i - -qscale 0 -vcodec mpeg4 output.mp4

UIButton: set image for selected-highlighted state

You can do this in Interface Builder.

Select the UIButton you wish to set in IB then go to the attributes inspector.

In the screen shots,I am using a custom button type , but that does not matter.

Custom Default

enter image description here

enter image description here

Count all duplicates of each value

If you want to check repetition more than 1 in descending order then implement below query.

SELECT   duplicate_data,COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
HAVING   COUNT(duplicate_data) > 1
ORDER BY COUNT(duplicate_data) DESC

If want simple count query.

SELECT   COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
ORDER BY COUNT(duplicate_data) DESC

SELECT FOR UPDATE with SQL Server

I solved the rowlock problem in a completely different way. I realized that sql server was not able to manage such a lock in a satisfying way. I choosed to solve this from a programatically point of view by the use of a mutex... waitForLock... releaseLock...

Calculating a directory's size using Python?

For the second part of the question

def human(size):

    B = "B"
    KB = "KB" 
    MB = "MB"
    GB = "GB"
    TB = "TB"
    UNITS = [B, KB, MB, GB, TB]
    HUMANFMT = "%f %s"
    HUMANRADIX = 1024.

    for u in UNITS[:-1]:
        if size < HUMANRADIX : return HUMANFMT % (size, u)
        size /= HUMANRADIX

    return HUMANFMT % (size,  UNITS[-1])

How to hide Table Row Overflow?

Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53

Just define width of the table and width for each table cell

something like

table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}

It works like a charm :o)

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

START_STICKY and START_NOT_STICKY

The documentation for START_STICKY and START_NOT_STICKY is quite straightforward.

START_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Example: Local Service Sample

START_NOT_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Example: ServiceStartArguments.java

Duplicate AssemblyVersion Attribute

I came across the same when tried add GitVersion tool to update my version in AssemblyInfo.cs. Use VS2017 and .NET Core project. So I just mixed both worlds. My AssemblyInfo.cs contains only version info that was generated by GitVersion tool, my csproj contains remaingin things. Please note I don't use <GenerateAssemblyInfo>false</GenerateAssemblyInfo> I use attributes related to version only (see below). More details here AssemblyInfo properties.

AssemblyInfo.cs

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+13.Branch.master.Sha.119c35af0f529e92e0f75a5e6d8373912d457818")]

my.csproj contains all related to other assemblyu attributes:

<PropertyGroup>
...
<Company>SOME Company </Company>
<Authors>Some Authors</Authors>
<Product>SOME Product</Product>
...
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>

csproj maps to package tab at project properties

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

How to remove entry from $PATH on mac

On MAC OS X Leopard and higher

cd /etc/paths.d

There may be a text file in the above directory that contains the path you are trying to remove.

vim textfile //check and see what is in it when you are done looking type :q 
//:q just quits, no saves

If its the one you want to remove do this

rm textfile //remove it, delete it

Here is a link to a site that has more info on it, even though it illustrates 'adding' the path. However, you may gain some insight.

How to compare two Dates without the time portion?

My preference would be to use the Joda library insetad of java.util.Date directly, as Joda makes a distinction between date and time (see YearMonthDay and DateTime classes).

However, if you do wish to use java.util.Date I would suggest writing a utility method; e.g.

public static Date setTimeToMidnight(Date date) {
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( date );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

filedialog, tkinter and opening files

I had to specify individual commands first and then use the * to bring all in command.

from tkinter import filedialog
from tkinter import *

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

Concatenate strings from several rows using Pandas groupby

The answer by EdChum provides you with a lot of flexibility but if you just want to concateate strings into a column of list objects you can also:

output_series = df.groupby(['name','month'])['text'].apply(list)

hardcoded string "row three", should use @string resource

A good practice is write text inside String.xml

example:

String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

and inside layout:

<TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/yellow" />

jQuery - Trigger event when an element is removed from the DOM

I like mtkopone's answer using jQuery special events, but note that it doesn't work a) when elements are detached instead of removed or b) when some old non-jquery libraries use innerHTML to destroy your elements

Java: Get month Integer from Date

java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

Metadata file '.dll' could not be found

In my case it was caused by a .NET Framework version mismatch.

One project was 3.5 and the other referencing project 4.6.1.