Programs & Examples On #Opensoundcontrol

Open Sound Control (OSC) is a protocol for communication among computers, sound synthesizers, and other multimedia devices that is optimized for modern networking technology.

Spring MVC @PathVariable with dot (.) is getting truncated

Finally I found solution in Spring Docs:

To completely disable the use of file extensions, you must set both of the following:

 useSuffixPatternMatching(false), see PathMatchConfigurer

 favorPathExtension(false), see ContentNegotiationConfigurer

Adding this to my WebMvcConfigurerAdapter implementation solved the problem:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false);
}

@Override
public void configurePathMatch(PathMatchConfigurer matcher) {
    matcher.setUseSuffixPatternMatch(false);
}

How to randomize (shuffle) a JavaScript array?

var shuffledArray = function(inpArr){
    //inpArr - is input array
    var arrRand = []; //this will give shuffled array
    var arrTempInd = []; // to store shuffled indexes
    var max = inpArr.length;
    var min = 0;
    var tempInd;
    var i = 0;

    do{
        //generate random index between range
        tempInd = Math.floor(Math.random() * (max - min));
        //check if index is already available in array to avoid repetition
        if(arrTempInd.indexOf(tempInd)<0){
            //push character at random index
            arrRand[i] = inpArr[tempInd];
            //push random indexes
            arrTempInd.push(tempInd);
            i++;
        }
    }
    // check if random array length is equal to input array length
    while(arrTempInd.length < max){
        return arrRand; // this will return shuffled Array
    }
};

Just pass the array to function and in return get the shuffled array

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Here is solution for Hibernate 4.3.7.Final.

pacakge-info.java contains

@TypeDefs(
    {
        @TypeDef(
                name = "javaUtilDateType",
                defaultForType = java.util.Date.class,
                typeClass = JavaUtilDateType.class
        )
    })
package some.pack;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

And JavaUtilDateType:

package some.other.or.same.pack;

import java.sql.Timestamp;
import java.util.Comparator;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.VersionType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor;
import org.hibernate.type.descriptor.sql.TimestampTypeDescriptor;

/**
 * Note: Depends on hibernate implementation details hibernate-core-4.3.7.Final.
 *
 * @see
 * <a href="http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom">Hibernate
 * Documentation</a>
 * @see TimestampType
 */
public class JavaUtilDateType
        extends AbstractSingleColumnStandardBasicType<Date>
        implements VersionType<Date>, LiteralType<Date> {

    public static final TimestampType INSTANCE = new TimestampType();

    public JavaUtilDateType() {
        super(
                TimestampTypeDescriptor.INSTANCE,
                new JdbcTimestampTypeDescriptor() {

                    @Override
                    public Date fromString(String string) {
                        return new Date(super.fromString(string).getTime());
                    }

                    @Override
                    public <X> Date wrap(X value, WrapperOptions options) {
                        return new Date(super.wrap(value, options).getTime());
                    }

                }
        );
    }

    @Override
    public String getName() {
        return "timestamp";
    }

    @Override
    public String[] getRegistrationKeys() {
        return new String[]{getName(), Timestamp.class.getName(), java.util.Date.class.getName()};
    }

    @Override
    public Date next(Date current, SessionImplementor session) {
        return seed(session);
    }

    @Override
    public Date seed(SessionImplementor session) {
        return new Timestamp(System.currentTimeMillis());
    }

    @Override
    public Comparator<Date> getComparator() {
        return getJavaTypeDescriptor().getComparator();
    }

    @Override
    public String objectToSQLString(Date value, Dialect dialect) throws Exception {
        final Timestamp ts = Timestamp.class.isInstance(value)
                ? (Timestamp) value
                : new Timestamp(value.getTime());
        // TODO : use JDBC date literal escape syntax? -> {d 'date-string'} in yyyy-mm-dd hh:mm:ss[.f...] format
        return StringType.INSTANCE.objectToSQLString(ts.toString(), dialect);
    }

    @Override
    public Date fromStringValue(String xml) throws HibernateException {
        return fromString(xml);
    }
}

This solution mostly relies on TimestampType implementation with adding additional behaviour through anonymous class of type JdbcTimestampTypeDescriptor.

Page redirect with successful Ajax request

In your mail3.php file you should trap errors in a try {} catch {}

try {
    /*code here for email*/
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
}

Then in your success call you wont have to worry about your errors, because it will never return as a success.

and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.

Laravel: Get base url

I found an other way to just get the base url to to display the value of environment variable APP_URL

env('APP_URL')

which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).

Cannot issue data manipulation statements with executeQuery()

This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}

What's the best way to use R scripts on the command line (terminal)?

If you are interested in parsing command line arguments to an R script try RScript which is bundled with R as of version 2.5.x

http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html

map vs. hash_map in C++

map is implemented from balanced binary search tree(usually a rb_tree), since all the member in balanced binary search tree is sorted so is map;

hash_map is implemented from hashtable.Since all the member in hashtable is unsorted so the members in hash_map(unordered_map) is not sorted.

hash_map is not a c++ standard library, but now it renamed to unordered_map(you can think of it renamed) and becomes c++ standard library since c++11 see this question Difference between hash_map and unordered_map? for more detail.

Below i will give some core interface from source code of how the two type map is implemented.

map:

The below code is just to show that, map is just a wrapper of an balanced binary search tree, almost all it's function is just invoke the balanced binary search tree function.

template <typename Key, typename Value, class Compare = std::less<Key>>
class map{
    // used for rb_tree to sort
    typedef Key    key_type;

    // rb_tree node value
    typedef std::pair<key_type, value_type> value_type;

    typedef Compare key_compare;

    // as to map, Key is used for sort, Value used for store value
    typedef rb_tree<key_type, value_type, key_compare> rep_type;

    // the only member value of map (it's  rb_tree)
    rep_type t;
};

// one construct function
template<typename InputIterator>
map(InputIterator first, InputIterator last):t(Compare()){
        // use rb_tree to insert value(just insert unique value)
        t.insert_unique(first, last);
}

// insert function, just use tb_tree insert_unique function
//and only insert unique value
//rb_tree insertion time is : log(n)+rebalance
// so map's  insertion time is also : log(n)+rebalance 
typedef typename rep_type::const_iterator iterator;
std::pair<iterator, bool> insert(const value_type& v){
    return t.insert_unique(v);
};

hash_map:

hash_map is implemented from hashtable whose structure is somewhat like this:

enter image description here

In the below code, i will give the main part of hashtable, and then gives hash_map.

// used for node list
template<typename T>
struct __hashtable_node{
    T val;
    __hashtable_node* next;
};

template<typename Key, typename Value, typename HashFun>
class hashtable{
    public:
        typedef size_t   size_type;
        typedef HashFun  hasher;
        typedef Value    value_type;
        typedef Key      key_type;
    public:
        typedef __hashtable_node<value_type> node;

        // member data is buckets array(node* array)
        std::vector<node*> buckets;
        size_type num_elements;

        public:
            // insert only unique value
            std::pair<iterator, bool> insert_unique(const value_type& obj);

};

Like map's only member is rb_tree, the hash_map's only member is hashtable. It's main code as below:

template<typename Key, typename Value, class HashFun = std::hash<Key>>
class hash_map{
    private:
        typedef hashtable<Key, Value, HashFun> ht;

        // member data is hash_table
        ht rep;

    public:
        // 100 buckets by default
        // it may not be 100(in this just for simplify)
        hash_map():rep(100){};

        // like the above map's insert function just invoke rb_tree unique function
        // hash_map, insert function just invoke hashtable's unique insert function
        std::pair<iterator, bool> insert(const Value& v){
                return t.insert_unique(v);
        };

};

Below image shows when a hash_map have 53 buckets, and insert some values, it's internal structure.

enter image description here

The below image shows some difference between map and hash_map(unordered_map), the image comes from How to choose between map and unordered_map?:

enter image description here

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

Why would I use dirname(__FILE__) in an include or include_once statement?

If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.

Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.

How to check if a column exists before adding it to an existing table in PL/SQL?

To check column exists

select column_name as found
from user_tab_cols
where table_name = '__TABLE_NAME__'
and column_name = '__COLUMN_NAME__'

Reference link

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

Confirm deletion in modal / dialog using Twitter Bootstrap?

  // ---------------------------------------------------------- Generic Confirm  

  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal hide fade">' +    
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    });

    confirmModal.modal('show');     
  };

  // ---------------------------------------------------------- Confirm Put To Use

  $("i#deleteTransaction").live("click", function(event) {
    // get txn id from current table row
    var id = $(this).data('id');

    var heading = 'Confirm Transaction Delete';
    var question = 'Please confirm that you wish to delete transaction ' + id + '.';
    var cancelButtonTxt = 'Cancel';
    var okButtonTxt = 'Confirm';

    var callback = function() {
      alert('delete confirmed ' + id);
    };

    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

  });

Android studio doesn't list my phone under "Choose Device"

I solved the problem like that: go to Run and Select Clean and Rerun.

Missing Authentication Token while accessing API Gateway?

I just had the same issue and it seems it also shows this message if the resource cannot be found.

In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.

did you specify the right host or port? error on Kubernetes

The issue is that your kubeconfig is not right. To auto-generate it run:

gcloud container clusters get-credentials "CLUSTER NAME"

This worked for me.

Removing "NUL" characters

I was having same problem. The above put me on the right track but was not quite correct in my case. What did work was closely related:

  • Open your file in Notepad++
  • Type Control-A (select all)
  • Type Control-H (replace)
  • In 'Find What' type \x00
  • In 'Replace With' leave BLANK
  • In 'Search Mode' Selected 'Extended'
  • Then Click on 'Replace All'

Retrofit 2: Get JSON from Response body

use this

response.body().get(0).getUsername().toString();

pass **kwargs argument to another function with **kwargs

In the second example you provide 3 arguments: filename, mode and a dictionary (kwargs). But Python expects: 2 formal arguments plus keyword arguments.

By prefixing the dictionary by '**' you unpack the dictionary kwargs to keywords arguments.

A dictionary (type dict) is a single variable containing key-value pairs.

"Keyword arguments" are key-value method-parameters.

Any dictionary can by unpacked to keyword arguments by prefixing it with ** during function call.

How to pipe list of files returned by find command to cat to view all the files

There are a few ways to pass the list of files returned by the find command to the cat command, though technically not all use piping, and none actually pipe directly to cat.

  1. The simplest is to use backticks (`):

    cat `find [whatever]`
    

    This takes the output of find and effectively places it on the command line of cat. This doesn't work well if find has too much output (more than can fit on a command-line) or if the output has special characters (like spaces).

  2. In some shells, including bash, one can use $() instead of backticks :

    cat $(find [whatever])
    

    This is less portable, but is nestable. Aside from that, it has pretty much the same caveats as backticks.

  3. Because running other commands on what was found is a common use for find, find has an -exec action which executes a command for each file it finds:

    find [whatever] -exec cat {} \;
    

    The {} is a placeholder for the filename, and the \; marks the end of the command (It's possible to have other actions after -exec.)

    This will run cat once for every single file rather than running a single instance of cat passing it multiple filenames which can be inefficient and might not have the behavior you want for some commands (though it's fine for cat). The syntax is also a awkward to type -- you need to escape the semicolon because semicolon is special to the shell!

  4. Some versions of find (most notably the GNU version) let you replace ; with + to use -exec's append mode to run fewer instances of cat:

    find [whatever] -exec cat {} +
    

    This will pass multiple filenames to each invocation of cat, which can be more efficient.

    Note that this is not guaranteed to use a single invocation, however. If the command line would be too long then the arguments are spread across multiple invocations of cat. For cat this is probably not a big deal, but for some other commands this may change the behavior in undesirable ways. On Linux systems, the command line length limit is quite large, so splitting into multiple invocations is quite rare compared to some other OSes.

  5. The classic/portable approach is to use xargs:

    find [whatever] | xargs cat
    

    xargs runs the command specified (cat, in this case), and adds arguments based on what it reads from stdin. Just like -exec with +, this will break up the command-line if necessary. That is, if find produces too much output, it'll run cat multiple times. As mentioned in the section about -exec earlier, there are some commands where this splitting may result in different behavior. Note that using xargs like this has issues with spaces in filenames, as xargs just uses whitespace as a delimiter.

  6. The most robust, portable, and efficient method also uses xargs:

    find [whatever] -print0 | xargs -0 cat
    

    The -print0 flag tells find to use \0 (null character) delimiters between filenames, and the -0 flag tells xargs to expect these \0 delimiters. This has pretty much identical behavior to the -exec...+ approach, though is more portable (but unfortunately more verbose).

Enable CORS in Web API 2

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

How to disable horizontal scrolling of UIScrollView?

Introduced in iOS 11 is a new property on UIScrollView

var contentLayoutGuide: UILayoutGuide

The documentation states that you:

Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.

Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)

example:

NSLayoutConstraint.activate([
  scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
])

Documentation: https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

Getting a map() to return a list in Python 3.x

Using list comprehension in python and basic map function utility, one can do this also:

chi = [x for x in map(chr,[66,53,0,94])]

How to keep two folders automatically synchronized?

Just simple modification of @silgon answer:

while true; do 
  inotifywait -r -e modify,create,delete /directory
  rsync -avz /directory /target
done

(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)

How I could add dir to $PATH in Makefile?

Did you try export directive of Make itself (assuming that you use GNU Make)?

export PATH := bin:$(PATH)

test all:
    x

Also, there is a bug in you example:

test all:
    PATH=bin:${PATH}
    @echo $(PATH)
    x

First, the value being echoed is an expansion of PATH variable performed by Make, not the shell. If it prints the expected value then, I guess, you've set PATH variable somewhere earlier in your Makefile, or in a shell that invoked Make. To prevent such behavior you should escape dollars:

test all:
    PATH=bin:$$PATH
    @echo $$PATH
    x

Second, in any case this won't work because Make executes each line of the recipe in a separate shell. This can be changed by writing the recipe in a single line:

test all:
    export PATH=bin:$$PATH; echo $$PATH; x

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

Generating 8-character only UUIDs

It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings (see the other answers).

Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs).

What does [object Object] mean?

Consider the following example:

const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);

Which outputs

[object bar]

Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.

Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".

Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.

Underline text in UIlabel

An enhanced version of the code of Kovpas (color and line size)

@implementation UILabelUnderlined

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

    CGContextSetLineWidth(ctx, 1.0f);

    CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];

    CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
    CGContextAddLineToPoint(ctx, tmpSize.width, self.bounds.size.height - 1);

    CGContextStrokePath(ctx);

    [super drawRect:rect];  
}

@end

How to join two sets in one line without using "|"

You could use or_ alias:

>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I tried this and it works without any issues to validate if the field is empty. I have answered your question partially as I haven't personally tried to add default values to attributes

if(field.getText()!= null && !field.getText().isEmpty())

Hope it helps

Create two-dimensional arrays and access sub-arrays in Ruby

a = Array.new(Array.new(4))

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    a[i[j]] = 1
  end
end

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    print a[i[j]] = 1 #It's not a[i][j], but a[i[j]]
  end
  puts "\n"
end

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

Concatenate two char* strings in a C program

Here is a working solution:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) 
{
      char str1[16];
      char str2[16];
      strcpy(str1, "sssss");
      strcpy(str2, "kkkk");
      strcat(str1, str2);
      printf("%s", str1);
      return 0;
}

Output:

ssssskkkk

You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:

After declaration (both are empty): 
str1: [][][][][][][][][][][][][][][][][][][][] 
str2: [][][][][][][][][][][][][][][][][][][][]

After calling strcpy (\0 is the string terminator zero byte): 
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

After calling strcat: 
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

How to add an element to the beginning of an OrderedDict?

There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend() method/function that operates on the OrderedDict internals with O(1) complexity.

For Python 3.2 and later, you should use the move_to_end method. The method accepts a last argument which indicates whether the element will be moved to the bottom (last=True) or the top (last=False) of the OrderedDict.

Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict from scratch.

Details for the four different solutions:


Extend OrderedDict and add a new instance method

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def prepend(self, key, value, dict_setitem=dict.__setitem__):

        root = self._OrderedDict__root
        first = root[1]

        if key in self:
            link = self._OrderedDict__map[key]
            link_prev, link_next, _ = link
            link_prev[1] = link_next
            link_next[0] = link_prev
            link[0] = root
            link[1] = first
            root[1] = first[0] = link
        else:
            root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
            dict_setitem(self, key, value)

Demo:

>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])

Standalone function that manipulates OrderedDict objects

This function does the same thing by accepting the dict object, key and value. I personally prefer the class:

from collections import OrderedDict

def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
    root = dct._OrderedDict__root
    first = root[1]

    if key in dct:
        link = dct._OrderedDict__map[key]
        link_prev, link_next, _ = link
        link_prev[1] = link_next
        link_next[0] = link_prev
        link[0] = root
        link[1] = first
        root[1] = first[0] = link
    else:
        root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
        dict_setitem(dct, key, value)

Demo:

>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])

Use OrderedDict.move_to_end() (Python >= 3.2)

Python 3.2 introduced the OrderedDict.move_to_end() method. Using it, we can move an existing key to either end of the dictionary in O(1) time.

>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])

If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend() wrapper (not presented here).


Create a new OrderedDict - slow!!!

If you don't want to do that and performance is not an issue then easiest way is to create a new dict:

from itertools import chain, ifilterfalse
from collections import OrderedDict


def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)])   #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
                                           unique_everseen(chain(d2, d1)))
print new_dic

output:

OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

Difference between string and StringBuilder in C#

String

A String instance is immutable, that is, we cannot change it after it was created. If we perform any operation on a String it will return a new instance (creates a new instance in memory) instead of modifying the existing instance value.

StringBuilder

StringBuilder is mutable, that is, if we perform any operation on StringBuilder it will update the existing instance value and it will not create new instance.

Difference between String and StringBuilder

What does the 'static' keyword do in a class?

static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page

Adding an external directory to Tomcat classpath

See also question: Can I create a custom classpath on a per application basis in Tomcat

Tomcat 7 Context hold Loader element. According to docs deployment descriptor (what in <Context> tag) can be placed in:

  • $CATALINA_BASE/conf/server.xml - bad - require server restarts in order to reread config
  • $CATALINA_BASE/conf/context.xml - bad - shared across all applications
  • $CATALINA_BASE/work/$APP.war:/META-INF/context.xml - bad - require repackaging in order to change config
  • $CATALINA_BASE/work/[enginename]/[hostname]/$APP/META-INF/context.xml - nice, but see last option!!
  • $CATALINA_BASE/webapps/$APP/META-INF/context.xml - nice, but see last option!!
  • $CATALINA_BASE/conf/[enginename]/[hostname]/$APP.xml - best - completely out of application and automatically scanned for changes!!!

Here my config which demonstrate how to use development version of project files out of $CATALINA_BASE hierarchy (note that I place this file into src/test/resources dir and intruct Maven to preprocess ${basedir} placeholders through pom.xml <filtering>true</filtering> so after build in new environment I copy it to $CATALINA_BASE/conf/Catalina/localhost/$APP.xml):

<Context docBase="${basedir}/src/main/webapp"
         reloadable="true">
    <!-- http://tomcat.apache.org/tomcat-7.0-doc/config/context.html -->
    <Resources className="org.apache.naming.resources.VirtualDirContext"
               extraResourcePaths="/WEB-INF/classes=${basedir}/target/classes,/WEB-INF/lib=${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <Loader className="org.apache.catalina.loader.VirtualWebappLoader"
            virtualClasspath="${basedir}/target/classes;${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <JarScanner scanAllDirectories="true"/>

    <!-- Use development version of JS/CSS files. -->
    <Parameter name="min" value="dev"/>
    <Environment name="app.devel.ldap" value="USER" type="java.lang.String" override="true"/>
    <Environment name="app.devel.permitAll" value="true" type="java.lang.String" override="true"/>
</Context>

UPDATE Tomcat 8 change syntax for <Resources> and <Loader> elements, corresponding part now look like:

<Resources>
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/classes" base="${basedir}/target/classes" />
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/lib" base="${basedir}/target/${project.build.finalName}/WEB-INF/lib" />
</Resources>

`export const` vs. `export default` in ES6

From the documentation:

Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.

Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.

Java: Integer equals vs. ==

Integer refers to the reference, that is, when comparing references you're comparing if they point to the same object, not value. Hence, the issue you're seeing. The reason it works so well with plain int types is that it unboxes the value contained by the Integer.

May I add that if you're doing what you're doing, why have the if statement to begin with?

mismatch = ( cdiCt != null && cdsCt != null && !cdiCt.equals( cdsCt ) );

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

Python Remove last 3 characters of a string

Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

The problem is that the file name should be Dockerfile and not DockerFile or dockerfile it should be D capital followed by ockerfile in lower-case pls note

Delete a closed pull request from GitHub

5 step to do what you want if you made the pull request from a forked repository:

  1. reopen the pull request
  2. checkout to the branch which you made the pull request
  3. reset commit to the last master commit(that means remove all you new code)
  4. git push --force
  5. delete your forked repository which made the pull request

And everything is done, good luck!

How can I change my Cygwin home folder after installation?

I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.

@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL

This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.

Visual Studio : short cut Key : Duplicate Line

The command you want is Edit.Duplicate. It is mapped to CtrlE, CtrlV. This will not overwrite your clipboard.

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

How to force Selenium WebDriver to click on element which is not currently visible?

I had a similar issue, but it was related to the element not being visible in the viewport. I took a screenshot and realized the browser window was too narrow and the element couldn't be seen. I did one of these and it worked:

driver.maximize_window()

See: WebDriver.maximize_window()

How to print a percentage value in python?

Just to add Python 3 f-string solution

prob = 1.0/3.0
print(f"{prob:.0%}")

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

c# razor url parameter from view

@(ViewContext.RouteData.Values["parameterName"])

worked with ROUTE PARAM.

Request.Params["paramName"]

did not work with ROUTE PARAM.

How to get length of a list of lists in python

You can do it with reduce:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

What does the restrict keyword mean in C++?

As others said, if means nothing as of C++14, so let's consider the __restrict__ GCC extension which does the same as the C99 restrict.

C99

restrict says that two pointers cannot point to overlapping memory regions. The most common usage is for function arguments.

This restricts how the function can be called, but allows for more compile optimizations.

If the caller does not follow the restrict contract, undefined behavior.

The C99 N1256 draft 6.7.3/7 "Type qualifiers" says:

The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

and 6.7.3.1 "Formal definition of restrict" gives the gory details.

A possible optimization

The Wikipedia example is very illuminating.

It clearly shows how as it allows to save one assembly instruction.

Without restrict:

void f(int *a, int *b, int *x) {
  *a += *x;
  *b += *x;
}

Pseudo assembly:

load R1 ? *x    ; Load the value of x pointer
load R2 ? *a    ; Load the value of a pointer
add R2 += R1    ; Perform Addition
set R2 ? *a     ; Update the value of a pointer
; Similarly for b, note that x is loaded twice,
; because x may point to a (a aliased by x) thus 
; the value of x will change when the value of a
; changes.
load R1 ? *x
load R2 ? *b
add R2 += R1
set R2 ? *b

With restrict:

void fr(int *restrict a, int *restrict b, int *restrict x);

Pseudo assembly:

load R1 ? *x
load R2 ? *a
add R2 += R1
set R2 ? *a
; Note that x is not reloaded,
; because the compiler knows it is unchanged
; "load R1 ? *x" is no longer needed.
load R2 ? *b
add R2 += R1
set R2 ? *b

Does GCC really do it?

g++ 4.8 Linux x86-64:

g++ -g -std=gnu++98 -O0 -c main.cpp
objdump -S main.o

With -O0, they are the same.

With -O3:

void f(int *a, int *b, int *x) {
    *a += *x;
   0:   8b 02                   mov    (%rdx),%eax
   2:   01 07                   add    %eax,(%rdi)
    *b += *x;
   4:   8b 02                   mov    (%rdx),%eax
   6:   01 06                   add    %eax,(%rsi)  

void fr(int *__restrict__ a, int *__restrict__ b, int *__restrict__ x) {
    *a += *x;
  10:   8b 02                   mov    (%rdx),%eax
  12:   01 07                   add    %eax,(%rdi)
    *b += *x;
  14:   01 06                   add    %eax,(%rsi) 

For the uninitiated, the calling convention is:

  • rdi = first parameter
  • rsi = second parameter
  • rdx = third parameter

GCC output was even clearer than the wiki article: 4 instructions vs 3 instructions.

Arrays

So far we have single instruction savings, but if pointer represent arrays to be looped over, a common use case, then a bunch of instructions could be saved, as mentioned by supercat and michael.

Consider for example:

void f(char *restrict p1, char *restrict p2, size_t size) {
     for (size_t i = 0; i < size; i++) {
         p1[i] = 4;
         p2[i] = 9;
     }
 }

Because of restrict, a smart compiler (or human), could optimize that to:

memset(p1, 4, size);
memset(p2, 9, size);

Which is potentially much more efficient as it may be assembly optimized on a decent libc implementation (like glibc) Is it better to use std::memcpy() or std::copy() in terms to performance?, possibly with SIMD instructions.

Without, restrict, this optimization could not be done, e.g. consider:

char p1[4];
char *p2 = &p1[1];
f(p1, p2, 3);

Then for version makes:

p1 == {4, 4, 4, 9}

while the memset version makes:

p1 == {4, 9, 9, 9}

Does GCC really do it?

GCC 5.2.1.Linux x86-64 Ubuntu 15.10:

gcc -g -std=c99 -O0 -c main.c
objdump -dr main.o

With -O0, both are the same.

With -O3:

  • with restrict:

    3f0:   48 85 d2                test   %rdx,%rdx
    3f3:   74 33                   je     428 <fr+0x38>
    3f5:   55                      push   %rbp
    3f6:   53                      push   %rbx
    3f7:   48 89 f5                mov    %rsi,%rbp
    3fa:   be 04 00 00 00          mov    $0x4,%esi
    3ff:   48 89 d3                mov    %rdx,%rbx
    402:   48 83 ec 08             sub    $0x8,%rsp
    406:   e8 00 00 00 00          callq  40b <fr+0x1b>
                            407: R_X86_64_PC32      memset-0x4
    40b:   48 83 c4 08             add    $0x8,%rsp
    40f:   48 89 da                mov    %rbx,%rdx
    412:   48 89 ef                mov    %rbp,%rdi
    415:   5b                      pop    %rbx
    416:   5d                      pop    %rbp
    417:   be 09 00 00 00          mov    $0x9,%esi
    41c:   e9 00 00 00 00          jmpq   421 <fr+0x31>
                            41d: R_X86_64_PC32      memset-0x4
    421:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)
    428:   f3 c3                   repz retq
    

    Two memset calls as expected.

  • without restrict: no stdlib calls, just a 16 iteration wide loop unrolling which I do not intend to reproduce here :-)

I haven't had the patience to benchmark them, but I believe that the restrict version will be faster.

Strict aliasing rule

The restrict keyword only affects pointers of compatible types (e.g. two int*) because the strict aliasing rules says that aliasing incompatible types is undefined behavior by default, and so compilers can assume it does not happen and optimize away.

See: What is the strict aliasing rule?

Does it work for references?

According to the GCC docs it does: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Restricted-Pointers.html with syntax:

int &__restrict__ rref

There is even a version for this of member functions:

void T::fn () __restrict__

Get Line Number of certain phrase in file Python

listStr = open("file_name","mode")

if "search element" in listStr:
    print listStr.index("search element")  # This will gives you the line number

Android Push Notifications: Icon not displaying in notification, white square shown instead

I found a link where we can generate our own white icon,

try this link to generate white icon of your launcher icon.

Open this Link and upload your ic_launcher or notification icon

Evenly space multiple views within a container view

Another approach might be to have the top and bottom labels have constraints relative to the view top and bottom, respectively, and have the middle view have top and bottom constraints relative to the first and third view, respectively.

Note that you have more control over constraints than it might seem by dragging views close to one another until guiding dashed lines appear - these indicate constraints between the two objects that will be formed instead of between the object and the superview.

In this case you would then want to alter the constraints to be "Greater than or equal to" the desired value, instead of "equal to" to allow them to resize. Not sure if this will do exactly what you want.

SQL query return data from multiple tables

Hopes this makes it find the tables as you're reading through the thing:

jsfiddle

mysql> show columns from colors;                                                         
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+           
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

When should I use GC.SuppressFinalize()?

Dispose(true);
GC.SuppressFinalize(this);

If object has finalizer, .net put a reference in finalization queue.

Since we have call Dispose(ture), it clear object, so we don't need finalization queue to do this job.

So call GC.SuppressFinalize(this) remove reference in finalization queue.

How to Replace Multiple Characters in SQL?

Here are the steps

  1. Create a CLR function

See following code:

public partial class UserDefinedFunctions 
{

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Replace2(SqlString inputtext, SqlString filter,SqlString      replacewith)
{

    string str = inputtext.ToString();
    try
    {
        string pattern = (string)filter;
        string replacement = (string)replacewith;
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(str, replacement);
        return (SqlString)result;

    }
    catch (Exception s)
    {
        return (SqlString)s.Message;
    }
}
}
  1. Deploy your CLR function

  2. Now Test it

See following code:

create table dbo.test(dummydata varchar(255))
Go
INSERT INTO dbo.test values('P@ssw1rd'),('This 12is @test')
Go
Update dbo.test
set dummydata=dbo.Replace2(dummydata,'[0-9@]','')

select * from dbo.test
dummydata, Psswrd, This is test booom!!!!!!!!!!!!!

Html- how to disable <a href>?

.disabledLink.disabled {pointer-events:none;}

That should do it hope I helped!

Search all the occurrences of a string in the entire project in Android Studio

TLDR: ??F on MacOS will open "Find in path" dialog.

First of all, this IDEA has a nice "Find Usages" command. It can be found in the context menu, when the cursor is on some field, method, etc.

It's context-aware, and as far as I know, is the best way to find class, method or field usage.

Alternatively, you can use the

Edit > Find > Find in path…

dialog, which allows you to search the whole workspace.

Also in IDEA 13 there is an awesome "Search Everywhere" option, by default called by double Shift. It allows you to search in project, files, classes, settings, and so on.

Also you can search from Project Structure dialog with "Find in Path…". Just call it by right mouse button on concrete directory and the search will be scoped, only inside that directory and it's sub-directory.

Enjoy!

How to convert UTF8 string to byte array?

Assuming the question is about a DOMString as input and the goal is to get an Array, that when interpreted as string (e.g. written to a file on disk), would be UTF-8 encoded:

Now that nearly all modern browsers support Typed Arrays, it'd be ashamed if this approach is not listed:

  • According to the W3C, software supporting the File API should accept DOMStrings in their Blob constructor (see also: String encoding when constructing a Blob)
  • Blobs can be converted to an ArrayBuffer using the .readAsArrayBuffer() function of a File Reader
  • Using a DataView or constructing a Typed Array with the buffer read by the File Reader, one can access every single byte of the ArrayBuffer

Example:

// Create a Blob with an Euro-char (U+20AC)
var b = new Blob(['€']);
var fr = new FileReader();

fr.onload = function() {
    ua = new Uint8Array(fr.result);
    // This will log "3|226|130|172"
    //                  E2  82  AC
    // In UTF-16, it would be only 2 bytes long
    console.log(
        fr.result.byteLength + '|' + 
        ua[0]  + '|' + 
        ua[1] + '|' + 
        ua[2] + ''
    );
};
fr.readAsArrayBuffer(b);

Play with that on JSFiddle. I haven't benchmarked this yet but I can imagine this being efficient for large DOMStrings as input.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will not "grayout" the textbox and will still submit the value on a postback.

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

Get current controller in view

Just use:

ViewContext.Controller.GetType().Name

This will give you the whole Controller's Name

Assign static IP to Docker container

For docker-compose you can use following docker-compose.yml

version: '2'
services:
  nginx:
    image: nginx
    container_name: nginx-container
    networks:
      static-network:
        ipv4_address: 172.20.128.2
networks:
  static-network:
    ipam:
      config:
        - subnet: 172.20.0.0/16
          #docker-compose v3+ do not use ip_range
          ip_range: 172.28.5.0/24

from host you can test using:

docker-compose up -d
curl 172.20.128.2

Modern docker-compose does not change ip address that frequently.

To find ips of all containers in your docker-compose in a single line use:

for s in `docker-compose ps -q`; do echo ip of `docker inspect -f "{{.Name}}" $s` is `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $s`; done

If you want to automate, you can use something like this example gist

JavaScript function to add X months to a date

As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."

// Given a number of days, return a Date object
//   that many days in the future. 
function getFutureDate( days ) {

    // Convert 'days' to milliseconds
    var millies = 1000 * 60 * 60 * 24 * days;

    // Get the current date/time
    var todaysDate = new Date();

    // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
    var futureMillies = todaysDate.getTime() + millies;

    // Use the Epoch time of the targeted future date to create
    //   a new Date object, and then return it.
    return new Date( futureMillies );
}

// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );

This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.

EDIT: Full source here!

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

How to run regasm.exe from command line other than Visual Studio command prompt?

In command prompt:

SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"

How can I find my Apple Developer Team id and Team Agent Apple ID?

Apple has changed the interface.

The team ID could be found via this link: https://developer.apple.com/account/#/membership

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

Iterate over object in Angular

In JavaScript this will translate to an object that with data might look like this

Interfaces in TypeScript are a dev time construct (purely for tooling ... 0 runtime impact). You should write the same TypeScript as your JavaScript.

Microsoft Web API: How do you do a Server.MapPath?

The selected answer did not work in my Web API application. I had to use

System.Web.HttpRuntime.AppDomainAppPath

Python: Ignore 'Incorrect padding' error when base64 decoding

Incorrect padding error is caused because sometimes, metadata is also present in the encoded string If your string looks something like: 'data:image/png;base64,...base 64 stuff....' then you need to remove the first part before decoding it.

Say if you have image base64 encoded string, then try below snippet..

from PIL import Image
from io import BytesIO
from base64 import b64decode
imagestr = 'data:image/png;base64,...base 64 stuff....'
im = Image.open(BytesIO(b64decode(imagestr.split(',')[1])))
im.save("image.png")

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

javascript unexpected identifier

In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?

react-router - pass props to handler component

For react router 2.x.

const WrappedComponent = (Container, propsToPass, { children }) => <Container {...propsToPass}>{children}</Container>;

and in your routes...

<Route path="/" component={WrappedComponent.bind(null, LayoutContainer, { someProp })}>
</Route>

make sure the 3rd param is an object like: { checked: false }.

Git commit with no commit message

git generally requires a non-empty message because providing a meaningful commit message is part of good development practice and good repository stewardship. The first line of the commit message is used all over the place within git; for more, read "A Note About Git Commit Messages".

If you open Terminal.app, cd to your project directory, and git commit -am '', you will see that it fails because an empty commit message is not allowed. Newer versions of git have the
--allow-empty-message commandline argument, including the version of git included with the latest version of Xcode. This will let you use this command to make a commit with an empty message:

git commit -a --allow-empty-message -m ''

Prior to the --allow-empty-message flag, you had to use the commit-tree plumbing command. You can see an example of using this command in the "Raw Git" chapter of the Git book.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Instead of clearing the cache you can set a temporary folder:

npm install --cache /tmp/empty-cache

or

npm install --global --cache /tmp/empty-cache

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

Text Editor For Linux (Besides Vi)?

The best I've found is gedit unfortunately. Spend a few hours with it and you'll discover it's not so bad, with plugins and themes. You can use the command line to open documents in it.

What is the equivalent of "!=" in Excel VBA?

Because the inequality operator in VBA is <>

If strTest <> "" Then
    .....

the operator != is used in C#, C++.

Forms authentication timeout vs sessionState timeout

They are different things. The Forms Authentication Timeout value sets the amount of time in minutes that the authentication cookie is set to be valid, meaning, that after value number of minutes, the cookie will expire and the user will no longer be authenticated—they will be redirected to the login page automatically. The slidingExpiration=true value is basically saying that as long as the user makes a request within the timeout value, they will continue to be authenticated (more details here). If you set slidingExpiration=false the authentication cookie will expire after value number of minutes regardless of whether the user makes a request within the timeout value or not.

The SessionState timeout value sets the amount of time a Session State provider is required to hold data in memory (or whatever backing store is being used, SQL Server, OutOfProc, etc) for a particular session. For example, if you put an object in Session using the value in your example, this data will be removed after 30 minutes. The user may still be authenticated but the data in the Session may no longer be present. The Session Timeout value is always reset after every request.

Add a new element to an array without specifying the index in Bash

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.

$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array     # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h

Here's how to get the last index:

$ end=(${!array[@]})   # put all the indices in an array
$ end=${end[@]: -1}    # get the last one
$ echo $end
42

That illustrates how to get the last element of an array. You'll often see this:

$ echo ${array[${#array[@]} - 1]}
g

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:

$ echo ${array[@]: -1}
i

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

Why is quicksort better than mergesort?

Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime. However, it’s superior to merge sort in many scenarios because many factors influence an algorithm’s runtime, and, when taking them all together, quicksort wins out.

In particular, the often-quoted runtime of sorting algorithms refers to the number of comparisons or the number of swaps necessary to perform to sort the data. This is indeed a good measure of performance, especially since it’s independent of the underlying hardware design. However, other things – such as locality of reference (i.e. do we read lots of elements which are probably in cache?) – also play an important role on current hardware. Quicksort in particular requires little additional space and exhibits good cache locality, and this makes it faster than merge sort in many cases.

In addition, it’s very easy to avoid quicksort’s worst-case run time of O(n2) almost entirely by using an appropriate choice of the pivot – such as picking it at random (this is an excellent strategy).

In practice, many modern implementations of quicksort (in particular libstdc++’s std::sort) are actually introsort, whose theoretical worst-case is O(nlogn), same as merge sort. It achieves this by limiting the recursion depth, and switching to a different algorithm (heapsort) once it exceeds logn.

How do you share constants in NodeJS modules?

ES6 way.

export in foo.js

const FOO = 'bar';
module.exports = {
  FOO
}

import in bar.js

const {FOO} = require('foo');

First Heroku deploy failed `error code=H10`

If you locally start node server by nodemon, like I did, and it locally works, try npm start. Nodemon was telling me no errors, but npm start told me a lot of them in a understandable way and then I could solve them by following another posts here. I hope it helps to someone.

How to find minimum value from vector?

#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator>  // std::begin, std::end

int main() {
    std::vector<int> v = {5,14,2,4,6};
    auto result = std::min_element(std::begin(v), std::end(v));
    if (std::end(v)!=result)
        std::cout << *result << '\n';
}

The program you show has a few problems, the primary culprit being the for condition: i<v[n]. You initialize the array, setting the first 5 elements to various values and the rest to zero. n is set to the number of elements you explicitly initialized so v[n] is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.

Some minor issues:

  • avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)

  • avoid magic numbers. int v[100] is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.

  • avoid using namespace std; It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.

How to loop over a Class attributes in Java?

Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.

Checkout subdirectories in Git?

Actually, "narrow" or "partial" or "sparse" checkouts are under current, heavy development for Git. Note, you'll still have the full repository under .git. So, the other two posts are current for the current state of Git but it looks like we will be able to do sparse checkouts eventually. Checkout the mailing lists if you're interested in more details -- they're changing rapidly.

Char array in a struct - incompatible assignment?

sara is the struct itself, not a pointer (i.e. the variable representing location on the stack where actual struct data is stored). Therefore, *sara is meaningless and won't compile.

CSV with comma or semicolon?

To change comma to semicolon as the default Excel separator for CSV - go to Region -> Additional Settings -> Numbers tab -> List separator and type ; instead of the default ,

Python: convert string from UTF-8 to Latin-1

Instead of .encode('utf-8'), use .encode('latin-1').

What is the most accurate way to retrieve a user's correct IP address in PHP?

Just another clean way:

  function validateIp($var_ip){
    $ip = trim($var_ip);

    return (!empty($ip) &&
            $ip != '::1' &&
            $ip != '127.0.0.1' &&
            filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
            ? $ip : false;
  }

  function getClientIp() {
    $ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
          @$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
          'LOCAL OR UNKNOWN ACCESS';

    return $ip;
  }

How to make a simple popup box in Visual C#?

Why not make use of a tooltip?

private void ShowToolTip(object sender, string message)
{
  new ToolTip().Show(message, this, Cursor.Position.X - this.Location.X, Cursor.Position.Y - this.Location.Y, 1000);
}

The code above will show message for 1000 milliseconds (1 second) where you clicked.

To call it, you can use the following in your button click event:

ShowToolTip("Hello World");

What does asterisk * mean in Python?

I find * useful when writing a function that takes another callback function as a parameter:

def some_function(parm1, parm2, callback, *callback_args):
    a = 1
    b = 2
    ...
    callback(a, b, *callback_args)
    ...

That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:

def my_callback_function(a, b, x, y, z):
    ...

x = 5
y = 6
z = 7

some_function('parm1', 'parm2', my_callback_function, x, y, z)

Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

How to create an email form that can send email using html

Short answer, you can't.

HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.

How to retrieve Jenkins build parameters using the Groovy API?

In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:

def myParam = env.getProperty(dynamicParamName)

In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:

def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName

Calculating the SUM of (Quantity*Price) from 2 different tables

i think this - including null value = 0

 SELECT oi.id, 
         SUM(nvl(oi.quantity,0) * nvl(p.price,0)) AS total_qty 
    FROM ORDERITEM oi 
    JOIN PRODUCT p ON p.id = oi.productid 
   WHERE oi.orderid = @OrderId 
GROUP BY oi.id 

Convert String with Dot or Comma as decimal separator to number in JavaScript

The perfect solution

accounting.js is a tiny JavaScript library for number, money and currency formatting.

Check this for ref

Best way to compare two complex objects

Implement IEquatable<T> (typically in conjunction with overriding the inherited Object.Equals and Object.GetHashCode methods) on all your custom types. In the case of composite types, invoke the contained types’ Equals method within the containing types. For contained collections, use the SequenceEqual extension method, which internally calls IEquatable<T>.Equals or Object.Equals on each element. This approach will obviously require you to extend your types’ definitions, but its results are faster than any generic solutions involving serialization.

Edit: Here is a contrived example with three levels of nesting.

For value types, you can typically just call their Equals method. Even if the fields or properties were never explicitly assigned, they would still have a default value.

For reference types, you should first call ReferenceEquals, which checks for reference equality – this would serve as an efficiency boost when you happen to be referencing the same object. It would also handle cases where both references are null. If that check fails, confirm that your instance's field or property is not null (to avoid NullReferenceException) and call its Equals method. Since our members are properly typed, the IEquatable<T>.Equals method gets called directly, bypassing the overridden Object.Equals method (whose execution would be marginally slower due to the type cast).

When you override Object.Equals, you’re also expected to override Object.GetHashCode; I didn’t do so below for the sake of conciseness.

public class Person : IEquatable<Person>
{
    public int Age { get; set; }
    public string FirstName { get; set; }
    public Address Address { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Person);
    }

    public bool Equals(Person other)
    {
        if (other == null)
            return false;

        return this.Age.Equals(other.Age) &&
            (
                object.ReferenceEquals(this.FirstName, other.FirstName) ||
                this.FirstName != null &&
                this.FirstName.Equals(other.FirstName)
            ) &&
            (
                object.ReferenceEquals(this.Address, other.Address) ||
                this.Address != null &&
                this.Address.Equals(other.Address)
            );
    }
}

public class Address : IEquatable<Address>
{
    public int HouseNo { get; set; }
    public string Street { get; set; }
    public City City { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Address);
    }

    public bool Equals(Address other)
    {
        if (other == null)
            return false;

        return this.HouseNo.Equals(other.HouseNo) &&
            (
                object.ReferenceEquals(this.Street, other.Street) ||
                this.Street != null &&
                this.Street.Equals(other.Street)
            ) &&
            (
                object.ReferenceEquals(this.City, other.City) ||
                this.City != null &&
                this.City.Equals(other.City)
            );
    }
}

public class City : IEquatable<City>
{
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as City);
    }

    public bool Equals(City other)
    {
        if (other == null)
            return false;

        return
            object.ReferenceEquals(this.Name, other.Name) ||
            this.Name != null &&
            this.Name.Equals(other.Name);
    }
}

Update: This answer was written several years ago. Since then, I've started to lean away from implementing IEquality<T> for mutable types for such scenarios. There are two notions of equality: identity and equivalence. At a memory representation level, these are popularly distinguished as “reference equality” and “value equality” (see Equality Comparisons). However, the same distinction can also apply at a domain level. Suppose that your Person class has a PersonId property, unique per distinct real-world person. Should two objects with the same PersonId but different Age values be considered equal or different? The answer above assumes that one is after equivalence. However, there are many usages of the IEquality<T> interface, such as collections, that assume that such implementations provide for identity. For example, if you're populating a HashSet<T>, you would typically expect a TryGetValue(T,T) call to return existing elements that share merely the identity of your argument, not necessarily equivalent elements whose contents are completely the same. This notion is enforced by the notes on GetHashCode:

In general, for mutable reference types, you should override GetHashCode() only if:

  • You can compute the hash code from fields that are not mutable; or
  • You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

Check to see if cURL is installed locally?

In the Terminal, type:

$ curl -V

That's a capital V for the version

Typescript: How to extend two classes?

I think there is a much better approach, that allows for solid type-safety and scalability.

First declare interfaces that you want to implement on your target class:

interface IBar {
  doBarThings(): void;
}

interface IBazz {
  doBazzThings(): void;
}

class Foo implements IBar, IBazz {}

Now we have to add the implementation to the Foo class. We can use class mixins that also implements these interfaces:

class Base {}

type Constructor<I = Base> = new (...args: any[]) => I;

function Bar<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBar {
    public doBarThings() {
      console.log("Do bar!");
    }
  };
}

function Bazz<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBazz {
    public doBazzThings() {
      console.log("Do bazz!");
    }
  };
}

Extend the Foo class with the class mixins:

class Foo extends Bar(Bazz()) implements IBar, IBazz {
  public doBarThings() {
    super.doBarThings();
    console.log("Override mixin");
  }
}

const foo = new Foo();
foo.doBazzThings(); // Do bazz!
foo.doBarThings(); // Do bar! // Override mixin

How to pass the values from one jsp page to another jsp without submit button?

I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.

  1. It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.

  2. Pick the values in a servlet ie.

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
  3. Then Store the Values inside the Session:

    HttpSession sess = request.getSession(); 
    sess.setAttribute("username", username);
    sess.setAttribute("password", password);
    
  4. These values Will be available anywhere in the Application as long as the session is valid.

    HttpSession sess = request.getSession(false); //use false to use the existing session
    sess.getAttribute("username");//this will return username anytime in the session
    sess.getAttribute("password");//this will return password Any time in the session
    

I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl in the JSPs:

 ${username}//this will give you the username in the JSP
 ${password}// this will give you the password in the JSP

To the power of in C?

just use pow(a,b),which is exactly 3**4 in python

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Simply you can import it using require as following code:

var _ = require('your_module_name');

pip installing in global site-packages instead of virtualenv

I hit into the same issue while installing a python package from within a virtualenv. The root cause in my case was different. From within the virtualenv, I was (out of habit on Ubuntu), doing:

sudo easy_install -Z <package>

This caused the bin/pip shebang to be ignored and it used the root's non virtualenv python to install it in the global site-packages. Since we have a virtual environment, we should install the package without "sudo"

How can I break up this long line in Python?

For anyone who is also trying to call .format() on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format( call, you can do str.format("", 1, 2) instead of "".format(1, 2). This lets you break the string with whatever technique you like. For example:

logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))

can be

logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))

Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.

List of lists into numpy array

If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:

1) Make an array of arrays:

x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>

2) Make an array of lists:

x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'list'>

3) First make the lists equal in length:

x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi+[None]*(length-len(xi)) for xi in x])
y
>>>array([[1, 2, None],
>>>       [1, 2, 3],
>>>       [1, None, None]], dtype=object)

Any way to Invoke a private method?

you can do this using ReflectionTestUtils of Spring (org.springframework.test.util.ReflectionTestUtils)

ReflectionTestUtils.invokeMethod(instantiatedObject,"methodName",argument);

Example : if you have a class with a private method square(int x)

Calculator calculator = new Calculator();
ReflectionTestUtils.invokeMethod(calculator,"square",10);

How to increase the Java stack size?

Hmm... it works for me and with far less than 999MB of stack:

> java -Xss4m Test
0

(Windows JDK 7, build 17.0-b05 client VM, and Linux JDK 6 - same version information as you posted)

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

calling server side event from html button control

If you are OK with converting the input button to a server side control by specifying runat="server", and you are using asp.net, an option could be using the HtmlButton.OnServerClick property.

<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />

This should work and call foo_OnClick in your server side code. Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.

MVC 4 - Return error message from Controller - Show in View

Thanks for all the replies.

I was able to solve this by doing the following:

CONTROLLER:

[HttpPost]       
public ActionResult form_edit(FormModels model)
{
  model.error_msg = model.update_content(model);
  return RedirectToAction("Form_edit", "Form", model);
}

public ActionResult form_edit(FormModels model, string searchString,string id)
{
  string test = model.selectedvalue;
  var bal = new FormModels();
  bal.Countries = bal.get_contentdetails(searchString);
  bal.selectedvalue = id;
  bal.dd_text = "content_name";
  bal.dd_value = "content_id";

  test = model.error_msg;
  ViewBag.head = "Heading";

  if (model.error_msg != null)
  {
    ModelState.AddModelError("error_msg", test);
  }

  model.error_msg = "";
  return View(bal);
}   

VIEW:

@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
  <table>
    <tr>
      <td>
        @ViewBag.error
        @Html.ValidationMessage("error_msg")
      </td>
    </tr>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
      </th>
    </tr>
  </table>
}

Convert pem key to ssh-rsa format

The following script would obtain the ci.jenkins-ci.org public key certificate in base64-encoded DER format and convert it to an OpenSSH public key file. This code assumes that a 2048-bit RSA key is used and draws a lot from this Ian Boyd's answer. I've explained a bit more how it works in comments to this article in Jenkins wiki.

echo -n "ssh-rsa " > jenkins.pub
curl -sfI https://ci.jenkins-ci.org/ | grep -i X-Instance-Identity | tr -d \\r | cut -d\  -f2 | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 >> jenkins.pub
echo >> jenkins.pub

Import SQL file by command line in Windows 7

To import database from dump file (in this case called filename.sql)

    use: mysql -u username -p password database_name < filename.sql 

you are on Windows you will need to open CMD and go to directory where mysql.exe is installed. you are using WAMP server then this is usually located in: C:\wamp\bin\mysql\mysql5.5.8\bin (*note the version of mysql might be different)

So you will: cd C:\wamp\bin\mysql\mysql5.5.8\bin

and then execute one of the above commands. Final command like this

    C:\wamp\bin\mysql\mysql5.5.8\bin>mysql -u rootss -p pwdroot testdatabasename < D:\test\Projects\test_demo_db.sql

how to import csv data into django models

If you're working with new versions of Django (>10) and don't want to spend time writing the model definition. you can use the ogrinspect tool.

This will create a code definition for the model .

python manage.py ogrinspect [/path/to/thecsv] Product

The output will be the class (model) definition. In this case the model will be called Product. You need to copy this code into your models.py file.

Afterwards you need to migrate (in the shell) the new Product table with:

python manage.py makemigrations
python manage.py migrate

More information here: https://docs.djangoproject.com/en/1.11/ref/contrib/gis/tutorial/

Do note that the example has been done for ESRI Shapefiles but it works pretty good with standard CSV files as well.

For ingesting your data (in CSV format) you can use pandas.

import pandas as pd
your_dataframe = pd.read_csv(path_to_csv)
# Make a row iterator (this will go row by row)
iter_data = your_dataframe.iterrows()

Now, every row needs to be transformed into a dictionary and use this dict for instantiating your model (in this case, Product())

# python 2.x
map(lambda (i,data) : Product.objects.create(**dict(data)),iter_data

Done, check your database now.

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

Choosing the best concurrency list in Java

Any Java collection can be made to be Thread-safe like so:

List newList = Collections.synchronizedList(oldList);

Or to create a brand new thread-safe list:

List newList = Collections.synchronizedList(new ArrayList());

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)

How to tell git to use the correct identity (name and email) for a given project?

Edit the config file with in ".git" folder to maintain the different username and email depends upon the repository

  • Go to Your repository
  • Show the hidden files and go to ".git" folder
  • Find the "config" file
  • Add the below lines at EOF

[user]

name = Bob

email = [email protected]

This below command show you which username and email set for this repository.

git config --get user.name

git config --get user.email

Example: for mine that config file in D:\workspace\eclipse\ipchat\.git\config

Here ipchat is my repo name

How to set the height of table header in UITableView?

In case you still need it, have you tried to set the property

self.tableView.tableHeaderView 

If you calculate the heigh you need, and set a new view for tableHeaderView:

CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];

It should work.

Override back button to act like home button

Use the following code:

public void onBackPressed() {    
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

SQLAlchemy equivalent to SQL "LIKE" statement

Each column has like() method, which can be used in query.filter(). Given a search string, add a % character on either side to search as a substring in both directions.

tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()

Getting an "ambiguous redirect" error

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then ('shell command within quotes' + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

inner join in linq to entities

Not 100% sure about the relationship between these two entities but here goes:

IList<Splitting> res = (from s in [data source]
                        where s.Customer.CompanyID == [companyID] &&
                              s.CustomerID == [customerID]
                        select s).ToList();

IList<Splitting> res = [data source].Splittings.Where(
                           x => x.Customer.CompanyID == [companyID] &&
                                x.CustomerID == [customerID]).ToList();

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

Android: How to stretch an image to the screen width while maintaining aspect ratio?

A very simple solution is to just use the features provided by RelativeLayout.

Here is the xml that makes it possible with standard Android Views:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <RelativeLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <LinearLayout
            android:id="@+id/button_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentBottom="true"
            >
            <Button
                android:text="button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:text="button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:text="button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <ImageView 
            android:src="@drawable/cat"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:layout_above="@id/button_container"/>
    </RelativeLayout>
</ScrollView>

The trick is that you set the ImageView to fill the screen but it has to be above the other layouts. This way you achieve everything you need.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

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

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

Questions every good Java/Java EE Developer should be able to answer?

Core: 1. What are checked and unchecked exceptions ? 2. While adding new exception in code what type (Checked/Unchecked) to use when ?

Servlet: 1. What is the difference between response.sendRedirect() and request.forward() ?

How to get first two characters of a string in oracle query?

select substr(orderno,1,2) from shipment;

You may want to have a look at the documentation too.

How can I execute PHP code from the command line?

On the command line:

php -i | grep sourceguardian

If it's there, then you'll get some text. If not, you won't get a thing.

How to compile the finished C# project and then run outside Visual Studio?

In the project file is folder "bin/debug/your_appliacion_name.exe". This is final executable program file.

Spring JSON request getting 406 (not Acceptable)

As @atott mentioned.

If you have added the latest version of Jackson in your pom.xml, and with Spring 4.0 or newer, using @ResponseBody on your action method and @RequestMapping configured with produces="application/json;charset=utf-8", however, you still got 406(Not Acceptable), I guess you need to try this in your MVC DispatcherServlet context configuration:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
</bean>

That's the way how I resolved my issue finally.

Access a global variable in a PHP function

If you want, you can use the "define" function, but this function creates a constant which can't be changed once defined.

<?php
    define("GREETING", "Welcome to W3Schools.com!");

    function myTest() {
        echo GREETING;
    }

    myTest();
?>

PHP Constants

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

Can't install Scipy through pip

  1. Download SciPy from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
  2. Go into the directory the downloaded file is in and pip install the file.
  3. Go to python shell, run import scipy; it worked for me with no errors.

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

How can I convert JSON to a HashMap using Gson?

Here you go:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);

Export to CSV via PHP

I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.

How do I 'foreach' through a two-dimensional array?

string[][] languages = new string[2][];
            languages[0] = new string[2];
            languages[1] = new string[3];
// inserting data into double dimensional arrays.
            for (int i = 0; i < 2; i++)
            {
                languages[0][i] = "Jagged"+i.ToString();
            }
            for (int j = 0; j < 3; j++)
            {
                languages[1][j] = "Jag"+j.ToString();
            }

// doing foreach through 2 dimensional arrays.
foreach (string[] s in languages)
            {
                foreach (string a in s)
                {
                    Console.WriteLine(a);
                }
            }

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

What is the best Java QR code generator library?

I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.

How to store printStackTrace into a string

Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.

how to convert object to string in java

The question how do I convert an object to a String, despite the several answers you see here, and despite the existence of the Object.toString method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.

Before code can be written to convert an object to a String, you must decide on the language/format to be used.

How to get a property value based on the name

Simple sample (without write reflection hard code in the client)

class Customer
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    // approach here
    public string GetPropertyValue(string propertyName)
    {
        try
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
        }
        catch { return null; }
    }
}
//use sample
static void Main(string[] args)
    {
        var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
        Console.WriteLine(customer.GetPropertyValue("CustomerName"));
    }

How do I change the default library path for R packages

After a couple of hours of trying to solve the issue in several ways, some of which are described here, for me (on Win 10) the option of creating a Renviron file worked, but a little different from what was written here above. The task is to change the value of the variable R_LIBS_USER. To do this two steps needed:

  1. Create the file named Renviron (without dot) in the folder \Program\etc\ (Programm is the directory where the R installed, for example for me it was c:\Program Files\R\R-4.0.0\etc)
  2. Insert a line in Renviron with new path: R_LIBS_USER=c:/R/Library

It's been working for a few days already.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I faced similar error, tried all the suggestions above, but did not resolve. what worked for me is this:

Right-click your Global.asax file and click View Markup. You will see the attribute Inherits="nadeem.MvcApplication". This means that your Global.asax file is trying to inherit from the type nadeem.MvcApplication.

Now double click your Global.asax file and see what the class name specified in your Global.asax.cs file is. It should look something like this:

namespace nadeem
{

public class MvcApplication: System.Web.HttpApplication
    {
    ....

But if it doesn't look like above, you will receive that error, The value in the Inherits attribute of your Global.asax file must match a type that is derived from System.Web.HttpApplication.

Check below link for more info:

Parser Error: Server Error in '/' Application

Use of "instanceof" in Java

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

nginx- duplicate default server error

Execute this at the terminal to see conflicting configurations listening to the same port:

grep -R default_server /etc/nginx

How Do I Make Glyphicons Bigger? (Change Size?)

I've used bootstrap header classes ("h1", "h2", etc.) for this. This way you get all the style benefits without using the actual tags. Here is an example:

<div class="h3"><span class="glyphicon glyphicon-tags" aria-hidden="true"></span></div>

python: SyntaxError: EOL while scanning string literal

I also had this exact error message, for me the problem was fixed by adding an " \"

It turns out that my long string, broken into about eight lines with " \" at the very end, was missing a " \" on one line.

Python IDLE didn't specify a line number that this error was on, but it red-highlighted a totally correct variable assignment statement, throwing me off. The actual misshapen string statement (multiple lines long with " \") was adjacent to the statement being highlighted. Maybe this will help someone else.

Python display text with font & color?

You can use your own custom fonts by setting the font path using pygame.font.Font

pygame.font.Font(filename, size): return Font

example:

pygame.font.init()
font_path = "./fonts/newfont.ttf"
font_size = 32
fontObj = pygame.font.Font(font_path, font_size)

Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)

Less aggressive compilation with CSS3 calc

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

When should a class be Comparable and/or Comparator?

Comparable lets a class implement its own comparison:

  • it's in the same class (it is often an advantage)
  • there can be only one implementation (so you can't use that if you want two different cases)

By comparison, Comparator is an external comparison:

  • it is typically in a unique instance (either in the same class or in another place)
  • you name each implementation with the way you want to sort things
  • you can provide comparators for classes that you do not control
  • the implementation is usable even if the first object is null

In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.

As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(

  • Comparable<Object> lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.
  • Comparable<Itself> is very strict on the contrary.

Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).

Unicode characters in URLs

What Tgr said. Background:

http://www.example.com/düsseldorf?neighbourhood=Lörick

That's not a URI. But it is an IRI.

You can't include an IRI in an HTML4 document; the type of attributes like href is defined as URI and not IRI. Some browsers will handle an IRI here anyway, but it's not really a good idea.

To encode an IRI into a URI, take the path and query parts, UTF-8-encode them then percent-encode the non-ASCII bytes:

http://www.example.com/d%C3%BCsseldorf?neighbourhood=L%C3%B6rick

If there are non-ASCII characters in the hostname part of the IRI, eg. http://??.???/, they have be encoded using Punycode instead.

Now you have a URI. It's an ugly URI. But most browsers will hide that for you: copy and paste it into the address bar or follow it in a link and you'll see it displayed with the original Unicode characters. Wikipedia have been using this for years, eg.:

http://en.wikipedia.org/wiki/?

The one browser whose behaviour is unpredictable and doesn't always display the pretty IRI version is...

...well, you know.

Accept function as parameter in PHP

Tested for PHP 5.3

As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php

What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.

The function to do check:

if( is_callable( $string_function_name ) ){
    /*perform the call*/
}

Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php

call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );

as it follows (in a similar, parameterless, way):

    function funToBeCalled(){
        print("----------------------i'm here");
    }
    function wrapCaller($fun){
        if( is_callable($fun)){
            print("called");
            call_user_func($fun);
        }else{
            print($fun." not called");
        }
    }

    wrapCaller("funToBeCalled");
    wrapCaller("cannot call me");

Here's a class explaining how to do something similar :

<?php
class HolderValuesOrFunctionsAsString{
    private $functions = array();
    private $vars = array();

    function __set($name,$data){
        if(is_callable($data))
            $this->functions[$name] = $data;
        else
            $this->vars[$name] = $data;
    }

    function __get($name){
        $t = $this->vars[$name];
        if(isset($t))
            return $t;
        else{
            $t = $this->$functions[$name];
            if( isset($t))
                return $t;
        }
    }

    function __call($method,$args=null){
        $fun = $this->functions[$method];
        if(isset($fun)){
            call_user_func_array($fun,$args);
        } else {
            // error out
            print("ERROR: Funciton not found: ". $method);
        }
    }
}
?>

and an example of usage

<?php
    /*create a sample function*/
    function sayHello($some = "all"){
    ?>
         <br>hello to <?=$some?><br>
    <?php
    }

    $obj = new HolderValuesOrFunctionsAsString;

    /*do the assignement*/
    $obj->justPrintSomething = 'sayHello'; /*note that the given
        "sayHello" it's a string ! */

    /*now call it*/
    $obj->justPrintSomething(); /*will print: "hello to all" and
        a break-line, for html purpose*/

    /*if the string assigned is not denoting a defined method
         , it's treat as a simple value*/
    $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';

    echo $obj->justPrintSomething; /*what do you expect to print?
        just that string*/
    /*N.B.: "justPrintSomething" is treated as a variable now!
        as the __set 's override specify"*/

    /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
     $obj->justPrintSomething("Jack Sparrow");


     /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/

     $obj->justPrintSomething( $obj->justPrintSomething );
         /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/

    /*in fact, "justPrintSomething" it's a name used to identify both
         a value (into the dictionary of values) or a function-name
         (into the dictionary of functions)*/
?>

How to resolve Unneccessary Stubbing exception

Replace

@RunWith(MockitoJUnitRunner.class)

with

@RunWith(MockitoJUnitRunner.Silent.class)

or remove @RunWith(MockitoJUnitRunner.class)

or just comment out the unwanted mocking calls (shown as unauthorised stubbing).

PostgreSQL: How to change PostgreSQL user password?

Then type:

$ sudo -u postgres psql

Then:

\password postgres

Then to quit psql:

\q

If that does not work, reconfigure authentication.

Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

    local   all             all                                     peer

to:

    local   all             all                                     md5

Then restart the server:

$ sudo service postgresql restart

Node.js: Python not found exception due to node-sass and node-gyp

This is 2 years old, but none of them helped me.

I uninstalled my NodeJS v12.8.1 (Current) and installed a brand new v10.16.3 (LTS) and my ng build --prod worked.

Assign an initial value to radio button as checked

For anyone looking for an Angular2 (2.4.8) solution, since this is a generically-popular question when searching:

<div *ngFor="let choice of choices">
  <input type="radio" [checked]="choice == defaultChoice">
</div>

This will add the checked attribute to the input given the condition, but will add nothing if the condition fails.

Do not do this:

[attr.checked]="choice == defaultChoice"

because this will add the attribute checked="false" to every other input element.

Since the browser only looks for the presence of the checked attribute (the key), ignoring its value, so the last input in the group will be checked.

How do I get which JRadioButton is selected from a ButtonGroup

I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.

If you really want the widget, then you can test each with isSelected, or maintain a Map<ButtonModel,JRadioButton>.

How to use HTML to print header and footer on every printed page of a document?

the magic solution is really putting every thing in single table.

  • thead: this is for the repeated header.

  • tfoot: the repeated footer.

  • tbody: the content.

and make a single tr, td and put every thing in a div

CODE::

<table class="report-container">
   <thead class="report-header">
     <tr>
        <th class="report-header-cell">
           <div class="header-info">
            ...
           </div>
         </th>
      </tr>
    </thead>
    <tfoot class="report-footer">
      <tr>
         <td class="report-footer-cell">
           <div class="footer-info">
           ...
           </div>
          </td>
      </tr>
    </tfoot>
    <tbody class="report-content">
      <tr>
         <td class="report-content-cell">
            <div class="main">
            ...
            </div>
          </td>
       </tr>
     </tbody>
</table>

table.report-container {
    page-break-after:always;
}
thead.report-header {
    display:table-header-group;
}
tfoot.report-footer {
    display:table-footer-group;
} 

extra: to prevent overlapping with multiple pages. like:

<div class="main">
    <div class="article">
        ...
  </div>
    <div class="article">
        ...
  </div>
    <div class="article">
        ...
  </div>
  ...
  ...
  ...
</div>

which results in overflow that will make things overlap with the header within the page breaks..

so >> use: page-break-inside: avoid !important; with this class article.

table.report-container div.article {
    page-break-inside: avoid;
}

pretty simple, hope this will give you the best result you wishing for.

best regards. ;)

source..

Unstaged changes left after git reset --hard

Run clean command:

# Remove all untracked files and directories. (`-f` is `force`, `-d` is `remove directories`)

git clean -fd

Send values from one form to another form

Form1 Code :

private void button1_Click(object sender, EventArgs e)
{
            Form2 f2 = new Form2();
            f2.ShowDialog();
            MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}

Form2 Code :

        public Form2()
        {
            InitializeComponent();
            t = textBox1;                        //Initialize with static textbox
        }
        public static TextBox t=new TextBox();   //make static to get the same value as inserted
        private void button1_Click(object sender, EventArgs e)
        {

            this.Close();

        }

It Works!

Is there any JSON Web Token (JWT) example in C#?

Thanks everyone. I found a base implementation of a Json Web Token and expanded on it with the Google flavor. I still haven't gotten it completely worked out but it's 97% there. This project lost it's steam, so hopefully this will help someone else get a good head-start:

Note: Changes I made to the base implementation (Can't remember where I found it,) are:

  1. Changed HS256 -> RS256
  2. Swapped the JWT and alg order in the header. Not sure who got it wrong, Google or the spec, but google takes it the way It is below according to their docs.
public enum JwtHashAlgorithm
{
    RS256,
    HS384,
    HS512
}

public class JsonWebToken
{
    private static Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> HashAlgorithms;

    static JsonWebToken()
    {
        HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
            {
                { JwtHashAlgorithm.RS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } },
                { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } },
                { JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } }
            };
    }

    public static string Encode(object payload, string key, JwtHashAlgorithm algorithm)
    {
        return Encode(payload, Encoding.UTF8.GetBytes(key), algorithm);
    }

    public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm)
    {
        var segments = new List<string>();
        var header = new { alg = algorithm.ToString(), typ = "JWT" };

        byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
        byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
        //byte[] payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}");

        segments.Add(Base64UrlEncode(headerBytes));
        segments.Add(Base64UrlEncode(payloadBytes));

        var stringToSign = string.Join(".", segments.ToArray());

        var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

        byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign);
        segments.Add(Base64UrlEncode(signature));

        return string.Join(".", segments.ToArray());
    }

    public static string Decode(string token, string key)
    {
        return Decode(token, key, true);
    }

    public static string Decode(string token, string key, bool verify)
    {
        var parts = token.Split('.');
        var header = parts[0];
        var payload = parts[1];
        byte[] crypto = Base64UrlDecode(parts[2]);

        var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
        var headerData = JObject.Parse(headerJson);
        var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
        var payloadData = JObject.Parse(payloadJson);

        if (verify)
        {
            var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload));
            var keyBytes = Encoding.UTF8.GetBytes(key);
            var algorithm = (string)headerData["alg"];

            var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](keyBytes, bytesToSign);
            var decodedCrypto = Convert.ToBase64String(crypto);
            var decodedSignature = Convert.ToBase64String(signature);

            if (decodedCrypto != decodedSignature)
            {
                throw new ApplicationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature));
            }
        }

        return payloadData.ToString();
    }

    private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
    {
        switch (algorithm)
        {
            case "RS256": return JwtHashAlgorithm.RS256;
            case "HS384": return JwtHashAlgorithm.HS384;
            case "HS512": return JwtHashAlgorithm.HS512;
            default: throw new InvalidOperationException("Algorithm not supported.");
        }
    }

    // from JWT spec
    private static string Base64UrlEncode(byte[] input)
    {
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    }

    // from JWT spec
    private static byte[] Base64UrlDecode(string input)
    {
        var output = input;
        output = output.Replace('-', '+'); // 62nd char of encoding
        output = output.Replace('_', '/'); // 63rd char of encoding
        switch (output.Length % 4) // Pad with trailing '='s
        {
            case 0: break; // No pad chars in this case
            case 2: output += "=="; break; // Two pad chars
            case 3: output += "="; break; // One pad char
            default: throw new System.Exception("Illegal base64url string!");
        }
        var converted = Convert.FromBase64String(output); // Standard base64 decoder
        return converted;
    }
}

And then my google specific JWT class:

public class GoogleJsonWebToken
{
    public static string Encode(string email, string certificateFilePath)
    {
        var utc0 = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
        var issueTime = DateTime.Now;

        var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
        var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; // Expiration time is up to 1 hour, but lets play on safe side

        var payload = new
        {
            iss = email,
            scope = "https://www.googleapis.com/auth/gan.readonly",
            aud = "https://accounts.google.com/o/oauth2/token",
            exp = exp,
            iat = iat
        };

        var certificate = new X509Certificate2(certificateFilePath, "notasecret");

        var privateKey = certificate.Export(X509ContentType.Cert);

        return JsonWebToken.Encode(payload, privateKey, JwtHashAlgorithm.RS256);
    }
}

DROP IF EXISTS VS DROP?

DROP TABLE IF EXISTS [table_name]

it first checks if the table exists, if it does it deletes the table while

DROP TABLE [table_name]

it deletes without checking, so if it doesn't exist it exits with an error

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Note however:

If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.

http://msdn.microsoft.com/en-us/library/ms173763.aspx

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

What is the proper way to format a multi-line dict in Python?

I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

mylist = [
    (1, 'hello'),
    (2, 'world'),
]

nested = {
    a: [
        (1, 'a'),
        (2, 'b'),
    ],
    b: [
        (3, 'c'),
        (4, 'd'),
    ],
}

Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

Can a for loop increment/decrement by more than one?

for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional

Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

Why can't I use a list as a dict key in python?

Because lists are mutable, dict keys (and set members) need to be hashable, and hashing mutable objects is a bad idea because hash values should be computed on the basis of instance attributes.

In this answer, I will give some concrete examples, hopefully adding value on top of the existing answers. Every insight applies to the elements of the set datastructure as well.

Example 1: hashing a mutable object where the hash value is based on a mutable characteristic of the object.

>>> class stupidlist(list):
...     def __hash__(self):
...         return len(self)
... 
>>> stupid = stupidlist([1, 2, 3])
>>> d = {stupid: 0}
>>> stupid.append(4)
>>> stupid
[1, 2, 3, 4]
>>> d
{[1, 2, 3, 4]: 0}
>>> stupid in d
False
>>> stupid in d.keys()
False
>>> stupid in list(d.keys())
True

After mutating stupid, it cannot be found in the dict any longer because the hash changed. Only a linear scan over the list of the dict's keys finds stupid.

Example 2: ... but why not just a constant hash value?

>>> class stupidlist2(list):
...     def __hash__(self):
...         return id(self)
... 
>>> stupidA = stupidlist2([1, 2, 3])
>>> stupidB = stupidlist2([1, 2, 3])
>>> 
>>> stupidA == stupidB
True
>>> stupidA in {stupidB: 0}
False

That's not a good idea as well because equal objects should hash identically such that you can find them in a dict or set.

Example 3: ... ok, what about constant hashes across all instances?!

>>> class stupidlist3(list):
...     def __hash__(self):
...         return 1
... 
>>> stupidC = stupidlist3([1, 2, 3])
>>> stupidD = stupidlist3([1, 2, 3])
>>> stupidE = stupidlist3([1, 2, 3, 4])
>>> 
>>> stupidC in {stupidD: 0}
True
>>> stupidC in {stupidE: 0}
False
>>> d = {stupidC: 0}
>>> stupidC.append(5)
>>> stupidC in d
True

Things seem to work as expected, but think about what's happening: when all instances of your class produce the same hash value, you will have a hash collision whenever there are more than two instances as keys in a dict or present in a set.

Finding the right instance with my_dict[key] or key in my_dict (or item in my_set) needs to perform as many equality checks as there are instances of stupidlist3 in the dict's keys (in the worst case). At this point, the purpose of the dictionary - O(1) lookup - is completely defeated. This is demonstrated in the following timings (done with IPython).

Some Timings for Example 3

>>> lists_list = [[i]  for i in range(1000)]
>>> stupidlists_set = {stupidlist3([i]) for i in range(1000)}
>>> tuples_set = {(i,) for i in range(1000)}
>>> l = [999]
>>> s = stupidlist3([999])
>>> t = (999,)
>>> 
>>> %timeit l in lists_list
25.5 µs ± 442 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit s in stupidlists_set
38.5 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit t in tuples_set
77.6 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As you can see, the membership test in our stupidlists_set is even slower than a linear scan over the whole lists_list, while you have the expected super fast lookup time (factor 500) in a set without loads of hash collisions.


TL; DR: you can use tuple(yourlist) as dict keys, because tuples are immutable and hashable.

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

How to append a char to a std::string?

In addition to the others mentioned, one of the string constructors take a char and the number of repetitions for that char. So you can use that to append a single char.

std::string s = "hell";
s += std::string(1, 'o');

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

How can I set NODE_ENV=production on Windows?

I used npm script for running a gulp task without "&&"

NODE_ENV=testcases npm run seed-db

Are there constants in JavaScript?

The const keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:

const CONSTANT_NAME = 0;

Composer update memory limit

<C:\>set COMPOSER_MEMORY_LIMIT=-1
<C:\>composer install exhausted/packages

Spring Boot War deployed to Tomcat

Hey make sure to do this changes to the pom.xml

<packaging>war</packaging>

in the dependencies section make sure to indicated the tomcat is provided so you dont need the embeded tomcat plugin.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>       

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>       

This is the whole pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.example.Application</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>       

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>       

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

And the Application class should be like this

Application.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {


    /**
     * Used when run as JAR
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Used when run as WAR
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}

And you can add a controller for testing MyController.java

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/hi")
    public @ResponseBody String hiThere(){
        return "hello world!";
    }
}

Then you can run the project in a tomcat 8 version and access the controller like this

http://localhost:8080/demo/hi

If for some reason you are not able to add the project to tomcat do a right click in the project and then go to the Build Path->configure build path->Project Faces

make sure only this 3 are selected

Dynamic web Module 3.1 Java 1.8 Javascript 1.0

PHP - Getting the index of a element from a array

PHP arrays are both integer-indexed and string-indexed. You can even mix them:

array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');

What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.

Another solution for you is to coerce the array to an integer-indexed list of values.

foreach (array_values($array) as $i => $value) {
  echo "$i: $value\n";
}

Output:

0: red
1: green
2: white
3: blue
4: yellow

How to use vertical align in bootstrap

Prinsen's answer is the best choice. But, to fix the issue where the columns don't collapse his code needs to be surrounded by a media check statement. This way these styles are only applied when the larger columns are active. Here is the updated complete answer.

HTML:

<div class="row display-table">
    <div class="col-xs-12 col-sm-4 display-cell">
        img
    </div>
    <div class="col-xs-12 col-sm-8 display-cell">
        text
    </div>
</div>

CSS:

@media (min-width: 768px){
   .display-table{
       display: table;
       table-layout: fixed;
   }

   .display-cell{
       display: table-cell;
       vertical-align: middle;
       float: none;
   }
}

Pass request headers in a jQuery AJAX GET call

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

How to build & install GLFW 3 and use it in a Linux project

Note that you do not need that many -ls if you install glfw with the BUILD_SHARED_LIBS option. (You can enable this option by running ccmake first).

This way sudo make install will install the shared library in /usr/local/lib/libglfw.so. You can then compile the example file with a simple:

g++ main.cpp -L /usr/local/lib/ -lglfw

Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:

export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}

And you can put that in your ~/.bashrc so you don't have to type it all the time.

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

Creating stored procedure and SQLite?

Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.

Print content of JavaScript object?

Internet Explorer 8 has developer tools which is similar to Firebug for Firefox. Opera has Opera DragonFly, and Google Chrome also has something called Developer Tools (Shift+Ctrl+J).

Here is more a more detailed answer to debug JavaScript in IE6-8: Using the IE8 'Developer Tools' to debug earlier IE versions