Programs & Examples On #Enums

A data type consisting of a set of named values called elements, members or enumerators of the type.

Java Enum Methods - return opposite direction enum

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

How to enumerate an enum with String type?

Here's my suggested approach. It's not completely satisfactory (I'm very new to Swift and OOP!) but maybe someone can refine it. The idea is to have each enum provide its own range information as .first and .last properties. It adds just two lines of code to each enum: still a bit hard-coded, but at least it's not duplicating the whole set. It does require modifying the Suit enum to be an Int like the Rank enum is, instead of untyped.

Rather than echo the whole solution, here's the code I added to the . enum, somewhere after the case statements (Suit enum is similar):

var first: Int { return Ace.toRaw() }
var last: Int { return King.toRaw() }

and the loop I used to build the deck as an array of String. (The problem definition did not state how the deck was to be structured.)

func createDeck() -> [String] {
    var deck: [String] = []
    var card: String
    for r in Rank.Ace.first...Rank.Ace.last {
        for s in Suit.Hearts.first...Suit.Hearts.last {
            card = Rank.simpleDescription( Rank.fromRaw(r)!)() + " of " + Suit.simpleDescription( Suit.fromRaw(s)!)()
           deck.append( card)
       }
    }
    return deck
}

It's unsatisfactory because the properties are associated to an element rather than to the enum. But it does add clarity to the 'for' loops. I'd like it to say Rank.first instead of Rank.Ace.first. It works (with any element), but it's ugly. Can someone show how to elevate that to the enum level?

And to make it work, I lifted the createDeck method out of the Card struct. I could not figure out how to get a [String] array returned from that struct, and that seems a bad place to put such a method anyway.

Java: using switch statement with enum under subclass

this should do:

//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }    
        public MyEnum myEnum;
    }

    public void someMethod() { 
        AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...

        switch (enumExample) {
            case VALUE_A: { //<-- error on this line
            //..
            break;
            }
        }
    }
}

How to get C# Enum description from value?

I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:

public static string DescriptionAttr<T>(this T source)
{
    FieldInfo fi = source.GetType().GetField(source.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0) return attributes[0].Description;
    else return source.ToString();
}

Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:

string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();

Total number of items defined in an enum

I've run a benchmark today and came up with interesting result. Among these three:

var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;

GetNames(enum) is by far the fastest!

|         Method |      Mean |    Error |   StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
|       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
|      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |

Convert from enum ordinal to enum type

Every enum has name(), which gives a string with the name of enum member.

Given enum Suit{Heart, Spade, Club, Diamond}, Suit.Heart.name() will give Heart.

Every enum has a valueOf() method, which takes an enum type and a string, to perform the reverse operation:

Enum.valueOf(Suit.class, "Heart") returns Suit.Heart.

Why anyone would use ordinals is beyond me. It may be nanoseconds faster, but it is not safe, if the enum members change, as another developer may not be aware some code is relying on ordinal values (especially in the JSP page cited in the question, network and database overhead completely dominates the time, not using an integer over a string).

Casting string to enum

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

Enums in Javascript with ES6

Here is my approach, including some helper methods

export default class Enum {

    constructor(name){
        this.name = name;
    }

    static get values(){
        return Object.values(this);
    }

    static forName(name){
        for(var enumValue of this.values){
            if(enumValue.name === name){
                return enumValue;
            }
        }
        throw new Error('Unknown value "' + name + '"');
    }

    toString(){
        return this.name;
    }
}

-

import Enum from './enum.js';

export default class ColumnType extends Enum {  

    constructor(name, clazz){
        super(name);        
        this.associatedClass = clazz;
    }
}

ColumnType.Integer = new ColumnType('Integer', Number);
ColumnType.Double = new ColumnType('Double', Number);
ColumnType.String = new ColumnType('String', String);

Check if value exists in enum in TypeScript

If you want to use the variable as enum, just add the function:

Enum EVehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

const getVehicleAsEnum = (vehicleStr:string) => vehicleStr === 'car' ? EVehicle.Car : vehicleStr === 'bike' ? EVehicle.Bike : vehicleStr === 'truck' ? EVehicle.Truck : undefined

And then test:

const vehicleEnum = getVecicleAsEnum(str)
if(vehicleEnum) {
   // do something
}

C# Enum - How to Compare Value

You can use Enum.Parse like, if it is string

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

Enum "Inheritance"

The short answer is no. You can play a bit, if you want:

You can always do something like this:

private enum Base
{
    A,
    B,
    C
}

private enum Consume
{
    A = Base.A,
    B = Base.B,
    C = Base.C,
    D,
    E
}

But, it doesn't work all that great because Base.A != Consume.A

You can always do something like this, though:

public static class Extensions
{
    public static T As<T>(this Consume c) where T : struct
    {
        return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
    }
}

In order to cross between Base and Consume...

You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.

The extension method return should type cast it type T.

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

Get Enum from Description attribute

Should be pretty straightforward, its just the reverse of your previous method;

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
        if(attribute == null)
            continue;
        if(attribute.Description == description)
        {
            return (int) field.GetValue(null);
        }
    }
    return 0;
}

Usage:

Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));

convert an enum to another type of enum

public static TEnum ConvertByName<TEnum>(this Enum source, bool ignoreCase = false) where TEnum : struct
{
    // if limited by lack of generic enum constraint
    if (!typeof(TEnum).IsEnum)
    {
        throw new InvalidOperationException("enumeration type required.");
    }

    TEnum result;
    if (!Enum.TryParse(source.ToString(), ignoreCase, out result))
    {
        throw new Exception("conversion failure.");
    }

    return result;
}

Enum Naming Convention - Plural

Microsoft recommends using singular for Enums unless the Enum represents bit fields (use the FlagsAttribute as well). See Enumeration Type Naming Conventions (a subset of Microsoft's Naming Guidelines).

To respond to your clarification, I see nothing wrong with either of the following:

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass { 
    public OrderStatus OrderStatus { get; set; }
}

or

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass {
    public OrderStatus Status { get; set; }
}

Enum to String C++

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

List of enum values in java

An enum is just another class in Java, it should be possible.

More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html

So yes, it should work.

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Håken Lid's answer helped solved my problem (thanks!) , in my case present in Python3.7 running Flask in a Docker container (FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7).

In my case, enum34 was being installed by another library (pip install smartsheet-python-sdk). For those coming with a similar Docker container problem, here is my final Dockerfile (stripped to the relevant lines):

FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7
...
RUN pip install -r requirements.txt
RUN pip uninstall -y enum34
...

Choosing the default value of an Enum type without having to change values

The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).

enum Orientation
{
    None = 0, //default value since it has the value '0'
    North = 1,
    East = 2,
    South = 3,
    West = 4
}

Orientation o; // initialized to 'None'

If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." (C# reference)

enum Orientation
{
    None, //default value since it is the first enumerator
    North,
    East,
    South,
    West
}

Orientation o; // initialized to 'None'

Can I set enum start value in Java?

whats about using this way:

public enum HL_COLORS{
          YELLOW,
          ORANGE;

          public int getColorValue() {
              switch (this) {
            case YELLOW:
                return 0xffffff00;
            case ORANGE:
                return 0xffffa500;    
            default://YELLOW
                return 0xffffff00;
            }
          }
}

there is only one method ..

you can use static method and pass the Enum as parameter like:

public enum HL_COLORS{
          YELLOW,
          ORANGE;

          public static int getColorValue(HL_COLORS hl) {
              switch (hl) {
            case YELLOW:
                return 0xffffff00;
            case ORANGE:
                return 0xffffa500;    
            default://YELLOW
                return 0xffffff00;
            }
          }

Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

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

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

What is the preferred syntax for defining enums in JavaScript?

There are basically two types of enums, global (like C) and object-like (like TypeScript). For global enums, do something like this-

// Note that // enum is optional, though it makes it look slightly better.
const // enum
  SUNDAY = 1,
  MONDAY = 2,
  TUESDAY = 3,
  WEDNSDAY = 4,
  THURSDAY = 5,
  FRIDAY = 6,
  SATURDAY = 7;

And for object-like enums, do this (like Artur Czajka's answer)-

// A trailing comma isn't required but is a good habit.
const Days = Object.freeze({
  SUNDAY = 1,
  MONDAY = 2,
  TUESDAY = 3,
  WEDSNDAY = 4,
  THURSDAY = 5,
  FRIDAY = 6,
  SATURDAY = 7,
});

or

const Days = {
  SUNDAY = 1,
  MONDAY = 2,
  TUESDAY = 3,
  WEDSNDAY = 4,
  THURSDAY = 5,
  FRIDAY = 6,
  SATURDAY = 7,
};
Object.freeze(Days);

The first way to declare object-like enums looks slightly cleaner. By the way, global and object-like enums aren't really correct terms, I made them up.

Edit:

A solution made (for global enums) by Aral Roca, it looks amazing but has a con of being slow (like 0.1 seconds slow)-

function* ENUM(count = 1) {
  while (true) yield count++;
}

and then

const [ RED, GREEN, BLUE ] = ENUM();

Java using enum with switch statement

I like a few usages of Java enum:

  1. .name() allows you to fetch the enum name in String.
  2. .ordinal() allow you to get the integer value, 0-based.
  3. You can attach other value parameters with each enum.
  4. and, of course, switch enabled.

enum with value parameters:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

switch example:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;

enum Values to NSString (iOS)

Suppose requirement is to enumerate list of languages.

Add this to .h file

typedef NS_ENUM(NSInteger, AvailableLanguage) {
  ENGLISH,
  GERMAN,
  CHINENSE
};

Now, in .m file simply create an array like,

// Try to use the same naming convention throughout. 
// That is, adding ToString after NS_ENUM name;

NSString* const AvailableLanguageToString[] = {
  [ENGLISH] = @"English",
  [GERMAN]  = @"German",
  [CHINESE] = @"Chinese"
};

Thats it. Now you can use enum with easy and get string for enums using array. For example,

- (void) setPreferredLanguage:(AvailableLanguage)language {
  // this will get the NSString* for the language.
  self.preferredLanguage = AvailableLanguageToString[language];
}

Thus, this pattern depends on accepted naming convention of NS_ENUM and companion ToString array. Try to follow this convention through out and it will become natural.

C# int to enum conversion

Casting should be enough. If you're using C# 3.0 you can make a handy extension method to parse enum values:

public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
    Type type = typeof(TEnum);

    if (value == default(TInput))
    {
        throw new ArgumentException("Value is null or empty.", "value");
    }

    if (!type.IsEnum)
    {
        throw new ArgumentException("Enum expected.", "TEnum");
    }

    return (TEnum)Enum.Parse(type, value.ToString(), true);
}

Get int value from enum in C#

Try this one instead of convert enum to int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}

Easy way to use variables of enum types as string in C?

I thought that a solution like Boost.Fusion one for adapting structs and classes would be nice, they even had it at some point, to use enums as a fusion sequence.

So I made just some small macros to generate the code to print the enums. This is not perfect and has nothing to see with Boost.Fusion generated boilerplate code, but can be used like the Boost Fusion macros. I want to really do generate the types needed by Boost.Fusion to integrate in this infrastructure which allows to print names of struct members, but this will happen later, for now this is just macros :

#ifndef SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP
#define SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP

#include <swissarmyknife/detail/config.hpp>

#include <string>
#include <ostream>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>


#define SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C(                     \
    R, unused, ENUMERATION_ENTRY)                                               \
    case ENUMERATION_ENTRY:                                                     \
      return BOOST_PP_STRINGIZE(ENUMERATION_ENTRY);                             \
    break;                                                                      

/**
 * \brief Adapts ENUM to reflectable types.
 *
 * \param ENUM_TYPE To be adapted
 * \param ENUMERATION_SEQ Sequence of enum states
 */
#define SWISSARMYKNIFE_ADAPT_ENUM(ENUM_TYPE, ENUMERATION_SEQ)                   \
    inline std::string to_string(const ENUM_TYPE& enum_value) {                 \
      switch (enum_value) {                                                     \
      BOOST_PP_SEQ_FOR_EACH(                                                    \
          SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C,                   \
          unused, ENUMERATION_SEQ)                                              \
        default:                                                                \
          return BOOST_PP_STRINGIZE(ENUM_TYPE);                                 \
      }                                                                         \
    }                                                                           \
                                                                                \
    inline std::ostream& operator<<(std::ostream& os, const ENUM_TYPE& value) { \
      os << to_string(value);                                                   \
      return os;                                                                \
    }

#endif

The old answer below is pretty bad, please don't use that. :)

Old answer:

I've been searching a way which solves this problem without changing too much the enums declaration syntax. I came to a solution which uses the preprocessor to retrieve a string from a stringified enum declaration.

I'm able to define non-sparse enums like this :

SMART_ENUM(State, 
    enum State {
        RUNNING,
        SLEEPING, 
        FAULT, 
        UNKNOWN
    })

And I can interact with them in different ways:

// With a stringstream
std::stringstream ss;
ss << State::FAULT;
std::string myEnumStr = ss.str();

//Directly to stdout
std::cout << State::FAULT << std::endl;

//to a string
std::string myStr = State::to_string(State::FAULT);

//from a string
State::State myEnumVal = State::from_string(State::FAULT);

Based on the following definitions :

#define SMART_ENUM(enumTypeArg, ...)                                                     \
namespace enumTypeArg {                                                                  \
    __VA_ARGS__;                                                                         \
    std::ostream& operator<<(std::ostream& os, const enumTypeArg& val) {                 \
            os << swissarmyknife::enums::to_string(#__VA_ARGS__, val);                   \
            return os;                                                                   \
    }                                                                                    \
                                                                                     \
    std::string to_string(const enumTypeArg& val) {                                      \
            return swissarmyknife::enums::to_string(#__VA_ARGS__, val);                  \
    }                                                                                    \
                                                                                     \
    enumTypeArg from_string(const std::string &str) {                                    \
            return swissarmyknife::enums::from_string<enumTypeArg>(#__VA_ARGS__, str);   \
    }                                                                                    \
}                                                                                        \


namespace swissarmyknife { namespace enums {

    static inline std::string to_string(const std::string completeEnumDeclaration, size_t enumVal) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            if (enumVal == count) {
                std::string identifiersSubset = identifiers.substr(0, found);
                size_t beginId = identifiersSubset.find_last_of("{,");
                identifiersSubset = identifiersSubset.substr(beginId+1);
                boost::algorithm::trim(identifiersSubset);
                return identifiersSubset;
            }

            ++count;
        } while (found != std::string::npos);

        throw std::runtime_error("The enum declaration provided doesn't contains this state.");
    }                                                  

    template <typename EnumType>
    static inline EnumType from_string(const std::string completeEnumDeclaration, const std::string &enumStr) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            std::string identifiersSubset = identifiers.substr(0, found);
            size_t beginId = identifiersSubset.find_last_of("{,");
            identifiersSubset = identifiersSubset.substr(beginId+1);
            boost::algorithm::trim(identifiersSubset);

            if (identifiersSubset == enumStr) {
                return static_cast<EnumType>(count);
            }

            ++count;
        } while (found != std::string::npos);

        throw std::runtime_error("No valid enum value for the provided string");
    }                      

}}

When I'll need support for sparse enum and when I'll have more time I'll improve the to_string and from_string implementations with boost::xpressive, but this will costs in compilation time because of the important templating performed and the executable generated is likely to be really bigger. But this has the advantage that it will be more readable and maintanable than this ugly manual string manipulation code. :D

Otherwise I always used boost::bimap to perform such mappings between enums value and string, but it has to be maintained manually.

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

How can I represent an 'Enum' in Python?

Before PEP 435, Python didn't have an equivalent but you could implement your own.

Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...

class Animal:
    DOG = 1
    CAT = 2

x = Animal.DOG

In Python 3.4 (PEP 435), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a name and a value.

class Animal(Enum):
    DOG = 1
    CAT = 2

print(Animal.DOG)
# <Animal.DOG: 1>

print(Animal.DOG.value)
# 1

print(Animal.DOG.name)
# "DOG"

If you don't want to type the values, use the following shortcut:

class Animal(Enum):
    DOG, CAT = range(2)

Enum implementations can be converted to lists and are iterable. The order of its members is the declaration order and has nothing to do with their values. For example:

class Animal(Enum):
    DOG = 1
    CAT = 2
    COW = 0

list(Animal)
# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]

[animal.value for animal in Animal]
# [1, 2, 0]

Animal.CAT in Animal
# True

Map enum in JPA with fixed values?

I would do the folowing:

Declare separetly the enum, in it´s own file:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { this.value = value; }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

Declare a new JPA entity named Right

@Entity
public class Right{
    @Id
    private Integer id;
    //FIElDS

    // constructor
    public Right(RightEnum rightEnum){
          this.id = rightEnum.getValue();
    }

    public Right getInstance(RightEnum rightEnum){
          return new Right(rightEnum);
    }


}

You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)

import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 
 * 
 */
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{

    @Override //this method shoudn´t be used, but I implemented anyway, just in case
    public Integer convertToDatabaseColumn(RightEnum attribute) {
        return attribute.getValue();
    }

    @Override
    public RightEnum convertToEntityAttribute(Integer dbData) {
        return RightEnum.valueOf(dbData);
    }

}

The Authority entity:

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;

  // the **Entity** to map : 
  private Right right;

  // the **Enum** to map (not to be persisted or updated) : 
  @Column(name="COLUMN1", insertable = false, updatable = false)
  @Convert(converter = RightEnumConverter.class)
  private RightEnum rightEnum;

}

By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using

autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example

And if you need to compare, you can use:

authority.getRight().equals( RightEnum.READ ); //for example

Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.


However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).

Let´s see.

The RightEnum:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { 
            try {
                  this.value= value;
                  final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
                  field.setAccessible(true);
                  field.set(this, value);
             } catch (Exception e) {//or use more multicatch if you use JDK 1.7+
                  throw new RuntimeException(e);
            }
      }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

and the Authority entity

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;


  // the **Enum** to map (to be persisted or updated) : 
  @Column(name="COLUMN1")
  @Enumerated(EnumType.ORDINAL)
  private RightEnum rightEnum;

}

In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.

I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.

How can I output the value of an enum class in C++11

It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).

The solution is to write a generic operator<< function which will work for any scoped enum. The solution employs SFINAE via std::enable_if and is as follows.

#include <iostream>
#include <type_traits>

// Scoped enum
enum class Color
{
    Red,
    Green,
    Blue
};

// Unscoped enum
enum Orientation
{
    Horizontal,
    Vertical
};

// Another scoped enum
enum class ExecStatus
{
    Idle,
    Started,
    Running
};

template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
    return stream << static_cast<typename std::underlying_type<T>::type>(e);
}

int main()
{
    std::cout << Color::Blue << "\n";
    std::cout << Vertical << "\n";
    std::cout << ExecStatus::Running << "\n";
    return 0;
}

How to Get enum item name from its value

I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

Java Enum return Int

Font.PLAIN is not an enum. It is just an int. If you need to take the value out of an enum, you can't avoid calling a method or using a .value, because enums are actually objects of its own type, not primitives.

If you truly only need an int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants as int also:

public final class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

    // If you have only static members and want to simulate a static
    // class in Java, then you can make the constructor private.
    private DownloadType() {}
}

By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

and get the "value" using

DownloadType.AUDIO_AND_VIDEO.ordinal()

Edit: Corrected the code.. static class is not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.

Adding a new value to an existing ENUM Type

Complementing @Dariusz 1

For Rails 4.2.1, there's this doc section:

== Transactional Migrations

If the database adapter supports DDL transactions, all migrations will automatically be wrapped in a transaction. There are queries that you can't execute inside a transaction though, and for these situations you can turn the automatic transactions off.

class ChangeEnum < ActiveRecord::Migration
  disable_ddl_transaction!

  def up
    execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  end
end

Pass in an enum as a method parameter

If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

Java: Enum parameter in method

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

Check if enum exists in Java

Most of the answers suggest either using a loop with equals to check if the enum exists or using try/catch with enum.valueOf(). I wanted to know which method is faster and tried it. I am not very good at benchmarking, so please correct me if I made any mistakes.

Heres the code of my main class:

    package enumtest;

public class TestMain {

    static long timeCatch, timeIterate;
    static String checkFor;
    static int corrects;

    public static void main(String[] args) {
        timeCatch = 0;
        timeIterate = 0;
        TestingEnum[] enumVals = TestingEnum.values();
        String[] testingStrings = new String[enumVals.length * 5];
        for (int j = 0; j < 10000; j++) {
            for (int i = 0; i < testingStrings.length; i++) {
                if (i % 5 == 0) {
                    testingStrings[i] = enumVals[i / 5].toString();
                } else {
                    testingStrings[i] = "DOES_NOT_EXIST" + i;
                }
            }

            for (String s : testingStrings) {
                checkFor = s;
                if (tryCatch()) {
                    ++corrects;
                }
                if (iterate()) {
                    ++corrects;
                }
            }
        }

        System.out.println(timeCatch / 1000 + "us for try catch");
        System.out.println(timeIterate / 1000 + "us for iterate");
        System.out.println(corrects);
    }

    static boolean tryCatch() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        try {
            TestingEnum.valueOf(checkFor);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } finally {
            timeEnd = System.nanoTime();
            timeCatch += timeEnd - timeStart;
        }

    }

    static boolean iterate() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        TestingEnum[] values = TestingEnum.values();
        for (TestingEnum v : values) {
            if (v.toString().equals(checkFor)) {
                timeEnd = System.nanoTime();
                timeIterate += timeEnd - timeStart;
                return true;
            }
        }
        timeEnd = System.nanoTime();
        timeIterate += timeEnd - timeStart;
        return false;
    }
}

This means, each methods run 50000 times the lenght of the enum I ran this test multiple times, with 10, 20, 50 and 100 enum constants. Here are the results:

  • 10: try/catch: 760ms | iteration: 62ms
  • 20: try/catch: 1671ms | iteration: 177ms
  • 50: try/catch: 3113ms | iteration: 488ms
  • 100: try/catch: 6834ms | iteration: 1760ms

These results were not exact. When executing it again, there is up to 10% difference in the results, but they are enough to show, that the try/catch method is far less efficient, especially with small enums.

Pick a random value from an enum?

I guess that this single-line-return method is efficient enough to be used in such a simple job:

public enum Day {
    SUNDAY,
    MONDAY,
    THURSDAY,
    WEDNESDAY,
    TUESDAY,
    FRIDAY;

    public static Day getRandom() {
        return values()[(int) (Math.random() * values().length)];
    }

    public static void main(String[] args) {
        System.out.println(Day.getRandom());
    }
}

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

TypeScript enum to object array

You can do that in this way:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

export class GoalProgressMeasurement {
    constructor(public goalProgressMeasurement: GoalProgressMeasurements, public name: string) {
    }
}

export var goalProgressMeasurements: { [key: number]: GoalProgressMeasurement } = {
    1: new GoalProgressMeasurement(GoalProgressMeasurements.Percentage, "Percentage"),
    2: new GoalProgressMeasurement(GoalProgressMeasurements.Numeric_Target, "Numeric Target"),
    3: new GoalProgressMeasurement(GoalProgressMeasurements.Completed_Tasks, "Completed Tasks"),
    4: new GoalProgressMeasurement(GoalProgressMeasurements.Average_Milestone_Progress, "Average Milestone Progress"),
    5: new GoalProgressMeasurement(GoalProgressMeasurements.Not_Measured, "Not Measured"),
}

And you can use it like this:

var gpm: GoalProgressMeasurement = goalProgressMeasurements[GoalProgressMeasurements.Percentage];
var gpmName: string = gpm.name;

var myProgressId: number = 1; // the value can come out of drop down selected value or from back-end , so you can imagine the way of using
var gpm2: GoalProgressMeasurement = goalProgressMeasurements[myProgressId];
var gpmName: string = gpm.name;

You can extend the GoalProgressMeasurement with additional properties of the object as you need. I'm using this approach for every enumeration that should be an object containing more then a value.

Swift: Convert enum value to String?

I like to use Printable with Raw Values.

enum Audience: String, Printable {
    case Public = "Public"
    case Friends = "Friends"
    case Private = "Private"

    var description: String {
        return self.rawValue
    }
}

Then we can do:

let audience = Audience.Public.description // audience = "Public"

or

println("The value of Public is \(Audience.Public)") 
// Prints "The value of Public is Public"

Ways to save enums in database

Unless you have specific performance reasons to avoid it, I would recommend using a separate table for the enumeration. Use foreign key integrity unless the extra lookup really kills you.

Suits table:

suit_id suit_name
1       Clubs
2       Hearts
3       Spades
4       Diamonds

Players table

player_name suit_id
Ian Boyd           4
Shelby Lake        2
  1. If you ever refactor your enumeration to be classes with behavior (such as priority), your database already models it correctly
  2. Your DBA is happy because your schema is normalized (storing a single integer per player, instead of an entire string, which may or may not have typos).
  3. Your database values (suit_id) are independent from your enumeration value, which helps you work on the data from other languages as well.

Best practice to look up Java Enum

You can use a static lookup map to avoid the exception and return a null, then throw as you'd like:

public enum Mammal {
    COW,
    MOUSE,
    OPOSSUM;

    private static Map<String, Mammal> lookup = 
            Arrays.stream(values())
                  .collect(Collectors.toMap(Enum::name, Function.identity()));

    public static Mammal getByName(String name) {
        return lookup.get(name);
    }
}

A 'for' loop to iterate over an enum in Java

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

Cast Int to enum in Java

You can iterate over values() of enum and compare integer value of enum with given id like below:

public enum  TestEnum {
    None(0),
    Value1(1),
    Value2(2),
    Value3(3),
    Value4(4),
    Value5(5);

    private final int value;
    private TestEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static TestEnum  getEnum(int value){
        for (TestEnum e:TestEnum.values()) {
            if(e.getValue() == value)
                return e;
        }
        return TestEnum.None;//For values out of enum scope
    }
}

And use just like this:
TestEnum x = TestEnum.getEnum(4);//Will return TestEnum.Value4
I hope this helps ;)

get enum name from enum value

If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.

import java.util.HashMap;
import java.util.Map;

/**
 * Example of enum with a getter that need a value in parameter, and that return the Choice/Instance 
 * of the enum which has the same value.
 * The value of each choice can be random.
 */
public enum MyEnum {
    /** a random choice */
    Choice1(4),
    /** a nother one */
    Choice2(2),
    /** another one again */
    Choice3(9);
    /** a map that contains every choices of the enum ordered by their value. */
    private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
    static {
        // populating the map
        for (MyEnum myEnum : values()) {
            MY_MAP.put(myEnum.getValue(), myEnum);
        }
    }
    /** the value of the choice */
    private int value;

    /**
     * constructor
     * @param value the value
     */
    private MyEnum(int value) {
        this.value = value;
    }

    /**
     * getter of the value
     * @return int
     */
    public int getValue() {
        return value;
    }

    /**
     * Return one of the choice of the enum by its value.
     * May return null if there is no choice for this value.
     * @param value value
     * @return MyEnum
     */
    public static MyEnum getByValue(int value) {
        return MY_MAP.get(value);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.Enum#toString()
     */
    public String toString() {
        return name() + "=" + value;
    }

    /**
     * Exemple of how to use this class.
     * @param args args
     */
    public static void main(String[] args) {
        MyEnum enum1 = MyEnum.Choice1;
        System.out.println("enum1==>" + String.valueOf(enum1));
        MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
        System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
        MyEnum enum3Unknown = MyEnum.getByValue(4);
        System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
    }
}

Best way to create enum of strings?

Get and set with default values.

public enum Status {

    STATUS_A("Status A"),  STATUS_B("Status B"),

    private String status;

    Status(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

What is the size of an enum in C?

In C language, an enum is guaranteed to be of size of an int. There is a compile time option (-fshort-enums) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Why is enum class preferred over plain enum?

C++11 FAQ mentions below points:

conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.

enum color
{
    Red,
    Green,
    Yellow
};

enum class NewColor
{
    Red_1,
    Green_1,
    Yellow_1
};

int main()
{
    //! Implicit conversion is possible
    int i = Red;

    //! Need enum class name followed by access specifier. Ex: NewColor::Red_1
    int j = Red_1; // error C2065: 'Red_1': undeclared identifier

    //! Implicit converison is not possible. Solution Ex: int k = (int)NewColor::Red_1;
    int k = NewColor::Red_1; // error C2440: 'initializing': cannot convert from 'NewColor' to 'int'

    return 0;
}

conventional enums export their enumerators to the surrounding scope, causing name clashes.

// Header.h

enum vehicle
{
    Car,
    Bus,
    Bike,
    Autorickshow
};

enum FourWheeler
{
    Car,        // error C2365: 'Car': redefinition; previous definition was 'enumerator'
    SmallBus
};

enum class Editor
{
    vim,
    eclipes,
    VisualStudio
};

enum class CppEditor
{
    eclipes,       // No error of redefinitions
    VisualStudio,  // No error of redefinitions
    QtCreator
};

The underlying type of an enum cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

// Header1.h
#include <iostream>

using namespace std;

enum class Port : unsigned char; // Forward declare

class MyClass
{
public:
    void PrintPort(enum class Port p);
};

void MyClass::PrintPort(enum class Port p)
{
    cout << (int)p << endl;
}

.

// Header.h
enum class Port : unsigned char // Declare enum type explicitly
{
    PORT_1 = 0x01,
    PORT_2 = 0x02,
    PORT_3 = 0x04
};

.

// Source.cpp
#include "Header1.h"
#include "Header.h"

using namespace std;
int main()
{
    MyClass m;
    m.PrintPort(Port::PORT_1);

    return 0;
}

What's the proper way to compare a String to an enum value?

Define enum:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enum content:

private boolean enumContainsValue(String value)
{
    for (Gesture gesture : Gesture.values())
    {
        if (gesture.name().equals(value))
        {
            return true;
        }
    }

    return false;
}

And use it:

String gestureString = "PAPER";

if (enumContainsValue(gestureString))
{
    Gesture gestureId = Gesture.valueOf(gestureString);

    switch (gestureId)
    {
        case ROCK:
            Log.i("TAG", "ROCK");
            break;

        case PAPER:
            Log.i("TAG", "PAPER");
            break;

        case SCISSORS:
            Log.i("TAG", "SCISSORS");
            break;
    }
}

How to use enums in C++

You are looking for strongly typed enumerations, a feature available in the C++11 standard. It turns enumerations into classes with scope values.

Using your own code example, it is:

  enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
  Days day = Days::Saturday;

  if (day == Days::Saturday)  {
    cout << " Today is Saturday !" << endl;
  }
  //int day2 = Days::Sunday; // Error! invalid

Using :: as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.

If you are using GCC, enable C+11 with -std=c++11 or -std=gnu11 .

Be happy!

How to easily map c++ enums to strings

I use this solution which I reproduce below:

#define MACROSTR(k) #k

#define X_NUMBERS \
       X(kZero  ) \
       X(kOne   ) \
       X(kTwo   ) \
       X(kThree ) \
       X(kFour  ) \
       X(kMax   )

enum {
#define X(Enum)       Enum,
    X_NUMBERS
#undef X
} kConst;

static char *kConstStr[] = {
#define X(String) MACROSTR(String),
    X_NUMBERS
#undef X
};

int main(void)
{
    int k;
    printf("Hello World!\n\n");

    for (k = 0; k < kMax; k++)
    {
        printf("%s\n", kConstStr[k]);
    }

    return 0;
}

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

Better way to represent array in java properties file

I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Conveniently map between enum and int / String

Use an interface to show it who's boss.

public interface SleskeEnum {
    int id();

    SleskeEnum[] getValues();

}

public enum BonusType implements SleskeEnum {


  MONTHLY(1), YEARLY(2), ONE_OFF(3);

  public final int id;

  BonusType(int id) {
    this.id = id;
  }

  public SleskeEnum[] getValues() {
    return values();
  }

  public int id() { return id; }


}

public class Utils {

  public static SleskeEnum getById(SleskeEnum type, int id) {
      for(SleskeEnum t : type.getValues())
          if(t.id() == id) return t;
      throw new IllegalArgumentException("BonusType does not accept id " + id);
  }

  public static void main(String[] args) {

      BonusType shouldBeMonthly = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly == BonusType.MONTHLY);

      BonusType shouldBeMonthly2 = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly2 == BonusType.YEARLY);

      BonusType shouldBeYearly = (BonusType)getById(BonusType.MONTHLY,2);
      System.out.println(shouldBeYearly  == BonusType.YEARLY);

      BonusType shouldBeOneOff = (BonusType)getById(BonusType.MONTHLY,3);
      System.out.println(shouldBeOneOff == BonusType.ONE_OFF);

      BonusType shouldException = (BonusType)getById(BonusType.MONTHLY,4);
  }
}

And the result:

C:\Documents and Settings\user\My Documents>java Utils
true
false
true
true
Exception in thread "main" java.lang.IllegalArgumentException: BonusType does not accept id 4
        at Utils.getById(Utils.java:6)
        at Utils.main(Utils.java:23)

C:\Documents and Settings\user\My Documents>

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

How to get all enum values in Java?

Here, Role is an enum which contains the following values [ADMIN, USER, OTHER].

List<Role> roleList = Arrays.asList(Role.values());
roleList.forEach(role -> {
    System.out.println(role);
    });

String representation of an Enum

for me, the pragmatic approach is class inside class, sample:

public class MSEModel
{
    class WITS
    {
        public const string DATE = "5005";
        public const string TIME = "5006";
        public const string MD = "5008";
        public const string ROP = "5075";
        public const string WOB = "5073";
        public const string RPM = "7001";
... 
    }

How to check if any flags of a flag combination are set?

Would this work for you?

if ((letter & (Letters.A | Letters.B)) != 0)

How to get an enum value from a string value in Java?

Adding on to the top rated answer, with a helpful utility...

valueOf() throws two different Exceptions in cases where it doesn't like its input.

  • IllegalArgumentException
  • NullPointerExeption

If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...

So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.

private static <T extends Enum<T>> T valueOf( String name , T defaultVal) {
        try {
            return Enum.valueOf(defaultVal.getDeclaringClass() , name);
        } catch (IllegalArgumentException | NullPointerException e) {
            return defaultVal;
        }
    }

Use it like this:

public enum MYTHINGS {
    THINGONE,
    THINGTWO
}

public static void main(String [] asd) {
  valueOf("THINGTWO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGTWO
  valueOf("THINGZERO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGONE
}

How to get all values from python enum class?

Use _member_names_ for a quick easy result if it is just the names, i.e.

Color._member_names_

Also, you have _member_map_ which returns an ordered dictionary of the elements. This function returns a collections.OrderedDict, so you have Color._member_names_.items() and Color._member_names_.values() to play with. E.g.

return list(map(lambda x: x.value, Color._member_map_.values()))

will return all the valid values of Color

Convert Enum to String

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToString and GetName would be that GetName has to verify a few things first:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.

.ToString doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString method doesn't have the same verification issues as the static methods, I would conclude that .ToString is the fastest way to get the value as a string.

Getting attributes of Enum's value

And if you want the full list of names you can do something like

typeof (PharmacyConfigurationKeys).GetFields()
        .Where(x => x.GetCustomAttributes(false).Any(y => typeof(DescriptionAttribute) == y.GetType()))
        .Select(x => ((DescriptionAttribute)x.GetCustomAttributes(false)[0]).Description);

Java: Check if enum contains a given string?

If you are Using Java 8 or above, you can do this :

boolean isPresent(String testString){
      return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}

Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

Getting String value from enum in Java

if status is of type Status enum, status.name() will give you its defined name.

What are enums and why are they useful?

Instead of making a bunch of const int declarations

You can group them all in 1 enum

So its all organized by the common group they belong to

What's the advantage of a Java enum versus a class with public static final fields?

Nobody mentioned the ability to use them in switch statements; I'll throw that in as well.

This allows arbitrarily complex enums to be used in a clean way without using instanceof, potentially confusing if sequences, or non-string/int switching values. The canonical example is a state machine.

What is an idiomatic way of representing enums in Go?

I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types

package main

import "fmt"

type Enum interface {
    name() string
    ordinal() int
    values() *[]string
}

type GenderType uint

const (
    MALE = iota
    FEMALE
)

var genderTypeStrings = []string{
    "MALE",
    "FEMALE",
}

func (gt GenderType) name() string {
    return genderTypeStrings[gt]
}

func (gt GenderType) ordinal() int {
    return int(gt)
}

func (gt GenderType) values() *[]string {
    return &genderTypeStrings
}

func main() {
    var ds GenderType = MALE
    fmt.Printf("The Gender is %s\n", ds.name())
}

This is by far one of the idiomatic ways we could create Enumerated types and use in Go.

Edit:

Adding another way of using constants to enumerate

package main

import (
    "fmt"
)

const (
    // UNSPECIFIED logs nothing
    UNSPECIFIED Level = iota // 0 :
    // TRACE logs everything
    TRACE // 1
    // INFO logs Info, Warnings and Errors
    INFO // 2
    // WARNING logs Warning and Errors
    WARNING // 3
    // ERROR just logs Errors
    ERROR // 4
)

// Level holds the log level.
type Level int

func SetLogLevel(level Level) {
    switch level {
    case TRACE:
        fmt.Println("trace")
        return

    case INFO:
        fmt.Println("info")
        return

    case WARNING:
        fmt.Println("warning")
        return
    case ERROR:
        fmt.Println("error")
        return

    default:
        fmt.Println("default")
        return

    }
}

func main() {

    SetLogLevel(INFO)

}

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

Using Enum values as String literals

You can simply use:

""+ Modes.mode1

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

What's the common practice for enums in Python?

I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

class enumSeason():
    Spring = 0
    Summer = 1
    Fall = 2
    Winter = 3
    def __init__(self, Type):
        self.value = Type
    def __str__(self):
        if self.value == enumSeason.Spring:
            return 'Spring'
        if self.value == enumSeason.Summer:
            return 'Summer'
        if self.value == enumSeason.Fall:
            return 'Fall'
        if self.value == enumSeason.Winter:
            return 'Winter'
    def __eq__(self,y):
       return self.value==y.value

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring

Convert objective-c typedef to its string equivalent

I use a variation on Barry Walk's answer, that in order of importance:

  1. Allows the compiler to check for missing case clauses (it can't if you have a default clause).
  2. Uses an Objective-C typical name (rather than a Java like name).
  3. Raises a specific exception.
  4. Is shorter.

EG:

- (NSString*)describeFormatType:(FormatType)formatType {    
    switch(formatType) {
        case JSON:
            return @"JSON";
        case XML:
            return @"XML";
        case Atom:
            return @"Atom";
        case RSS:
            return @"RSS";
    }
    [NSException raise:NSInvalidArgumentException format:@"The given format type number, %ld, is not known.", formatType];
    return nil; // Keep the compiler happy - does not understand above line never returns!
}

C++: Print out enum value as text

Use the preprocessor:

#define VISIT_ERROR(FIRST, MIDDLE, LAST) \
    FIRST(ErrorA) MIDDLE(ErrorB) /* MIDDLE(ErrorB2) */ LAST(ErrorC)

enum Errors
{
    #define ENUMFIRST_ERROR(E)  E=0,
    #define ENUMMIDDLE_ERROR(E) E,
    #define ENUMLAST_ERROR(E)   E
    VISIT_ERROR(ENUMFIRST_ERROR, ENUMMIDDLE_ERROR, ENUMLAST_ERROR)
    // you might undefine the 3 macros defined above
};

std::string toString(Error e)
{
    switch(e)
    {
    #define CASERETURN_ERROR(E)  case E: return #E;
    VISIT_ERROR(CASERETURN_ERROR, CASERETURN_ERROR, CASERETURN_ERROR)
    // you might undefine the above macro.
    // note that this will produce compile-time error for synonyms in enum;
    // handle those, if you have any, in a distinct macro

    default:
        throw my_favourite_exception();
    }
}

The advantage of this approach is that: - it's still simple to understand, yet - it allows for various visitations (not just string)

If you're willing to drop the first, craft yourself a FOREACH() macro, then #define ERROR_VALUES() (ErrorA, ErrorB, ErrorC) and write your visitors in terms of FOREACH(). Then try to pass a code review :).

How to convert enum names to string in c

An simpler alternative to Hokyo's "Non-Sequential enums" answer, based on using designators to instantiate the string array:

#define NAMES C(RED, 10)C(GREEN, 20)C(BLUE, 30)
#define C(k, v) k = v,
enum color { NAMES };
#undef C

#define C(k, v) [v] = #k,    
const char * const color_name[] = { NAMES };

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

Can my enums have friendly names?

No, but you can use the DescriptionAttribute to accomplish what you're looking for.

How to test enum types?

I agree with aberrant80.

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

I would expand on it by adding that unit testings an Enum can be very useful. If you work in a large code base, build time starts to mount up and a unit test can be a faster way to verify functionality (tests only build their dependencies). Another really big advantage is that other developers cannot change the functionality of your code unintentionally (a huge problem with very large teams).

And with all Test Driven Development, tests around an Enums Methods reduce the number of bugs in your code base.

Simple Example

public enum Multiplier {
    DOUBLE(2.0),
    TRIPLE(3.0);

    private final double multiplier;

    Multiplier(double multiplier) {
        this.multiplier = multiplier;
    }

    Double applyMultiplier(Double value) {
        return multiplier * value;
    }

}

public class MultiplierTest {

    @Test
    public void should() {
        assertThat(Multiplier.DOUBLE.applyMultiplier(1.0), is(2.0));
        assertThat(Multiplier.TRIPLE.applyMultiplier(1.0), is(3.0));
    }
}

How can I declare enums using java

public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

What is a typedef enum in Objective-C?

Update for 64-bit Change: According to apple docs about 64-bit changes,

Enumerations Are Also Typed : In the LLVM compiler, enumerated types can define the size of the enumeration. This means that some enumerated types may also have a size that is larger than you expect. The solution, as in all the other cases, is to make no assumptions about a data type’s size. Instead, assign any enumerated values to a variable with the proper data type

So you have to create enum with type as below syntax if you support for 64-bit.

typedef NS_ENUM(NSUInteger, ShapeType) {
    kCircle,
    kRectangle,
    kOblateSpheroid
};

or

typedef enum ShapeType : NSUInteger {
   kCircle,
   kRectangle,
   kOblateSpheroid
} ShapeType;

Otherwise, it will lead to warning as Implicit conversion loses integer precision: NSUInteger (aka 'unsigned long') to ShapeType

Update for swift-programming:

In swift, there's an syntax change.

enum ControlButtonID: NSUInteger {
        case kCircle , kRectangle, kOblateSpheroid
    }

Enum String Name from Value

For getting the String value [Name]:

EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)GetDBValue();
string stringValue = $"{enumDisplayStatus:G}"; 

And for getting the enum value:

string stringValue = $"{enumDisplayStatus:D}";
SetDBValue(Convert.ToInt32(stringValue ));

How to define an enum with string value?

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
    Comma = ',',
    Tab = '\t',
    Space = ' '
}

(EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
    // TODO: validation
    return ((char) separator).ToString();
}

How do I convert an enum to a list in C#?

List <SomeEnum> theList = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();

How to create enum like type in TypeScript?

As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:

enum TShirtSize {
  Small,
  Medium,
  Large
}

var mySize = TShirtSize.Large;

By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.

Listing 6.2 Enumerations with explicit members

enum TShirtSize {
  Small = 3,
  Medium = 5,
  Large = 8
}

var mySize = TShirtSize.Large;

Both of these examples lifted directly out of TypeScript for JavaScript Programmers.

Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:

Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.

enum TShirtSize {
  Small: 3,
  Medium: 5,
  Large: 8
}

var mySize = TShirtSize.Large;

enum to string in modern C++11 / C++14 / C++17 and future C++20

You could use a reflection library, like Ponder:

enum class MyEnum
{
    Zero = 0,
    One  = 1,
    Two  = 2
};

ponder::Enum::declare<MyEnum>()
    .value("Zero", MyEnum::Zero)
    .value("One",  MyEnum::One)
    .value("Two",  MyEnum::Two);

ponder::EnumObject zero(MyEnum::Zero);

zero.name(); // -> "Zero"

Filling a List with all enum values in Java

private ComboBox gender;
private enum Selgender{Male,Famle};
ObservableList<Object> observableList  =FXCollections.observableArrayList(Selgender.values());

C# how to use enum with switch

All the other answers are correct, but you also need to call your method correctly:

Calculate(5, 5, Operator.PLUS))

And since you use int for left and right, the result will be int as well (3/2 will result in 1). you could cast to double before calculating the result or modify your parameters to accept double

what is the size of an enum type data in C++?

This is a C++ interview test question not homework.

Then your interviewer needs to refresh his recollection with how the C++ standard works. And I quote:

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.

The whole "whose underlying type is not fixed" part is from C++11, but the rest is all standard C++98/03. In short, the sizeof(months_t) is not 4. It is not 2 either. It could be any of those. The standard does not say what size it should be; only that it should be big enough to fit any enumerator.

why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?

Because enums are not variables. The members of an enum are not actual variables; they're just a semi-type-safe form of #define. They're a way of storing a number in a reader-friendly format. The compiler will transform all uses of an enumerator into the actual numerical value.

Enumerators are just another way of talking about a number. january is just shorthand for 0. And how much space does 0 take up? It depends on what you store it in.

How to use enums as flags in C++?

Currently there is no language support for enum flags, Meta classes might inherently add this feature if it would ever be part of the c++ standard.

My solution would be to create enum-only instantiated template functions adding support for type-safe bitwise operations for enum class using its underlying type:

File: EnumClassBitwise.h

#pragma once
#ifndef _ENUM_CLASS_BITWISE_H_
#define _ENUM_CLASS_BITWISE_H_

#include <type_traits>

//unary ~operator    
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator~ (Enum& val)
{
    val = static_cast<Enum>(~static_cast<std::underlying_type_t<Enum>>(val));
    return val;
}

// & operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator& (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
}

// &= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator&= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

//| operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator| (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
}
//|= operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator|= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

#endif // _ENUM_CLASS_BITWISE_H_

For convenience and for reducing mistakes, you might want to wrap your bit flags operations for enums and for integers as well:

File: BitFlags.h

#pragma once
#ifndef _BIT_FLAGS_H_
#define _BIT_FLAGS_H_

#include "EnumClassBitwise.h"

 template<typename T>
 class BitFlags
 {
 public:

     constexpr inline BitFlags() = default;
     constexpr inline BitFlags(T value) { mValue = value; }
     constexpr inline BitFlags operator| (T rhs) const { return mValue | rhs; }
     constexpr inline BitFlags operator& (T rhs) const { return mValue & rhs; }
     constexpr inline BitFlags operator~ () const { return ~mValue; }
     constexpr inline operator T() const { return mValue; }
     constexpr inline BitFlags& operator|=(T rhs) { mValue |= rhs; return *this; }
     constexpr inline BitFlags& operator&=(T rhs) { mValue &= rhs; return *this; }
     constexpr inline bool test(T rhs) const { return (mValue & rhs) == rhs; }
     constexpr inline void set(T rhs) { mValue |= rhs; }
     constexpr inline void clear(T rhs) { mValue &= ~rhs; }

 private:
     T mValue;
 };
#endif //#define _BIT_FLAGS_H_

Possible usage:

#include <cstdint>
#include <BitFlags.h>
void main()
{
    enum class Options : uint32_t
    { 
          NoOption = 0 << 0
        , Option1  = 1 << 0
        , Option2  = 1 << 1
        , Option3  = 1 << 2
        , Option4  = 1 << 3
    };

    const uint32_t Option1 = 1 << 0;
    const uint32_t Option2 = 1 << 1;
    const uint32_t Option3 = 1 << 2;
    const uint32_t Option4 = 1 << 3;

   //Enum BitFlags
    BitFlags<Options> optionsEnum(Options::NoOption);
    optionsEnum.set(Options::Option1 | Options::Option3);

   //Standard integer BitFlags
    BitFlags<uint32_t> optionsUint32(0);
    optionsUint32.set(Option1 | Option3); 

    return 0;
}

How to get names of enum entries?

Using a current version TypeScript you can use functions like these to map the Enum to a record of your choosing. Note that you cannot define string values with these functions as they look for keys with a value that is a number.

enum STATES {
  LOGIN,
  LOGOUT,
}

export const enumToRecordWithKeys = <E extends any>(enumeration: E): E => (
  Object.keys(enumeration)
    .filter(key => typeof enumeration[key] === 'number')
    .reduce((record, key) => ({...record, [key]: key }), {}) as E
);

export const enumToRecordWithValues = <E extends any>(enumeration: E): E => (
  Object.keys(enumeration)
    .filter(key => typeof enumeration[key] === 'number')
    .reduce((record, key) => ({...record, [key]: enumeration[key] }), {}) as E
);

const states = enumToRecordWithKeys(STATES)
const statesWithIndex = enumToRecordWithValues(STATES)

console.log(JSON.stringify({
  STATES,
  states,
  statesWithIndex,
}, null ,2));

// Console output:
{
  "STATES": {
    "0": "LOGIN",
    "1": "LOGOUT",
    "LOGIN": 0,
    "LOGOUT": 1
  },
  "states": {
    "LOGIN": "LOGIN",
    "LOGOUT": "LOGOUT"
  },
  "statesWithIndex": {
    "LOGIN": 0,
    "LOGOUT": 1
  }
}

Why do you use typedef when declaring an enum in C++?

You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.

typedef enum MyEnum { 
  //...
} MyEnum;

allowed functions taking a parameter of the enum to be defined as

void f( MyEnum x )

instead of the longer

void f( enum MyEnum x )

Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.

In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.

// C++
enum MyEnum {
   // ...
};
void f( MyEnum x ); // Correct C++, Error in C

Comparing Java enum members: == or equals()?

In short, both have pros and cons.

On one hand, it has advantages to use ==, as described in the other answers.

On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used == bites you. (BTDT.)

ProgressDialog is deprecated.What is the alternate one to use?

ProgressDialog was deprecated in API level 26 .

"Deprecated" refers to functions or elements that are in the process of being replaced by newer ones.

ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI.

Advantage

I would personally say that ProgressBar has the edge over the two .ProgressBar is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.

SecurityError: The operation is insecure - window.history.pushState()

Make sure you are following the Same Origin Policy. This means same domain, same subdomain, same protocol (http vs https) and same port.

How does pushState protect against potential content forgeries?

EDIT: As @robertc aptly pointed out in his comment, some browsers actually implement slightly different security policies when the origin is file:///. Not to mention you can encounter problems when testing locally with file:/// when the page expects it is running from a different origin (and so your pushState assumes production origin scenarios, not localhost scenarios)

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Use table row coloring for cells in Bootstrap

With less you can set it up like this;

.table tbody tr {
    &.error > td { background-color: red !important; }
    &.error:hover > td { background-color: yellow !important; }
    &.success > td { background-color: green !important; }
    &.success:hover > td { background-color: yellow !important; }
    ...
}

That did the trick for me.

How do I extract a substring from a string until the second space is encountered?

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

how to store Image as blob in Sqlite & how to retrieve it?

for a ionic project


    var imgURI       = "";
    var imgBBDD      = ""; //sqllite for save into

    function takepicture() {
                var options = {
                    quality : 75,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,
                    allowEdit : true,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 300,
                    targetHeight: 300,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(function(imageData) {
                    imgURI = "data:image/jpeg;base64," + imageData;
                    imgBBDD = imageData;
                }, function(err) {
                    // An error occured. Show a message to the user
                });
            }

And now we put imgBBDD into SqlLite


     function saveImage = function (theId, theimage){
      var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
      console.log('>>>>>>>');
      DDBB.SelectQuery(insertQuery)
                    .then( function(result) {
                        console.log("Image saved");
                    })
                    .catch( function(err) 
                     {
                        deferred.resolve(err);
                        return cb(err);
                    });
    }

A server side (php)


        $request = file_get_contents("php://input"); // gets the raw data
        $dades = json_decode($request,true); // true for return as array


    if($dades==""){
            $array = array();
            $array['error'] = -1;
            $array['descError'] = "Error when get the file";
            $array['logError'] = '';
            echo json_encode($array);
            exit;
        }
        //send the image again to the client
        header('Content-Type: image/jpeg');
        echo '';

Can an ASP.NET MVC controller return an Image?

Use the base controllers File method.

public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.
    return base.File(path, "image/jpeg");
}

As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (http://localhost/MyController/Image/MyImage) and through the direct URL (http://localhost/Images/MyImage.jpg) and the results were:

  • MVC: 7.6 milliseconds per photo
  • Direct: 6.7 milliseconds per photo

Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.

correct way of comparing string jquery operator =

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

Eclipse/Java code completion not working

I had this problem and like @Marc, only on a particular class. I discovered that I needed to designate Open With = Java Editor. As a Eclipse newbie I hadn't even realized that I was just using a plain text editor.

In the package explorer, right-click the file and chose "Open With".

Reading binary file and looping over each byte

This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.

In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.

First, here are the results for what currently are the latest versions of Python 2 & 3:

Fastest to slowest execution speeds with 32-bit Python 2.7.16
  numpy version 1.16.5
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1                  Tcll (array.array) :   3.8943 secs, rel speed   1.00x,   0.00% slower (262.95 KiB/sec)
2  Vinay Sajip (read all into memory) :   4.1164 secs, rel speed   1.06x,   5.71% slower (248.76 KiB/sec)
3            codeape + iter + partial :   4.1616 secs, rel speed   1.07x,   6.87% slower (246.06 KiB/sec)
4                             codeape :   4.1889 secs, rel speed   1.08x,   7.57% slower (244.46 KiB/sec)
5               Vinay Sajip (chunked) :   4.1977 secs, rel speed   1.08x,   7.79% slower (243.94 KiB/sec)
6           Aaron Hall (Py 2 version) :   4.2417 secs, rel speed   1.09x,   8.92% slower (241.41 KiB/sec)
7                     gerrit (struct) :   4.2561 secs, rel speed   1.09x,   9.29% slower (240.59 KiB/sec)
8                     Rick M. (numpy) :   8.1398 secs, rel speed   2.09x, 109.02% slower (125.80 KiB/sec)
9                           Skurmedel :  31.3264 secs, rel speed   8.04x, 704.42% slower ( 32.69 KiB/sec)

Benchmark runtime (min:sec) - 03:26

Fastest to slowest execution speeds with 32-bit Python 3.8.0
  numpy version 1.17.4
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1  Vinay Sajip + "yield from" + "walrus operator" :   3.5235 secs, rel speed   1.00x,   0.00% slower (290.62 KiB/sec)
2                       Aaron Hall + "yield from" :   3.5284 secs, rel speed   1.00x,   0.14% slower (290.22 KiB/sec)
3         codeape + iter + partial + "yield from" :   3.5303 secs, rel speed   1.00x,   0.19% slower (290.06 KiB/sec)
4                      Vinay Sajip + "yield from" :   3.5312 secs, rel speed   1.00x,   0.22% slower (289.99 KiB/sec)
5      codeape + "yield from" + "walrus operator" :   3.5370 secs, rel speed   1.00x,   0.38% slower (289.51 KiB/sec)
6                          codeape + "yield from" :   3.5390 secs, rel speed   1.00x,   0.44% slower (289.35 KiB/sec)
7                                      jfs (mmap) :   4.0612 secs, rel speed   1.15x,  15.26% slower (252.14 KiB/sec)
8              Vinay Sajip (read all into memory) :   4.5948 secs, rel speed   1.30x,  30.40% slower (222.86 KiB/sec)
9                        codeape + iter + partial :   4.5994 secs, rel speed   1.31x,  30.54% slower (222.64 KiB/sec)
10                                        codeape :   4.5995 secs, rel speed   1.31x,  30.54% slower (222.63 KiB/sec)
11                          Vinay Sajip (chunked) :   4.6110 secs, rel speed   1.31x,  30.87% slower (222.08 KiB/sec)
12                      Aaron Hall (Py 2 version) :   4.6292 secs, rel speed   1.31x,  31.38% slower (221.20 KiB/sec)
13                             Tcll (array.array) :   4.8627 secs, rel speed   1.38x,  38.01% slower (210.58 KiB/sec)
14                                gerrit (struct) :   5.0816 secs, rel speed   1.44x,  44.22% slower (201.51 KiB/sec)
15                 Rick M. (numpy) + "yield from" :  11.8084 secs, rel speed   3.35x, 235.13% slower ( 86.72 KiB/sec)
16                                      Skurmedel :  11.8806 secs, rel speed   3.37x, 237.18% slower ( 86.19 KiB/sec)
17                                Rick M. (numpy) :  13.3860 secs, rel speed   3.80x, 279.91% slower ( 76.50 KiB/sec)

Benchmark runtime (min:sec) - 04:47

I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.

Here's the code used to do the benchmarking:

from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback

try:
    xrange
except NameError:  # Python 3
    xrange = range


class KiB(int):
    """ KibiBytes - multiples of the byte units for quantities of information. """
    def __new__(self, value=0):
        return 1024*value


BIG_TEST_FILE = 1  # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100  # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3  # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
    FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
    FILE_SIZE = SML_TEST_FILE  # For quicker testing.

# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
    # Make accessible in algorithms.
    from __main__ import array, deque, get_buffer_size, mmap, np, struct
    from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
    from functools import partial
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
""")


def get_buffer_size(path):
    """ Determine optimal buffer size for reading files. """
    st = os.stat(path)
    try:
        bufsize = st.st_blksize # Available on some Unix systems (like Linux)
    except AttributeError:
        bufsize = io.DEFAULT_BUFFER_SIZE
    return bufsize

# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
    # Verify generator reads correct number of bytes (assumes values are correct).
    bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
    assert bytes_read == FILE_SIZE, \
           'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
                bytes_read, FILE_SIZE)
"""

TIMING = namedtuple('TIMING', 'label, exec_time')

class Algorithm(namedtuple('CodeFragments', 'setup, test')):

    # Default timeit "stmt" code fragment.
    _TEST = """
        #for b in file_byte_iterator(TEMP_FILENAME):  # Loop over every byte.
        #    pass  # Do stuff with byte...
        deque(file_byte_iterator(TEMP_FILENAME), maxlen=0)  # Data sink.
    """

    # Must overload __new__ because (named)tuples are immutable.
    def __new__(cls, setup, test=None):
        """ Dedent (unindent) code fragment string arguments.
        Args:
          `setup` -- Code fragment that defines things used by `test` code.
                     In this case it should define a generator function named
                     `file_byte_iterator()` that will be passed that name of a test file
                     of binary data. This code is not timed.
          `test` -- Code fragment that uses things defined in `setup` code.
                    Defaults to _TEST. This is the code that's timed.
        """
        test =  cls._TEST if test is None else test  # Use default unless one is provided.

        # Uncomment to replace all performance tests with one that verifies the correct
        # number of bytes values are being generated by the file_byte_iterator function.
        #test = VERIFY_NUM_READ

        return tuple.__new__(cls, (dedent(setup), dedent(test)))


algorithms = {

    'Aaron Hall (Py 2 version)': Algorithm("""
        def file_byte_iterator(path):
            with open(path, "rb") as file:
                callable = partial(file.read, 1024)
                sentinel = bytes() # or b''
                for chunk in iter(callable, sentinel):
                    for byte in chunk:
                        yield byte
    """),

    "codeape": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                while True:
                    chunk = f.read(chunksize)
                    if chunk:
                        for b in chunk:
                            yield b
                    else:
                        break
    """),

    "codeape + iter + partial": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                for chunk in iter(partial(f.read, chunksize), b''):
                    for b in chunk:
                        yield b
    """),

    "gerrit (struct)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                fmt = '{}B'.format(FILE_SIZE)  # Reads entire file at once.
                for b in struct.unpack(fmt, f.read()):
                    yield b
    """),

    'Rick M. (numpy)': Algorithm("""
        def file_byte_iterator(filename):
            for byte in np.fromfile(filename, 'u1'):
                yield byte
    """),

    "Skurmedel": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                byte = f.read(1)
                while byte:
                    yield byte
                    byte = f.read(1)
    """),

    "Tcll (array.array)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                arr = array.array('B')
                arr.fromfile(f, FILE_SIZE)  # Reads entire file at once.
                for b in arr:
                    yield b
    """),

    "Vinay Sajip (read all into memory)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                bytes_read = f.read()  # Reads entire file at once.
            for b in bytes_read:
                yield b
    """),

    "Vinay Sajip (chunked)": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                chunk = f.read(chunksize)
                while chunk:
                    for b in chunk:
                        yield b
                    chunk = f.read(chunksize)
    """),

}  # End algorithms

#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
    algorithms.update({

        'codeape + iter + partial + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    for chunk in iter(partial(f.read, chunksize), b''):
                        yield from chunk
        """),

        'codeape + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while True:
                        chunk = f.read(chunksize)
                        if chunk:
                            yield from chunk
                        else:
                            break
        """),

        "jfs (mmap)": Algorithm("""
            def file_byte_iterator(filename):
                with open(filename, "rb") as f, \
                     mmap(f.fileno(), 0, access=ACCESS_READ) as s:
                    yield from s
        """),

        'Rick M. (numpy) + "yield from"': Algorithm("""
            def file_byte_iterator(filename):
            #    data = np.fromfile(filename, 'u1')
                yield from np.fromfile(filename, 'u1')
        """),

        'Vinay Sajip + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    chunk = f.read(chunksize)
                    while chunk:
                        yield from chunk  # Added in Py 3.3
                        chunk = f.read(chunksize)
        """),

    })  # End Python 3.3 update.

if sys.version_info >= (3, 5):
    algorithms.update({

        'Aaron Hall + "yield from"': Algorithm("""
            from pathlib import Path

            def file_byte_iterator(path):
                ''' Given a path, return an iterator over the file
                    that lazily loads the file.
                '''
                path = Path(path)
                bufsize = get_buffer_size(path)

                with path.open('rb') as file:
                    reader = partial(file.read1, bufsize)
                    for chunk in iter(reader, bytes()):
                        yield from chunk
        """),

    })  # End Python 3.5 update.

if sys.version_info >= (3, 8, 0):
    algorithms.update({

        'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk  # Added in Py 3.3
        """),

        'codeape + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk
        """),

    })  # End Python 3.8.0 update.update.


#### Main ####

def main():
    global TEMP_FILENAME

    def cleanup():
        """ Clean up after testing is completed. """
        try:
            os.remove(TEMP_FILENAME)  # Delete the temporary file.
        except Exception:
            pass

    atexit.register(cleanup)

    # Create a named temporary binary file of pseudo-random bytes for testing.
    fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
    with os.fdopen(fd, 'wb') as file:
         os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))

    # Execute and time each algorithm, gather results.
    start_time = time.time()  # To determine how long testing itself takes.

    timings = []
    for label in algorithms:
        try:
            timing = TIMING(label,
                            min(timeit.repeat(algorithms[label].test,
                                              setup=COMMON_SETUP + algorithms[label].setup,
                                              repeat=TIMINGS, number=EXECUTIONS)))
        except Exception as exc:
            print('{} occurred timing the algorithm: "{}"\n  {}'.format(
                    type(exc).__name__, label, exc))
            traceback.print_exc(file=sys.stdout)  # Redirect to stdout.
            sys.exit(1)
        timings.append(timing)

    # Report results.
    print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
            64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
    print('  numpy version {}'.format(np.version.full_version))
    print('  Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
    print('  {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
    print()

    longest = max(len(timing.label) for timing in timings)  # Len of longest identifier.
    ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
    fastest = ranked[0].exec_time
    for rank, timing in enumerate(ranked, 1):
        print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
              '({:6.2f} KiB/sec)'.format(
                    rank,
                    timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
                    round((timing.exec_time/fastest - 1) * 100, 2),
                    (FILE_SIZE/timing.exec_time) / KiB(1),  # per sec.
                    width=longest))
    print()
    mins, secs = divmod(time.time()-start_time, 60)
    print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
                                                               int(round(secs))))

main()

How to compare two floating point numbers in Bash?

Using bashj (https://sourceforge.net/projects/bashj/ ), a bash mutant with java support, you just write (and it IS easy to read):

#!/usr/bin/bashj

#!java
static int doubleCompare(double a,double b) {return((a>b) ? 1 : (a<b) ? -1 : 0);}

#!bashj
num1=3.17648e-22
num2=1.5
comp=j.doubleCompare($num1,$num2)
if [ $comp == 0 ] ; then echo "Equal" ; fi
if [ $comp == 1 ] ; then echo "$num1 > $num2" ; fi
if [ $comp == -1 ] ; then echo "$num2 > $num1" ; fi

Of course bashj bash/java hybridation offers much more...

Dynamically updating css in Angular 2

Check working Demo here

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';

import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';

@Component({
  selector: 'my-app',
    template: `
    <style>
       .myStyle{
        width:200px;
        height:100px;
        border:1px solid;
        margin-top:20px;
        background:gray;
        text-align:center;
       }
    </style>

          <div [class.myStyle]="my" [style.background-color]="randomColor" [style.width]="width+'px'" [style.height]="height+'px'"> my width={{width}} & height={{height}}</div>
    `,
    directives: []
})

export class AppComponent {
  my:boolean=true;
  width:number=200px;
  height:number=100px;
  randomColor;
  randomNumber;
  intervalId;
  textArray = [
    'blue',
    'green',
    'yellow',
    'orange',
    'pink'
  ];


  constructor() 
  {
    this.start();
  }

      start()
      { 
        this.randomNumber = Math.floor(Math.random()*this.textArray.length);
        this.randomColor=this.textArray[this.randomNumber];
        console.log('start' + this.randomNumber);
        this.intervalId = setInterval(()=>{
         this.width=this.width+20;
         this.height=this.height+10;
         console.log(this.width +" "+ this.height)
         if(this.width==300)
         {
           this.stop();
         }

        }, 1000);
      }
      stop()
      {
        console.log('stop');
        clearInterval(this.intervalId);
        this.width=200;
        this.height=100;
        this.start();

      }
 }

bootstrap(AppComponent, []);

CSS : center form in page horizontally and vertically

you can use display:flex to do this : http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}

or display:table http://codepen.io/anon/pen/LACnF/

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* shrinks to fit content */
    margin:auto;
}

Get the position of a spinner in Android

    final int[] positions=new int[2]; 
    Spinner sp=findViewByID(R.id.spinner);

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            Toast.makeText( arg2....);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

Jaxb, Class has two properties of the same name

just added this to my class

@XmlAccessorType(XmlAccessType.FIELD)

worked like a cham

Insert json file into mongodb

mongoimport --jsonArray  -d DatabaseN -c collectionName /filePath/filename.json

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

jQuery how to find an element based on a data-attribute value?

in case you don't want to type all that, here's a shorter way to query by data attribute:

$("ul[data-slide='" + current +"']");

FYI: http://james.padolsey.com/javascript/a-better-data-selector-for-jquery/

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

_method hidden field workaround

Used in Rails and could be adapted to any framework:

  • add a hidden _method parameter to any form that is not GET or POST:

    <input type="hidden" name="_method" value="DELETE">
    

    This can be done automatically in frameworks through the HTML creation helper method (e.g. Rails form_tag)

  • fix the actual form method to POST (<form method="post")

  • processes _method on the server and do exactly as if that method had been sent instead of the actual POST

Rationale / history of why it is not possible: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

How to make div occupy remaining height?

I tried with CSS, and or you need to use display: table or you need to use new css that is not yet supported on most browsers (2016).

So, I wrote a jquery plugin to do it for us, I am happy to share it:

_x000D_
_x000D_
 _x000D_
//Credit Efy Teicher_x000D_
$(document).ready(function () {_x000D_
            $(".fillHight").fillHeight();_x000D_
            $(".fillWidth").fillWidth();_x000D_
        });_x000D_
_x000D_
        window.onresize = function (event) {_x000D_
            $(".fillHight").fillHeight();_x000D_
            $(".fillWidth").fillWidth();_x000D_
        }_x000D_
_x000D_
        $.fn.fillHeight = function () {_x000D_
            var siblingsHeight = 0;_x000D_
            this.siblings("div").each(function () {_x000D_
                siblingsHeight = siblingsHeight + $(this).height();_x000D_
            });_x000D_
_x000D_
            var height = this.parent().height() - siblingsHeight;_x000D_
            this.height(height);_x000D_
        };_x000D_
_x000D_
 _x000D_
        $.fn.fillWidth = function (){_x000D_
            var siblingsWidth = 0;_x000D_
            this.siblings("div").each(function () {_x000D_
                siblingsWidth  += $(this).width();_x000D_
            });_x000D_
_x000D_
            var width =this.parent().width() - siblingsWidth;_x000D_
            this.width(width);_x000D_
        }
_x000D_
      * {_x000D_
            box-sizing: border-box;_x000D_
        }_x000D_
_x000D_
        html {_x000D_
        }_x000D_
_x000D_
        html, body, .fillParent {_x000D_
            height: 100%;_x000D_
            margin: 0;_x000D_
            padding: 0;_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div class="fillParent" style="background-color:antiquewhite">_x000D_
        <div>_x000D_
            no1_x000D_
        </div>_x000D_
        <div class="fillHight">_x000D_
            no2 fill_x000D_
        </div>_x000D_
        <div class="deb">_x000D_
            no3_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

ImportError: No module named request

You can do that using Python 2.

  1. Remove request
  2. Make that line: from urllib2 import urlopen

You cannot have request in Python 2, you need to have Python 3 or above.

Where is web.xml in Eclipse Dynamic Web Project

Might be your project is not JEE nature, to do this Right Click -> Properties -> Project Facets and click Convert to facet and check dynamic web module and ok. Now you will be able to see Java EE Tools.

How to load up CSS files using Javascript?

Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

function loadStyle(src) {
    return new Promise(function (resolve, reject) {
        let link = document.createElement('link');
        link.href = src;
        link.rel = 'stylesheet';

        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`Style load error for ${src}`));

        document.head.append(link);
    });
}

You can implement it as follows:

window.onload = function () {
    loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
        .then(() => loadStyle("css/style.css"))
        .then(() => loadStyle("css/icomoon.css"))
        .then(() => {
            alert('All styles are loaded!');
        }).catch(err => alert(err));
}

It's really cool, right? This is a way to decide the priority of the styles using Promises.

To see a multi-style loading implementation see: https://stackoverflow.com/a/63936671/13720928

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.dev.khamsat"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

How do I round a float upwards to the nearest int in C#?

If you want to round to the nearest int:

int rounded = (int)Math.Round(precise, 0);

You can also use:

int rounded = Convert.ToInt32(precise);

Which will use Math.Round(x, 0); to round and cast for you. It looks neater but is slightly less clear IMO.


If you want to round up:

int roundedUp = (int)Math.Ceiling(precise);

How to include quotes in a string

Escape them with backslashes.

"I want to learn \"C#\""

What does enumerate() mean?

The enumerate() function adds a counter to an iterable.

So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

Demo:

>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
...     print elem
... 
foo
bar
baz
>>> for count, elem in enumerate(elements):
...     print count, elem
... 
0 foo
1 bar
2 baz

By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

>>> for count, elem in enumerate(elements, 42):
...     print count, elem
... 
42 foo
43 bar
44 baz

If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

from itertools import count

def enumerate(it, start=0):
    # return an iterator that adds a counter to each element of it
    return zip(count(start), it)

and

def enumerate(it, start=0):
    count = start
    for elem in it:
        yield (count, elem)
        count += 1

The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).

Delete files or folder recursively on Windows CMD

After the blog post How Can I Use Windows PowerShell to Delete All the .TMP Files on a Drive?, you can use something like this to delete all .tmp for example from a folder and all subfolders in PowerShell:

get-childitem [your path/ or leave empty for current path] -include
*.tmp -recurse | foreach ($_) {remove-item $_.fullname}

PHP is_numeric or preg_match 0-9 validation

If you're only checking if it's a number, is_numeric() is much much better here. It's more readable and a bit quicker than regex.

The issue with your regex here is that it won't allow decimal values, so essentially you've just written is_int() in regex. Regular expressions should only be used when there is a non-standard data format in your input; PHP has plenty of built in validation functions, even an email validator without regex.

TypeScript function overloading

This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.

TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.

Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

React - clearing an input value after form submit

In your onHandleSubmit function, set your state to {city: ''} again like this :

this.setState({ city: '' });

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

How to config routeProvider and locationProvider in angularJS?

you could try:

<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>

<div>
    <div ng-view=""></div>
</div>

How to apply color in Markdown?

This works in the note-taking Joplin:

<span style="color:red">text in red</span>

Python update a key in dict if it doesn't exist

Since Python 3.9 you can use the merge operator | to merge two dictionaries. The dict on the right takes precedence:

new_dict = old_dict | { key: val }

For example:

new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }

print(new_dict} # {'a': 1, 'b': 42}

Note: this creates a new dictionary with the updated values.

MS SQL Date Only Without Time

Yes, T-SQL can feel extremely primitive at times, and it is things like these that often times push me to doing a lot of my logic in my language of choice (such as C#).

However, when you absolutely need to do some of these things in SQL for performance reasons, then your best bet is to create functions to house these "algorithms."

Take a look at this article. He offers up quite a few handy SQL functions along these lines that I think will help you.

http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx

How to center a "position: absolute" element

Just use display: flex and justify-content: center on the parent element

_x000D_
_x000D_
body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align: center;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
    display: flex;
    justify-content: center;
}

ul#slideshow li {
    position: absolute;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 100px;
}
_x000D_
<body>
   <div id="slideshowWrapper">
      <ul id="slideshow">
         <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
         <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
      </ul>
   </div>
</body>

<!-- Images from Unsplash-->
_x000D_
_x000D_
_x000D_

You can find this solution in JSFIDDLE

C#: Waiting for all threads to complete

I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do

if(!thread.Join(End-now))
    throw new NotFinishedInTime();

How to subtract X days from a date using Java calendar?

Taken from the docs here:

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

Location of my.cnf file on macOS

Copy /usr/local/opt/mysql/support-files/my-default.cnf as /etc/my.cnf or /etc/mysql/my.cnf and then restart mysql.

Semi-transparent color layer over background-image?

Here is a more simple trick with only css.

_x000D_
_x000D_
<div class="background"> </div>_x000D_
    <style>_x000D_
    .background {_x000D_
      position:relative;_x000D_
      height:50px;_x000D_
      background-color: rgba(248, 247, 216, 0.7);_x000D_
      background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAJElEQVQYV2NctWrVfwYkEBYWxojMZ6SDAmT7QGx0K1EcRBsFAADeG/3M/HteAAAAAElFTkSuQmCC); _x000D_
    }_x000D_
_x000D_
    .background:after {_x000D_
        content:" ";_x000D_
        background-color:inherit;_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        width: 100%;_x000D_
        height: 100%; _x000D_
    }_x000D_
_x000D_
    </style>
_x000D_
_x000D_
_x000D_

Matplotlib make tick labels font size smaller

The following worked for me:

ax2.xaxis.set_tick_params(labelsize=7)
ax2.yaxis.set_tick_params(labelsize=7)

The advantage of the above is you do not need to provide the array of labels and works with any data on the axes.

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

How do I find out which computer is the domain controller in Windows programmatically?

With the most simple programming language: DOS batch

echo %LOGONSERVER%

Adding an .env file to React Project

4 steps

  1. npm install dotenv --save

  2. Next add the following line to your app.

    require('dotenv').config()

  3. Then create a .env file at the root directory of your application and add the variables to it.

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

NOTE - Need to restart application after adding variable in .env file.

Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

Web-scraping JavaScript page with Python

You can also execute javascript using webdriver.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get(url)
driver.execute_script('document.title')

or store the value in a variable

result = driver.execute_script('var text = document.title ; return var')

How to combine class and ID in CSS selector?

Ids are supposed to be unique document wide, so you shouldn't have to select based on both. You can assign an element multiple classes though with class="class1 class2"

Setting a windows batch file variable to the day of the week

%DATE% is not your friend. Because the %DATE% environment variable (and the DATE command) returns the current date using the Windows short date format that is fully and endlessly customizable. One user may configure the system to return 07/06/2012 while another might choose Fri060712. Using %DATE% is a complete nightmare for a BAT programmer.

There are two possible approaches to solve this problem:

  1. You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value HKCU\Control Panel\International\sShortDate, to your recognizable format. Then access %DATE% to get the date in the format you want; and finally restore the format back to the original user format. Something like this

    reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f >nul
    reg add "HKCU\Control Panel\International" /v sShortDate /d "ddd" /f >nul
    set DOW=%DATE%
    reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f >nul
    

    but this method has two problems:

    • it tampers with a global registry value for its local particular purpouses, so it may interfere with other processes or user tasks that at the very same time query the date in short date format, including itself if run simultaneously.

    • and it returns the three letter day of the week in the local language that may be different in different systems or different users.

  2. use WMIC Win32_LocalTime, that returns the date in a convenient way to directly parse it with a FOR command.

    FOR /F "skip=1" %%A IN ('WMIC Path Win32_LocalTime Get DayOfWeek' ) DO (
      set DOW=%%A
    )
    

    this is the method I recommend.

php get values from json encode

json_decode() will return an object or array if second value it's true:

$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];

Extract parameter value from url using regular expressions

v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk

In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString

HttpUtility.ParseQueryString(url)["v"];

And you don't even need to check the key, as it will return null if the key is not in the collection.

Standardize data columns in R

Scale can be used for both full data frame and specific columns. For specific columns, following code can be used:

trainingSet[, 3:7] = scale(trainingSet[, 3:7]) # For column 3 to 7
trainingSet[, 8] = scale(trainingSet[, 8]) # For column 8 

Full data frame

trainingSet <- scale(trainingSet)

How do I use reflection to call a generic method?

Adding on to Adrian Gallero's answer:

Calling a generic method from type info involves three steps.

TLDR: Calling a known generic method with a type object can be accomplished by:

((Action)GenericMethod<object>)
    .Method
    .GetGenericMethodDefinition()
    .MakeGenericMethod(typeof(string))
    .Invoke(this, null);

where GenericMethod<object> is the method name to call and any type that satisfies the generic constraints.

(Action) matches the signature of the method to be called i.e. (Func<string,string,int> or Action<bool>)

Step 1 is getting the MethodInfo for the generic method definition

Method 1: Use GetMethod() or GetMethods() with appropriate types or binding flags.

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");

Method 2: Create a delegate, get the MethodInfo object and then call GetGenericMethodDefinition

From inside the class that contains the methods:

MethodInfo method = ((Action)GenericMethod<object>)
    .Method
    .GetGenericMethodDefinition();

MethodInfo method = ((Action)StaticMethod<object>)
    .Method
    .GetGenericMethodDefinition();

From outside of the class that contains the methods:

MethodInfo method = ((Action)(new Sample())
    .GenericMethod<object>)
    .Method
    .GetGenericMethodDefinition();

MethodInfo method = ((Action)Sample.StaticMethod<object>)
    .Method
    .GetGenericMethodDefinition();

In C#, the name of a method, i.e. "ToString" or "GenericMethod" actually refers to a group of methods that may contain one or more methods. Until you provide the types of the method parameters, it is not known which method you are referring to.

((Action)GenericMethod<object>) refers to the delegate for a specific method. ((Func<string, int>)GenericMethod<object>) refers to a different overload of GenericMethod

Method 3: Create a lambda expression containing a method call expression, get the MethodInfo object and then GetGenericMethodDefinition

MethodInfo method = ((MethodCallExpression)((Expression<Action<Sample>>)(
    (Sample v) => v.GenericMethod<object>()
    )).Body).Method.GetGenericMethodDefinition();

This breaks down to

Create a lambda expression where the body is a call to your desired method.

Expression<Action<Sample>> expr = (Sample v) => v.GenericMethod<object>();

Extract the body and cast to MethodCallExpression

MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;

Get the generic method definition from the method

MethodInfo methodA = methodCallExpr.Method.GetGenericMethodDefinition();

Step 2 is calling MakeGenericMethod to create a generic method with the appropriate type(s).

MethodInfo generic = method.MakeGenericMethod(myType);

Step 3 is invoking the method with the appropriate arguments.

generic.Invoke(this, null);

Why would an Enum implement an Interface?

Most common usage for this would be to merge the values of two enums into one group and treat them similarly. For example, see how to join Fruits and Vegatables.

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Here's a plugin which can list all event handlers for any given element/event:

$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};

Use it like this:

// List all onclick handlers of all anchor elements:
$('a').listHandlers('onclick', console.info);

// List all handlers for all events of all elements:
$('*').listHandlers('*', console.info);

// Write a custom output function:
$('#whatever').listHandlers('click',function(element,data){
    $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
});

Src: (my blog) -> http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/

remove all special characters in java

use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.

          String c= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(c);
        while(match.find())
        {
            String s= match.group();
        c=c.replaceAll("\\"+s, "");
        }
        System.out.println(c);

Could not find any resources appropriate for the specified culture or the neutral culture

I was also facing the same issue, tried all the solutions mentioned in the answer but none seemed to work. Turned out that during the checkin of code to TFS. TFS did not checkin the Resx file it only checked in the designer file. So all other developers were facing this issue while running on their machines. Checking in the resx file manually did the trick

How to identify a strong vs weak relationship on ERD?

  1. Weak (Non-Identifying) Relationship

    • Entity is existence-independent of other enties

    • PK of Child doesn’t contain PK component of Parent Entity

  2. Strong (Identifying) Relationship

    • Child entity is existence-dependent on parent

    • PK of Child Entity contains PK component of Parent Entity

    • Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.

Div height 100% and expands to fit content

You can also use

 display: inline-block;

mine worked with this

How can I increment a date by one day in Java?

Java 8 added a new API for working with dates and times.

With Java 8 you can use the following lines of code:

// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");

// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);

How to generate a simple popup using jQuery

First the CSS - tweak this however you like:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.

HTML becomes:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

Python: Find in list

While the answer from Niklas B. is pretty comprehensive, when we want to find an item in a list it is sometimes useful to get its index:

next((i for i, x in enumerate(lst) if [condition on x]), [default value])

Insert data to MySql DB and display if insertion is success or failure

$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";

}
else
{
echo "Error";

}

Using ng-click vs bind within link function of Angular Directive

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

Demo on plunkr

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.

Oracle select most recent date record

i think i'd try with MAX something like this:

SELECT staff_id, max( date ) from owner.table group by staff_id

then link in your other columns:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date

Compare a date string to datetime in SQL Server?

There are many formats for date in SQL which are being specified. Refer https://msdn.microsoft.com/en-in/library/ms187928.aspx

Converting and comparing varchar column with selected dates.

Syntax:

SELECT * FROM tablename where CONVERT(datetime,columnname,103) 
    between '2016-03-01' and '2016-03-03'
In CONVERT(DATETIME,COLUMNNAME,103) "103" SPECIFIES THE DATE FORMAT as dd/mm/yyyy

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables

Python: Finding differences between elements of a list

You can use itertools.tee and zip to efficiently build the result:

from itertools import tee
# python2 only:
#from itertools import izip as zip

def differences(seq):
    iterable, copied = tee(seq)
    next(copied)
    for x, y in zip(iterable, copied):
        yield y - x

Or using itertools.islice instead:

from itertools import islice

def differences(seq):
    nexts = islice(seq, 1, None)
    for x, y in zip(seq, nexts):
        yield y - x

You can also avoid using the itertools module:

def differences(seq):
    iterable = iter(seq)
    prev = next(iterable)
    for element in iterable:
        yield element - prev
        prev = element

All these solution work in constant space if you don't need to store all the results and support infinite iterables.


Here are some micro-benchmarks of the solutions:

In [12]: L = range(10**6)

In [13]: from collections import deque
In [15]: %timeit deque(differences_tee(L), maxlen=0)
10 loops, best of 3: 122 ms per loop

In [16]: %timeit deque(differences_islice(L), maxlen=0)
10 loops, best of 3: 127 ms per loop

In [17]: %timeit deque(differences_no_it(L), maxlen=0)
10 loops, best of 3: 89.9 ms per loop

And the other proposed solutions:

In [18]: %timeit [x[1] - x[0] for x in zip(L[1:], L)]
10 loops, best of 3: 163 ms per loop

In [19]: %timeit [L[i+1]-L[i] for i in range(len(L)-1)]
1 loops, best of 3: 395 ms per loop

In [20]: import numpy as np

In [21]: %timeit np.diff(L)
1 loops, best of 3: 479 ms per loop

In [35]: %%timeit
    ...: res = []
    ...: for i in range(len(L) - 1):
    ...:     res.append(L[i+1] - L[i])
    ...: 
1 loops, best of 3: 234 ms per loop

Note that:

  • zip(L[1:], L) is equivalent to zip(L[1:], L[:-1]) since zip already terminates on the shortest input, however it avoids a whole copy of L.
  • Accessing the single elements by index is very slow because every index access is a method call in python
  • numpy.diff is slow because it has to first convert the list to a ndarray. Obviously if you start with an ndarray it will be much faster:

    In [22]: arr = np.array(L)
    
    In [23]: %timeit np.diff(arr)
    100 loops, best of 3: 3.02 ms per loop
    

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

Python strptime() and timezones?

Since strptime returns a datetime object which has tzinfo attribute, We can simply replace it with desired timezone.

>>> import datetime

>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'

How to get base URL in Web API controller?

This is what I use:

Uri baseUri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));

Then when I combine it with another relative path, I use the following:

string resourceRelative = "~/images/myImage.jpg";
Uri resourceFullPath = new Uri(baseUri, VirtualPathUtility.ToAbsolute(resourceRelative));

How to add a "open git-bash here..." context menu to the windows explorer?

You can install TortoiseGit for Windows and include integration in context menu. I consider it the best tool to work with Git on Windows.

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

Make anchor link go some pixels above where it's linked to

A variant of Thomas' solution: CSS element>element selectors can be handy here:

CSS

.paddedAnchor{
  position: relative;
}
.paddedAnchor > a{
  position: absolute;
  top: -100px;
}

HTML

<a href="#myAnchor">Click Me!</a>

<span class="paddedAnchor"><a name="myAnchor"></a></span>

A click on the link will move the scroll position to 100px above wherever the element with a class of paddedAnchor is positioned.

Supported in non-IE browsers, and in IE from version 9. For support on IE 7 and 8, a <!DOCTYPE> must be declared.

What is the difference between ( for... in ) and ( for... of ) statements?

For...in loop

The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; it almost makes it more confusing than before.

Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop.

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

Prints:

0

1

2

3

4

5

6

7

8

9

function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); } }

This is why for...in loops are discouraged when looping over arrays.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

For...of loop

The for...of loop is used to loop over any type of data that is iterable.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

Prints:

0

1

2

3

4

5

6

7

8

9

This makes the for...of loop the most concise version of all the for loops.

But wait, there’s more! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops.

You can stop or break a for...of loop at anytime.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  if (digit % 2 === 0) {
    continue;
  }
  console.log(digit);
}

Prints:

1

3

5

7

9

And you don’t have to worry about adding new properties to objects. The for...of loop will only loop over the values in the object.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Short answer @SuppressWarnings is the right way to go.

Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

Therefore when you write

final List<MyObject> list = query.list();

You are doing an unsafe cast from List to List<MyObject> - this cannot be avoided.

There is no way you can safely carry out the cast as the List could contain anything.

The only way to make the error go away is the even more ugly

final List<MyObject> list = new LinkedList<>();
for(final Object o : query.list()) {
    list.add((MyObject)o);
}

Running multiple commands in one line in shell

Try this..

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Show MySQL host via SQL Command

To get current host name :-

select @@hostname;
show variables where Variable_name like '%host%';

To get hosts for all incoming requests :-

select host from information_schema.processlist;

Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.

However, mysql document mention this :-

resolveip google.com.sg

docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

How to calculate sum of a formula field in crystal Reports?

The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.

In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)

EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!

Declaring array of objects

Try this-

var arr = [];
arr.push({});

Plotting in a non-blocking way with Matplotlib


A simple trick that works for me is the following:

  1. Use the block = False argument inside show: plt.show(block = False)
  2. Use another plt.show() at the end of the .py script.

Example:

import matplotlib.pyplot as plt

plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")

plt.show(block=False)

#more code here (e.g. do calculations and use print to see them on the screen

plt.show()

Note: plt.show() is the last line of my script.

C# how to create a Guid value?

If you want to create a "desired" Guid you can do

var tempGuid = Guid.Parse("<guidValue>");

where <guidValue> would be something like 1A3B944E-3632-467B-A53A-206305310BAE.

JSLint is suddenly reporting: Use the function form of "use strict"

Add a file .jslintrc (or .jshintrc in the case of jshint) at the root of your project with the following content:

{
    "node": true
}

binning data in python with scipy/numpy

The numpy_indexed package (disclaimer: I am its author) contains functionality to efficiently perform operations of this type:

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))

This is essentially the same solution as the one I posted earlier; but now wrapped in a nice interface, with tests and all :)

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

Reading *.wav files in Python

Here's a Python 3 solution using the built in wave module [1], that works for n channels, and 8,16,24... bits.

import sys
import wave

def read_wav(path):
    with wave.open(path, "rb") as wav:
        nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
        print(wav.getparams(), "\nBits per sample =", sampwidth * 8)

        signed = sampwidth > 1  # 8 bit wavs are unsigned
        byteorder = sys.byteorder  # wave module uses sys.byteorder for bytes

        values = []  # e.g. for stereo, values[i] = [left_val, right_val]
        for _ in range(nframes):
            frame = wav.readframes(1)  # read next frame
            channel_vals = []  # mono has 1 channel, stereo 2, etc.
            for channel in range(nchannels):
                as_bytes = frame[channel * sampwidth: (channel + 1) * sampwidth]
                as_int = int.from_bytes(as_bytes, byteorder, signed=signed)
                channel_vals.append(as_int)
            values.append(channel_vals)

    return values, framerate

You can turn the result into a NumPy array.

import numpy as np

data, rate = read_wav(path)
data = np.array(data)

Note, I've tried to make it readable rather than fast. I found reading all the data at once was almost 2x faster. E.g.

with wave.open(path, "rb") as wav:
    nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
    all_bytes = wav.readframes(-1)

framewidth = sampwidth * nchannels
frames = (all_bytes[i * framewidth: (i + 1) * framewidth]
            for i in range(nframes))

for frame in frames:
    ...

Although python-soundfile is roughly 2 orders of magnitude faster (hard to approach this speed with pure CPython).

[1] https://docs.python.org/3/library/wave.html

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".

You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.

Maven dependency of "spring-boot-starter-web" will look like

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

jQuery to remove an option from drop down list, given option's text/value

$('#id option').remove();

This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

JQuery Calculate Day Difference in 2 date textboxes

Number of days calculation between two dates.

    $(document).ready(function () {
        $('.submit').on('click', function () {
            var startDate = $('.start-date').val();
            var endDate = $('.end-date').val();

            var start = new Date(startDate);
            var end = new Date(endDate);

            var diffDate = (end - start) / (1000 * 60 * 60 * 24);
            var days = Math.round(diffDate);
        });
    });

When should I use a struct rather than a class in C#?

I made a small benchmark with BenchmarkDotNet to get a better understanding of "struct" benefit in numbers. I'm testing looping through array (or list) of structs (or classes). Creating those arrays or lists is out of the benchmark's scope - it is clear that "class" is more heavy will utilize more memory, and will involve GC.

So the conclusion is: be careful with LINQ and hidden structs boxing/unboxing and using structs for microoptimizations strictly stay with arrays.

P.S. Another benchmark about passing struct/class through call stack is there https://stackoverflow.com/a/47864451/506147

BenchmarkDotNet=v0.10.8, OS=Windows 10 Redstone 2 (10.0.15063)
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233542 Hz, Resolution=309.2584 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2101.1
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2101.1
  Core   : .NET Core 4.6.25211.01, 64bit RyuJIT


          Method |  Job | Runtime |      Mean |     Error |    StdDev |       Min |       Max |    Median | Rank |  Gen 0 | Allocated |
---------------- |----- |-------- |----------:|----------:|----------:|----------:|----------:|----------:|-----:|-------:|----------:|
   TestListClass |  Clr |     Clr |  5.599 us | 0.0408 us | 0.0382 us |  5.561 us |  5.689 us |  5.583 us |    3 |      - |       0 B |
  TestArrayClass |  Clr |     Clr |  2.024 us | 0.0102 us | 0.0096 us |  2.011 us |  2.043 us |  2.022 us |    2 |      - |       0 B |
  TestListStruct |  Clr |     Clr |  8.427 us | 0.1983 us | 0.2204 us |  8.101 us |  9.007 us |  8.374 us |    5 |      - |       0 B |
 TestArrayStruct |  Clr |     Clr |  1.539 us | 0.0295 us | 0.0276 us |  1.502 us |  1.577 us |  1.537 us |    1 |      - |       0 B |
   TestLinqClass |  Clr |     Clr | 13.117 us | 0.1007 us | 0.0892 us | 13.007 us | 13.301 us | 13.089 us |    7 | 0.0153 |      80 B |
  TestLinqStruct |  Clr |     Clr | 28.676 us | 0.1837 us | 0.1534 us | 28.441 us | 28.957 us | 28.660 us |    9 |      - |      96 B |
   TestListClass | Core |    Core |  5.747 us | 0.1147 us | 0.1275 us |  5.567 us |  5.945 us |  5.756 us |    4 |      - |       0 B |
  TestArrayClass | Core |    Core |  2.023 us | 0.0299 us | 0.0279 us |  1.990 us |  2.069 us |  2.013 us |    2 |      - |       0 B |
  TestListStruct | Core |    Core |  8.753 us | 0.1659 us | 0.1910 us |  8.498 us |  9.110 us |  8.670 us |    6 |      - |       0 B |
 TestArrayStruct | Core |    Core |  1.552 us | 0.0307 us | 0.0377 us |  1.496 us |  1.618 us |  1.552 us |    1 |      - |       0 B |
   TestLinqClass | Core |    Core | 14.286 us | 0.2430 us | 0.2273 us | 13.956 us | 14.678 us | 14.313 us |    8 | 0.0153 |      72 B |
  TestLinqStruct | Core |    Core | 30.121 us | 0.5941 us | 0.5835 us | 28.928 us | 30.909 us | 30.153 us |   10 |      - |      88 B |

Code:

[RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]
    [ClrJob, CoreJob]
    [HtmlExporter, MarkdownExporter]
    [MemoryDiagnoser]
    public class BenchmarkRef
    {
        public class C1
        {
            public string Text1;
            public string Text2;
            public string Text3;
        }

        public struct S1
        {
            public string Text1;
            public string Text2;
            public string Text3;
        }

        List<C1> testListClass = new List<C1>();
        List<S1> testListStruct = new List<S1>();
        C1[] testArrayClass;
        S1[] testArrayStruct;
        public BenchmarkRef()
        {
            for(int i=0;i<1000;i++)
            {
                testListClass.Add(new C1  { Text1= i.ToString(), Text2=null, Text3= i.ToString() });
                testListStruct.Add(new S1 { Text1 = i.ToString(), Text2 = null, Text3 = i.ToString() });
            }
            testArrayClass = testListClass.ToArray();
            testArrayStruct = testListStruct.ToArray();
        }

        [Benchmark]
        public int TestListClass()
        {
            var x = 0;
            foreach(var i in testListClass)
            {
                x += i.Text1.Length + i.Text3.Length;
            }
            return x;
        }

        [Benchmark]
        public int TestArrayClass()
        {
            var x = 0;
            foreach (var i in testArrayClass)
            {
                x += i.Text1.Length + i.Text3.Length;
            }
            return x;
        }

        [Benchmark]
        public int TestListStruct()
        {
            var x = 0;
            foreach (var i in testListStruct)
            {
                x += i.Text1.Length + i.Text3.Length;
            }
            return x;
        }

        [Benchmark]
        public int TestArrayStruct()
        {
            var x = 0;
            foreach (var i in testArrayStruct)
            {
                x += i.Text1.Length + i.Text3.Length;
            }
            return x;
        }

        [Benchmark]
        public int TestLinqClass()
        {
            var x = testListClass.Select(i=> i.Text1.Length + i.Text3.Length).Sum();
            return x;
        }

        [Benchmark]
        public int TestLinqStruct()
        {
            var x = testListStruct.Select(i => i.Text1.Length + i.Text3.Length).Sum();
            return x;
        }
    }

Convert String to SecureString

You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.

var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');

Regular expression that matches valid IPv6 addresses

A simple regex that will match, but I wouldn't recommend for validation of any sort is this:

([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}

Note this matches compression anywhere in the address, though it won't match the loopback address ::1. I find this a reasonable compromise in order to keep the regex simple.

I successfully use this in iTerm2 smart selection rules to quad-click IPv6 addresses.

How to convert string date to Timestamp in java?

Use below code to convert String Date to Epoc Timestamp. Note : - Your input Date format should match with SimpleDateFormat.

String inputDateInString= "8/15/2017 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyy hh:mm:ss");

Date parsedDate = dateFormat.parse("inputDateInString");

Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());

System.out.println("Timestamp "+ timestamp.getTime());

NGinx Default public www location?

On Mac OS X installing nginx with brew makes the default directory:

/usr/local/var/www

So:

root html

means

root /usr/local/var/www/html

There is no html directory so it would have to be created manually.

Logging request/response messages when using HttpClient

An example of how you could do this:

Some notes:

  • LoggingHandler intercepts the request before it handles it to HttpClientHandler which finally writes to the wire.

  • PostAsJsonAsync extension internally creates an ObjectContent and when ReadAsStringAsync() is called in the LoggingHandler, it causes the formatter inside ObjectContent to serialize the object and that's the reason you are seeing the content in json.

Logging handler:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}

Chain the above LoggingHandler with HttpClient:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;

Output:

Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Fri, 20 Sep 2013 20:21:26 GMT
  Server: Microsoft-HTTPAPI/2.0
  Content-Length: 15
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

OS X Framework Library not loaded: 'Image not found'

So I managed to get it working, it's quite simple when you have the right instructions. What I was looking for was a 'private' framework which lives in the App bundle rather than being written to the system library folder.

Building The Framework

  1. Add a target to create a Cocoa Framework
  2. Within that targets 'Build Settings' configure the 'Installation Directory' to '@executable_path/../Frameworks'
  3. Build library, and access the .framework from the archive or products directory

Including The Framework

  1. Drag the created .framework file into the Xcode Project, be sure to tick 'Copy Files to Directory'
  2. In the containing applications target, add a new 'Copy File Build Phase'
  3. Set the 'Destination' to 'Frameworks'
  4. Drag in the created .framework

Git - How to close commit editor?

Note that if you're using Sublime as your commit editor, you need the -n -w flags, otherwise git keeps thinking your commit message is empty and aborting.

How to use UTF-8 in resource properties with ResourceBundle

Open the Settings / Preferences dialog (Ctrl + Alt + S), then click Editor and File Encodings.

Screenshot of window shown

Then, on the bottom, you will fing default encodings for properties files. Choose your encoding type.

Alternatively you can use unicode symbols instead of text in your resource bundle (for example "??" equals \u0456\u0432)

How can I use xargs to copy files that have spaces and quotes in their names?

bill_starr's Perl version won't work well for embedded newlines (only copes with spaces). For those on e.g. Solaris where you don't have the GNU tools, a more complete version might be (using sed)...

find -type f | sed 's/./\\&/g' | xargs grep string_to_find

adjust the find and grep arguments or other commands as you require, but the sed will fix your embedded newlines/spaces/tabs.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Walkthrough: Creating a SQL Server Compact 3.5 Database

To create a relationship between the tables created in the previous procedure

  1. In Server Explorer/Database Explorer, expand Tables.
  2. Right-click the Orders table and then click Table Properties.
  3. Click Add Relations.
  4. Type FK_Orders_Customers in the Relation Name box.
  5. Select CustomerID in the Foreign Key Table Column list.
  6. Click Add Columns.
  7. Click Add Relation.
  8. Click OK to complete the process and create the relationship in the database.
  9. Click OK again to close the Table Properties dialog box.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:

http://php.net/manual/en/mysqli.error.php

Try altering your problem line like so and you should be in good shape:

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection)); 

How to find a string inside a entire database?

This will work:

DECLARE @MyValue NVarChar(4000) = 'something';

SELECT S.name SchemaName, T.name TableName
INTO #T
FROM sys.schemas S INNER JOIN
     sys.tables T ON S.schema_id = T.schema_id;

WHILE (EXISTS (SELECT * FROM #T)) BEGIN
  DECLARE @SQL NVarChar(4000) = 'SELECT * FROM $$TableName WHERE (0 = 1) ';
  DECLARE @TableName NVarChar(1000) = (
    SELECT TOP 1 SchemaName + '.' + TableName FROM #T
  );
  SELECT @SQL = REPLACE(@SQL, '$$TableName', @TableName);

  DECLARE @Cols NVarChar(4000) = '';

  SELECT
    @Cols = COALESCE(@Cols + 'OR CONVERT(NVarChar(4000), ', '') + C.name + ') = CONVERT(NVarChar(4000), ''$$MyValue'') '
  FROM sys.columns C
  WHERE C.object_id = OBJECT_ID(@TableName);

  SELECT @Cols = REPLACE(@Cols, '$$MyValue', @MyValue);
  SELECT @SQL = @SQL + @Cols;

  EXECUTE(@SQL);

  DELETE FROM #T
  WHERE SchemaName + '.' + TableName = @TableName;
END;

DROP TABLE #T;

A couple caveats, though. First, this is outrageously slow and non-optimized. All values are being converted to nvarchar simply so that they can be compared without error. You may run into problems with values like datetime not converting as expected and therefore not being matched when they should be (false negatives).

The WHERE (0 = 1) is there to make building the OR clause easier. If there are not matches you won't get any rows back.

Generic deep diff between two objects

I just use ramda, for resolve the same problem, i need to know what is changed in new object. So here my design.

const oldState = {id:'170',name:'Ivab',secondName:'Ivanov',weight:45};
const newState = {id:'170',name:'Ivanko',secondName:'Ivanov',age:29};

const keysObj1 = R.keys(newState)

const filterFunc = key => {
  const value = R.eqProps(key,oldState,newState)
  return {[key]:value}
}

const result = R.map(filterFunc, keysObj1)

result is, name of property and it's status.

[{"id":true}, {"name":false}, {"secondName":true}, {"age":false}]

What issues should be considered when overriding equals and hashCode in Java?

There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!

Lazy loaded objects are subclasses

If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:

Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy

If you're dealing with an ORM, using o instanceof Person is the only thing that will behave correctly.

Lazy loaded objects have null-fields

ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name will be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode() and equals().

If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode() and equals().

Saving an object will change its state

Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode(). But you can use it in equals().

A pattern I often use is

if (this.getId() == null) {
    return this == other;
}
else {
    return this.getId().equals(other.getId());
}

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode changes. If the object is in a HashSet, you'll "never" find it again.

In my Person example, I probably would use getName() for hashCode and getId() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

Merge two (or more) lists into one, in C# .NET

list4 = list1.Concat(list2).Concat(list3).ToList();

JRE installation directory in Windows

where java works for me to list all java exe but java -verbose tells you which rt.jar is used and thus which jre (full path):

[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...

Edit: win7 and java:

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

How to use ImageBackground to set background image for screen in react-native

Here is a link to the RN docs: https://facebook.github.io/react-native/docs/images

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

You might not want to use <ImageBackground> in some cases, since the implementation is very simple. Refer to <ImageBackground>'s source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={require('./image.png')} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

Note that you must specify some width and height style attributes.

Note also that the file path is relative to the directory the component is in.

What's the difference between using "let" and "var"?

enter image description here

Take a look at this image, I created one very simple example for demonstration of const and let variables. As you can see, when you try to change const variable, you will get the error (Attempting to override 'name' which is constant'), but take a look at let variable...

First we declare let age = 33, and later assign some other value age = 34;, which is ok, we dont have any errors when we try to change let variable

What's the fastest way of checking if a point is inside a polygon in python

Comparison of different methods

I found other methods to check if a point is inside a polygon (here). I tested two of them only (is_inside_sm and is_inside_postgis) and the results were the same as the other methods.

Thanks to @epifanio, I parallelized the codes and compared them with @epifanio and @user3274748 (ray_tracing_numpy) methods. Note that both methods had a bug so I fixed them as shown in their codes below.

One more thing that I found is that the code provided for creating a polygon does not generate a closed path np.linspace(0,2*np.pi,lenpoly)[:-1]. As a result, the codes provided in above GitHub repository may not work properly. So It's better to create a closed path (first and last points should be the same).

Codes

Method 1: parallelpointinpolygon

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):   #<-- Fixed here, must start from zero
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D  

Method 2: ray_tracing_numpy_numba

@jit(nopython=True)
def ray_tracing_numpy_numba(points,poly):
    x,y = points[:,0], points[:,1]
    n = len(poly)
    inside = np.zeros(len(x),np.bool_)
    p2x = 0.0
    p2y = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
        if len(idx):    # <-- Fixed here. If idx is null skip comparisons below.
            if p1y != p2y:
                xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
            if p1x == p2x:
                inside[idx] = ~inside[idx]
            else:
                idxx = idx[x[idx] <= xints]
                inside[idxx] = ~inside[idxx]    

        p1x,p1y = p2x,p2y
    return inside 

Method 3: Matplotlib contains_points

path = mpltPath.Path(polygon,closed=True)  # <-- Very important to mention that the path 
                                           #     is closed (default is false)

Method 4: is_inside_sm (got it from here)

@jit(nopython=True)
def is_inside_sm(polygon, point):
    length = len(polygon)-1
    dy2 = point[1] - polygon[0][1]
    intersections = 0
    ii = 0
    jj = 1

    while ii<length:
        dy  = dy2
        dy2 = point[1] - polygon[jj][1]

        # consider only lines which are not completely above/bellow/right from the point
        if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0] or point[0] >= polygon[jj][0]):

            # non-horizontal line
            if dy<0 or dy2<0:
                F = dy*(polygon[jj][0] - polygon[ii][0])/(dy-dy2) + polygon[ii][0]

                if point[0] > F: # if line is left from the point - the ray moving towards left, will intersect it
                    intersections += 1
                elif point[0] == F: # point on line
                    return 2

            # point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and dx*dx2<=0)
            elif dy2==0 and (point[0]==polygon[jj][0] or (dy==0 and (point[0]-polygon[ii][0])*(point[0]-polygon[jj][0])<=0)):
                return 2

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections & 1  


@njit(parallel=True)
def is_inside_sm_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_sm(polygon,points[i])
    return D  

Method 5: is_inside_postgis (got it from here)

@jit(nopython=True)
def is_inside_postgis(polygon, point):
    length = len(polygon)
    intersections = 0

    dx2 = point[0] - polygon[0][0]
    dy2 = point[1] - polygon[0][1]
    ii = 0
    jj = 1

    while jj<length:
        dx  = dx2
        dy  = dy2
        dx2 = point[0] - polygon[jj][0]
        dy2 = point[1] - polygon[jj][1]

        F =(dx-dx2)*dy - dx*(dy-dy2);
        if 0.0==F and dx*dx2<=0 and dy*dy2<=0:
            return 2;

        if (dy>=0 and dy2<0) or (dy2>=0 and dy<0):
            if F > 0:
                intersections += 1
            elif F < 0:
                intersections -= 1

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections != 0  


@njit(parallel=True)
def is_inside_postgis_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_postgis(polygon,points[i])
    return D  

Benchmark

enter image description here

Timing for 10 million points:

parallelpointinpolygon Elapsed time:      4.0122294425964355
Matplotlib contains_points Elapsed time: 14.117807388305664
ray_tracing_numpy_numba Elapsed time:     7.908452272415161
sm_parallel Elapsed time:                 0.7710440158843994
is_inside_postgis_parallel Elapsed time:  2.131121873855591

Here is the code.

import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from time import time
import numpy as np

np.random.seed(2)

time_parallelpointinpolygon=[]
time_mpltPath=[]
time_ray_tracing_numpy_numba=[]
time_is_inside_sm_parallel=[]
time_is_inside_postgis_parallel=[]
n_points=[]

for i in range(1, 10000002, 1000000): 
    n_points.append(i)
    
    lenpoly = 100
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    N = i
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))
    
    
    #Method 1
    start_time = time()
    inside1=parallelpointinpolygon(points, polygon)
    time_parallelpointinpolygon.append(time()-start_time)

    # Method 2
    start_time = time()
    path = mpltPath.Path(polygon,closed=True)
    inside2 = path.contains_points(points)
    time_mpltPath.append(time()-start_time)

    # Method 3
    start_time = time()
    inside3=ray_tracing_numpy_numba(points,polygon)
    time_ray_tracing_numpy_numba.append(time()-start_time)

    # Method 4
    start_time = time()
    inside4=is_inside_sm_parallel(points,polygon)
    time_is_inside_sm_parallel.append(time()-start_time)

    # Method 5
    start_time = time()
    inside5=is_inside_postgis_parallel(points,polygon)
    time_is_inside_postgis_parallel.append(time()-start_time)


    
plt.plot(n_points,time_parallelpointinpolygon,label='parallelpointinpolygon')
plt.plot(n_points,time_mpltPath,label='mpltPath')
plt.plot(n_points,time_ray_tracing_numpy_numba,label='ray_tracing_numpy_numba')
plt.plot(n_points,time_is_inside_sm_parallel,label='is_inside_sm_parallel')
plt.plot(n_points,time_is_inside_postgis_parallel,label='is_inside_postgis_parallel')
plt.xlabel("N points")
plt.ylabel("time (sec)")
plt.legend(loc = 'best')
plt.show()

CONCLUSION

The fastest algorithms are:

1- is_inside_sm_parallel

2- is_inside_postgis_parallel

3- parallelpointinpolygon (@epifanio)

Convert string to JSON array

Input String

[
   {
      "userName": "sandeep",
      "age": 30
   }, 
   {
      "userName": "vivan",
      "age": 5
   }
]

Simple Way to Convert String to JSON

public class Test
{

    public static void main(String[] args) throws JSONException
    {
        String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}]  ";
        JSONArray jsonArr = new JSONArray(data);

        for (int i = 0; i < jsonArr.length(); i++)
        {
            JSONObject jsonObj = jsonArr.getJSONObject(i);

            System.out.println(jsonObj);
        }

    }
}

Output

{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

Remove padding from columns in Bootstrap 3

You can customize your Bootstrap Grid system and define your custom responsive grid.

change your default values for the following gutter width from @grid-gutter-width = 30px to @grid-gutter-width = 0px

(Gutter width is padding between columns. It gets divided in half for the left and right.)

Return Index of an Element in an Array Excel VBA

Dim pos, arr, val

arr=Array(1,2,4,5)
val = 4

pos=Application.Match(val, arr, False)

if not iserror(pos) then
   Msgbox val & " is at position " & pos
else
   Msgbox val & " not found!"
end if

Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:

Dim arr(1 To 10, 1 To 2)
Dim x

For x = 1 To 10
    arr(x, 1) = x
    arr(x, 2) = 11 - x
Next x

Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)

EDIT: it's worth illustrating here what @ARich pointed out in the comments - that using Index() to slice an array has horrible performance if you're doing it in a loop.

In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.

Sub PerfTest()

    Const VAL_TO_FIND As String = "R1800:C8"
    Dim a(1 To 2000, 1 To 10)
    Dim r As Long, c As Long, t

    For r = 1 To 2000
        For c = 1 To 10
            a(r, c) = "R" & r & ":C" & c
        Next c
    Next r

    t = Timer
    Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
    ' >> 0.00781 sec

     t = Timer
    Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
    ' >> 14.18 sec

End Sub

Function FindLoop(arr, val) As Boolean
    Dim r As Long, c As Long
    For r = 1 To UBound(arr, 1)
    For c = 1 To UBound(arr, 2)
        If arr(r, c) = val Then
            FindLoop = True
            Exit Function
        End If
    Next c
    Next r
End Function

Function FindIndex(arr, val)
    Dim r As Long
    For r = 1 To UBound(arr, 1)
        If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
            FindIndex = True
            Exit Function
        End If
    Next r
End Function

Downloading video from YouTube

I suggest you to take a look into SharpGrabber - a .NET Standard library I've written just for this purpose. It is newer than YouTubeExtractor and libvideo. It supports YouTube and Instagram as the time of this answer. This project also offers high-quality video and audio muxing and a cross-platform desktop application.

How can I use Helvetica Neue Condensed Bold in CSS?

After a lot of fiddling, got it working (only tested in Webkit) using:

font-family: "HelveticaNeue-CondensedBold";

font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)

This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:

font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";

As a fallback, else other browsers might default to serif if they can't work it out.

Demo: http://jsfiddle.net/ndFTL/12/

Assign JavaScript variable to Java Variable in JSP

The answer is You can't. Java (in your case JSP) is a server-side scripting language, which means that it is compiled and executed before all javascript code. You can assign javascript variables to JSP variables but not the other way around. If possible, you can have the variable appear in a QueryString or pass it via a form (through a hidden field), post it and extract the variable through JSP that way. But this would require resubmitting the page.

Hope this helps.

Convert InputStream to byte array in Java

I tried to edit @numan's answer with a fix for writing garbage data but edit was rejected. While this short piece of code is nothing brilliant I can't see any other better answer. Here's what makes most sense to me:

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // you can configure the buffer size
int length;

while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams
in.close(); // call this in a finally block

byte[] result = out.toByteArray();

btw ByteArrayOutputStream need not be closed. try/finally constructs omitted for readability

BASH Syntax error near unexpected token 'done'

What is the error you're getting?

$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file

If you get that error, you may have bad line endings. Unix uses <LF> at the end of the file while Windows uses <CR><LF>. That <CR> character gets interpreted as a character.

You can use od -a test.sh to see the invisible characters in the file.

$ od -a test.sh
0000000    #   !   /   b   i   n   /   b   a   s   h  cr  nl   #  sp  cr
0000020   nl   w   h   i   l   e  sp   :  cr  nl   d   o  cr  nl  sp  sp
0000040   sp  sp   e   c   h   o  sp   "   P   r   e   s   s  sp   [   C
0000060    T   R   L   +   C   ]  sp   t   o  sp   s   t   o   p   "  cr
0000100   nl  sp  sp  sp  sp   s   l   e   e   p  sp   1  cr  nl   d   o
0000120    n   e  cr  nl                                                
0000124

The sp stands for space, the ht stands for tab, the cr stands for <CR> and the nl stands for <LF>. Note that all of the lines end with cr followed by a nl character.

You can also use cat -v test.sh if your cat command takes the -v parameter.

If you have dos2unix on your box, you can use that command to fix your file:

$ dos2unix test.sh

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

open failed: EACCES (Permission denied)

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

.htaccess mod_rewrite - how to exclude directory from rewrite rule

add a condition to check for the admin directory, something like:

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/([^/] )\.html$ index.php?lang=$1&mod=$2 [L]

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/$ index.php?lang=$1&mod=home [L]

What to do about Eclipse's "No repository found containing: ..." error messages?

What I did was:

  1. I went to Window > Preferences > Install/Update > Available Software Sites, then for each enabled site I added a / to the end of the URL (if it wasn't there already), then clicked Reload as per @Hunternif answer. But the problem still persisted.
  2. Then I disabled all the software sites and re-enalbed them one by one and ran updates to keep only those that worked. After step 2. the problem was solved. Now I have enabled only the update sites that do not give the error and updates work.

bootstrap 4 file input doesn't show the file name

$(document).on('change', '.custom-file-input', function (event) {
    $(this).next('.custom-file-label').html(event.target.files[0].name);
})

Best of all worlds. Works on dynamically created inputs, and uses actual file name.

Add animated Gif image in Iphone UIImageView

You Can use https://github.com/Flipboard/FLAnimatedImage

#import "FLAnimatedImage.h"
NSData *dt=[NSData dataWithContentsOfFile:path];
imageView1 = [[FLAnimatedImageView alloc] init];
FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:dt];
imageView1.animatedImage = image1;
imageView1.frame = CGRectMake(0, 5, 168, 80);
[self.view addSubview:imageView1];

Launch custom android application from android browser

As of 15/06/2019

what I did is include all four possibilities to open url.

i.e, with http / https and 2 with www in prefix and 2 without www

and by using this my app launches automatically now without asking me to choose a browser and other option.

<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />

    <data android:scheme="https" android:host="example.in" />
    <data android:scheme="https" android:host="www.example.in" />
    <data android:scheme="http" android:host="example.in" />
    <data android:scheme="http" android:host="www.example.in" />

</intent-filter>

Whats the CSS to make something go to the next line in the page?

It depends why the something is on the same line in the first place.

clear in the case of floats, display: block in the case of inline content naturally flowing, nothing will defeat position: absolute as the previous element will be taken out of the normal flow by it.

How to replace item in array?

The Array.indexOf() method will replace the first instance. To get every instance use Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

Of course, that creates a new array. If you want to do it in place, use Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

Scheduled run of stored procedure on SQL server

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

How do I parse an ISO 8601-formatted date?

def parseISO8601DateTime(datetimeStr):
    import time
    from datetime import datetime, timedelta

    def log_date_string(when):
        gmt = time.gmtime(when)
        if time.daylight and gmt[8]:
            tz = time.altzone
        else:
            tz = time.timezone
        if tz > 0:
            neg = 1
        else:
            neg = 0
            tz = -tz
        h, rem = divmod(tz, 3600)
        m, rem = divmod(rem, 60)
        if neg:
            offset = '-%02d%02d' % (h, m)
        else:
            offset = '+%02d%02d' % (h, m)

        return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset

    dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')
    timestamp = dt.timestamp()
    return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)

Note that we should look if the string doesn't ends with Z, we could parse using %z.

Best way to save a trained model in PyTorch?

It depends on what you want to do.

Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm and Dropout layers that by default are in train mode on construction:

torch.save(model.state_dict(), filepath)

#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()

Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:

state = {
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}
torch.save(state, filepath)

To resume training you would do things like: state = torch.load(filepath), and then, to restore the state of each individual object, something like this:

model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])

Since you are resuming training, DO NOT call model.eval() once you restore the states when loading.

Case # 3: Model to be used by someone else with no access to your code: In Tensorflow you can create a .pb file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve. The equivalent way to do this in Pytorch would be:

torch.save(model, filepath)

# Then later:
model = torch.load(filepath)

This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This is the real proxy redirection to the intended server.

server {
  listen          80;
  server_name     localhost;
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
    proxy_pass http://xx.xxx.xxx.xxx/;
    proxy_redirect off;
    proxy_set_header Host $host;

  }
}

UICollectionView auto scroll to cell at IndexPath

Swift:

your_CollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)

Swift 3

let indexPath = IndexPath(row: itemIndex, section: sectionIndex)

collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.right, animated: true)

Scroll Position:

UICollectionViewScrollPosition.CenteredHorizontally / UICollectionViewScrollPosition.CenteredVertically

SQL search multiple values in same field

This will works perfectly in both cases, one or multiple fields searching multiple words.

Hope this will help someone. Thanks

declare @searchTrm varchar(MAX)='one two three four'; 
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols 
WHERE EXISTS (SELECT value  
    FROM STRING_SPLIT(@searchTrm, ' ')  
    WHERE 
        trim(value)<>''
        and(    
        BolNumber like '%'+ value+'%'
        or UserComment like '%'+ value+'%'
        or RequesterId like '%'+ value+'%' )
        )

How to horizontally center an unordered list of unknown width?

Use the below css to solve your issue

#footer{ text-align:center; height:58px;}
#footer ul {  font-size:11px;}
#footer ul li {display:inline-block;}

Note: Don't use float:left in li. it will make your li to align left.

Windows equivalent of the 'tail' command

FWIW, for those just needing to snip off an indeterminate number of records from the head of the file, more > works well. This is useful just to have a smaller file to work with in the early stages of developing something.

Fast query runs slow in SSRS

I simply deselected 'Repeat header columns on each page' within the Tablix Properties.

How to install JQ on Mac by command-line?

The simplest way to install jq and test that it works is through brew and then using the simplest filter that merely formats the JSON

Install

brew is the easiest way to manage packages on a mac:

brew install jq

Need brew? Run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Failing that: instructions to install and use are on https://brew.sh/

Test

The . filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)

echo '{ "name":"John", "age":31, "city":"New York" }' | jq .

The result should appear like so in your terminal:

{
  "name": "John",
  "age": 31,
  "city": "New York"
}

Angular - POST uploaded file

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

and the uploader code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

Here is example : https://github.com/wangzilong/angular2-multipartForm

Sending multipart/formdata with jQuery.ajax

Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).

Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

How to "perfectly" override a dict?

After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:

class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict

which I really hate, but seems to fit my needs, which are:

  • can override **my_dict
    • if you inherit from dict, this bypasses your code. try it out.
    • this makes #2 unacceptable for me at all times, as this is quite common in python code
  • masquerades as isinstance(my_dict, dict)
    • rules out MutableMapping alone, so #1 is not enough
    • I heartily recommend #1 if you don't need this, it's simple and predictable
  • fully controllable behavior
    • so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class). Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.


As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here

You'll see similar behavior for other scenarios. Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.


Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Is there a way to SELECT and UPDATE rows at the same time?

Perhaps something more like this?

declare @UpdateTime datetime

set @UpdateTime = getutcdate()

update Table1 set AlertDate = @UpdateTime where AlertDate is null

select ID from Table1 where AlertDate = @UpdateTime

adding and removing classes in angularJs using ng-click

You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:

_x000D_
_x000D_
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
  $scope.class = "red";_x000D_
  $scope.changeClass = function(){_x000D_
    if ($scope.class === "red")_x000D_
      $scope.class = "blue";_x000D_
    else_x000D_
      $scope.class = "red";_x000D_
  };_x000D_
});
_x000D_
.red{_x000D_
  color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
  color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
  <div ng-class="class">{{class}}</div>_x000D_
  <button ng-click="changeClass()">Change Class</button>    _x000D_
</body>
_x000D_
_x000D_
_x000D_

Here is the example working on jsFiddle

How to handle notification when app in background in Firebase

Thanks to All of you for your Answers. But I solved this by sending data message instead of sending Notification. Server code

<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "C-l6T_a7HouUK****";
$serverKey = "AAAAaOcKS00:********";
define( 'API_ACCESS_KEY', $serverKey );
$registrationIds = array($token);
// prep the bundle

$msg = array

(
 'message'  => 'here is a message. message',
 'title'        => 'This is a title. title',
 'subtitle' => 'This is a subtitle. subtitle',
 'tickerText'   => 'Ticker text here...Ticker text here...Ticker text 
 here',
 'vibrate'  => 1,
 'sound'        => 1,
 'largeIcon'    => 'large_icon',
 'smallIcon'    => 'small_icon'

);

$fields = array

(
  'registration_ids'    => $registrationIds,
  'data'            => $msg

);
$headers = array

(
  'Authorization: key=' . API_ACCESS_KEY,
 'Content-Type: application/json'

);


$ch = curl_init();

curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' 
);

curl_setopt( $ch,CURLOPT_POST, true );

curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );

curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );

curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );

$result = curl_exec($ch );

curl_close( $ch );

echo $result;

?>

And caught the Data in onMessageReceived

public class MyFirebaseMessagingService extends FirebaseMessagingService     {

  private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

      sendNotification(remoteMessage.getData().get("message"));
     }
   // Check if message contains a notification payload.
    else if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    sendNotification(remoteMessage.getNotification().getBody());
    }


}
   private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, Notify.class).putExtra("msg",messageBody);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = "idddd";
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(MyFirebaseMessagingService.this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

Initialize/reset struct to zero/null

In C, it is a common idiom to zero out the memory for a struct using memset:

struct x myStruct;
memset(&myStruct, 0, sizeof(myStruct));

Technically speaking, I don't believe that this is portable because it assumes that the NULL pointer on a machine is represented by the integer value 0, but it's used widely because on most machines this is the case.

If you move from C to C++, be careful not to use this technique on every object. C++ only makes this legal on objects with no member functions and no inheritance.

How to enable scrolling on website that disabled scrolling?

In a browser like Chrome etc.:

  1. Inspect the code (for e.g. in Chrome press ctrl + shift + c);
  2. Set overflow: visible on body element (for e.g., <body style="overflow: visible">)
  3. Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
    • To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
    • If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).

Good luck!

htaccess <Directory> deny from all

You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

#place this in /system/.htaccess as you had before
deny from all

Compile a DLL in C/C++, then call it from another program

The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.

You have two options to use a dll

  • Either use a lib file to link the symbols -- compile time dynamic linking
  • Use LoadLibrary() or some suitable function to load the library, retrieve a function pointer (GetProcAddress) and call it -- runtime dynamic linking

Exporting classes will not work if you follow the second method though.

Where does Hive store files in HDFS?

In Hive terminal type:

hive> set hive.metastore.warehouse.dir;

(it will print the path)

What is the best way to test for an empty string with jquery-out-of-the-box?

if(!my_string){ 
// stuff 
}

and

if(my_string !== "")

if you want to accept null but reject empty

EDIT: woops, forgot your condition is if it IS empty

How to select first parent DIV using jQuery?

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

Attach parameter to button.addTarget action in Swift

For Swift 2.X and above

button.addTarget(self,action:#selector(YourControllerName.buttonClicked(_:)),
                         forControlEvents:.TouchUpInside)

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

Bootstrap: If you are using Bootstrap. This is a really good one: Select2

Also, TokenInput is an interesting one. First, it does not depend on jQuery-UI, second its config is very smooth.

The only issue I had it does not support free-tagging natively. So, I have to return the query-string back to client as a part of response JSON.


As @culithay mentioned in the comment, TokenInput supports a lot of features to customize. And highlight of some feature that the others don't have:

  • tokenLimit: The maximum number of results allowed to be selected by the user. Use null to allow unlimited selections
  • minChars: The minimum number of characters the user must enter before a search is performed.
  • queryParam: The name of the query param which you expect to contain the search term on the server-side

Thanks culithay for the input.

How to force the input date format to dd/mm/yyyy?

DEMO : http://jsfiddle.net/shfj70qp/

//dd/mm/yyyy 

var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

console.log(month+"/"+day+"/"+year);

How can I check if a directory exists in a Bash shell script?

The below find can be used,

find . -type d -name dirname -prune -print

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

Pushing from local repository to GitHub hosted remote

Type

git push

from the command line inside the repository directory

How to get unique values in an array

Another thought of this question. Here is what I did to achieve this with fewer code.

_x000D_
_x000D_
var distinctMap = {};_x000D_
var testArray = ['John', 'John', 'Jason', 'Jason'];_x000D_
for (var i = 0; i < testArray.length; i++) {_x000D_
  var value = testArray[i];_x000D_
  distinctMap[value] = '';_x000D_
};_x000D_
var unique_values = Object.keys(distinctMap);_x000D_
_x000D_
console.log(unique_values);
_x000D_
_x000D_
_x000D_

How to get the azure account tenant Id?

If you have Azure CLI setup, you can run the command below,

az account list

or find it at ~/.azure/credentials

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

SQL datetime format to date only

if you are using SQL Server use convert

e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate

more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

Singleton with Arguments in Java

In your example you are not using a singleton. Notice that if you do the following (assuming that the Singleton.getInstance was actually static):

Singleton obj1 = Singleton.getInstance(3);
Singleton obj2 = Singleton.getInstance(4);

Then the obj2.x's values is 3, not 4. If you need to do this, make it a plain class. If the number of values is small and fixed, you can consider using an enum. If you are having problem with excessive object generation (which is usually not the case), then you can consider caching values (and check sources or get help with that, as it is obvious how to build caches without the danger of memory leaks).

You also might want to read this article as singletons can be very easily overused.

How do I Search/Find and Replace in a standard string?

The easiest way (offering something near what you wrote) is to use Boost.Regex, specifically regex_replace.

std::string has built in find() and replace() methods, but they are more cumbersome to work with as they require dealing with indices and string lengths.

How do I import/include MATLAB functions?

You have to set the path. See here.

Is there a template engine for Node.js?

I found hogan.js from Twitter and recommended by Tim O'Reilly on his site. I have no best practice with it, but I trust on Twitter and O'Reilly. You should try...

Can I add an image to an ASP.NET button?

You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.

Style="background-image:url('Image/1.png');"

You can change image location with using

background-repeat

properties. So you can write a button like below:

<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>

Import SQL dump into PostgreSQL database

I had more than 100MB data, therefore I could not restore database using Pgadmin4.

I used simply postgres client, and write below command.

postgres@khan:/$ pg_restore -d database_name /home/khan/Downloads/dump.sql

It worked fine and took few seconds.You can see below link for more information. https://www.postgresql.org/docs/8.1/app-pgrestore.html

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek

cURL equivalent in Node.js?

The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.

This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.

Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888

Access non-numeric Object properties by index?

If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead

var keys = []
var obj = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
}
for (var key in obj){
    keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])

How do I set a textbox's text to bold at run time?

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

How to delete object?

It sounds like you need to create a wrapper around an instance you can invalidate:

public class Ref<T> where T : class
{
    private T instance;
    public Ref(T instance)
    {
        this.instance = instance;
    }

    public static implicit operator Ref<T>(T inner)
    {
        return new Ref<T>(inner);
    }

    public void Delete()
    {
        this.instance = null;
    }

    public T Instance
    {
        get { return this.instance; }
    }
}

and you can use it like:

Ref<Car> carRef = new Car();
carRef.Delete();
var car = carRef.Instance;     //car is null

Be aware however that if any code saves the inner value in a variable, this will not be invalidated by calling Delete.

How to create a regex for accepting only alphanumeric characters?

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

Android - how to replace part of a string by another string?

rekaszeru

I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..

Im using a EditText as an example


// GIVE TARGET TEXT BOX A NAME

 EditText textbox = (EditText) findViewById(R.id.your_textboxID);

// STRING TO REPLACE

 String oldText = "hello"
 String newText = "Hi";      
 String textBoxText = textbox.getText().toString();

// REPLACE STRINGS WITH RETURNED STRINGS

String returnedString = textBoxText.replace( oldText, newText );

// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX

textbox.setText(returnedString);

This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !

Obviously this example requires that you have a EditText with the ID set to your_textboxID

Convert hex string (char []) to int?

Try below block of code, its working for me.

char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);

printf("value x: %x - %d", intVal, intVal);

Output is:

value x: 820 - 2080

How to find largest objects in a SQL Server database?

I've found this query also very helpful in SqlServerCentral, here is the link to original post

Sql Server largest tables

  select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case 
     when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
     else lob_used_page_count + row_overflow_used_page_count 
    end )
, index_kb=8*(sum(used_page_count) 
    - sum( case 
           when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
        else lob_used_page_count + row_overflow_used_page_count 
        end )
     )    
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by 
rows desc   

In my database they gave different results between this query and the 1st answer.

Hope somebody finds useful

Use querystring variables in MVC controller

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

How do you count the lines of code in a Visual Studio solution?

cloc is an excellent commandline, Perl-based, Windows-executable which will break down the blank lines, commented lines, and source lines of code, grouped by file-formats.

Now it won't specifically run on a VS solution file, but it can recurse through directories, and you can set up filename filters as you see fit.

Here's the sample output from their web page:


prompt> cloc perl-5.10.0.tar.gz
    4076 text files.
    3883 unique files.                                          
    1521 files ignored.

http://cloc.sourceforge.net v 1.07  T=10.0 s (251.0 files/s, 84566.5 lines/s)
-------------------------------------------------------------------------------
Language          files     blank   comment      code    scale   3rd gen. equiv
-------------------------------------------------------------------------------
Perl               2052    110356    112521    309778 x   4.00 =     1239112.00
C                   135     18718     22862    140483 x   0.77 =      108171.91
C/C++ Header        147      7650     12093     44042 x   1.00 =       44042.00
Bourne Shell        116      3402      5789     36882 x   3.81 =      140520.42
Lisp                  1       684      2242      7515 x   1.25 =        9393.75
make                  7       498       473      2044 x   2.50 =        5110.00
C++                  10       312       277      2000 x   1.51 =        3020.00
XML                  26       231         0      1972 x   1.90 =        3746.80
yacc                  2       128        97      1549 x   1.51 =        2338.99
YAML                  2         2         0       489 x   0.90 =         440.10
DOS Batch            11        85        50       322 x   0.63 =         202.86
HTML                  1        19         2        98 x   1.90 =         186.20
-------------------------------------------------------------------------------
SUM:               2510    142085    156406    547174 x   2.84 =     1556285.03
-------------------------------------------------------------------------------

The third generation equivalent scale is a rough estimate of how much code it would take in a third generation language. Not terribly useful, but interesting anyway.

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()