Programs & Examples On #Enumeration

The process of enumerating values, for example from some collection.

How to iterate a loop with index and element in Swift

Swift 5.x:

I personally prefer using the forEach method:

list.enumerated().forEach { (index, element) in
    ...
}

You can also use the short version:

list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }

What does the "map" method do in Ruby?

Map is a part of the enumerable module. Very similar to "collect" For Example:

  Class Car

    attr_accessor :name, :model, :year

    Def initialize (make, model, year)
      @make, @model, @year = make, model, year
    end

  end

  list = []
  list << Car.new("Honda", "Accord", 2016)
  list << Car.new("Toyota", "Camry", 2015)
  list << Car.new("Nissan", "Altima", 2014)

  p list.map {|p| p.model}

Map provides values iterating through an array that are returned by the block parameters.

(How) can I count the items in an enum?

I like to use enums as arguments to my functions. It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option". As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.

enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;

It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.

Collection was modified; enumeration operation may not execute in ArrayList

I like to iterate backward using a for loop, but this can get tedious compared to foreach. One solution I like is to create an enumerator that traverses the list backward. You can implement this as an extension method on ArrayList or List<T>. The implementation for ArrayList is below.

    public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The implementation for List<T> is similar.

    public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The example below uses the enumerator to remove all even integers from an ArrayList.

    ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    foreach (int item in list.GetRemoveSafeEnumerator())
    {
        if (item % 2 == 0)
            list.Remove(item);
    }

What is the best way to modify a list in a 'foreach' loop?

LINQ is very effective for juggling with collections.

Your types and structure are unclear to me, but I will try to fit your example to the best of my ability.

From your code it appears that, for each item, you are adding to that item everything from its own 'Enumerable' property. This is very simple:

foreach (var item in Enumerable)
{
    item = item.AddRange(item.Enumerable));
}

As a more general example, let's say we want to iterate a collection and remove items where a certain condition is true. Avoiding foreach, using LINQ:

myCollection = myCollection.Where(item => item.ShouldBeKept);

Add an item based on each existing item? No problem:

myCollection = myCollection.Concat(myCollection.Select(item => new Item(item.SomeProp)));

How do I iterate over an NSArray?

The three ways are:

        //NSArray
    NSArray *arrData = @[@1,@2,@3,@4];

    // 1.Classical
    for (int i=0; i< [arrData count]; i++){
        NSLog(@"[%d]:%@",i,arrData[i]);
    }

    // 2.Fast iteration
    for (id element in arrData){
        NSLog(@"%@",element);
    }

    // 3.Blocks
    [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"[%lu]:%@",idx,obj);
         // Set stop to YES in case you want to break the iteration
    }];
  1. Is the fastest way in execution, and 3. with autocompletion forget about writing iteration envelope.

C# loop - break vs. continue

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.

Case objects vs Enumerations in Scala

One big difference is that Enumerations come with support for instantiating them from some name String. For example:

object Currency extends Enumeration {
   val GBP = Value("GBP")
   val EUR = Value("EUR") //etc.
} 

Then you can do:

val ccy = Currency.withName("EUR")

This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use case objects. A case object is more flexible than an enum:

sealed trait Currency { def name: String }
case object EUR extends Currency { val name = "EUR" } //etc.

case class UnknownCurrency(name: String) extends Currency

So now I have the advantage of...

trade.ccy match {
  case EUR                   =>
  case UnknownCurrency(code) =>
}

As @chaotic3quilibrium pointed out (with some corrections to ease reading):

Regarding "UnknownCurrency(code)" pattern, there are other ways to handle not finding a currency code string than "breaking" the closed set nature of the Currency type. UnknownCurrency being of type Currency can now sneak into other parts of an API.

It's advisable to push that case outside Enumeration and make the client deal with an Option[Currency] type that would clearly indicate there is really a matching problem and "encourage" the user of the API to sort it out him/herself.

To follow up on the other answers here, the main drawbacks of case objects over Enumerations are:

  1. Can't iterate over all instances of the "enumeration". This is certainly the case, but I've found it extremely rare in practice that this is required.

  2. Can't instantiate easily from persisted value. This is also true but, except in the case of huge enumerations (for example, all currencies), this doesn't present a huge overhead.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

Search for a string in Enum and return the Enum

One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here

With this you can define your enumerations as classes (the examples are in vb.net):

< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)

Private Sub New(ByVal StrValue As String)
  MyBase.New(StrValue)   
End Sub

< Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")   

< Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")   

End Class

And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

I've been using this for a long time now and it makes the code more clear in intent.

Enumerations on PHP

If you need to use enums that are globally unique (i.e. even when comparing elements between different Enums) and are easy to use, feel free to use the following code. I also added some methods that I find useful. You will find examples in the comments at the very top of the code.

<?php

/**
 * Class Enum
 * 
 * @author Christopher Fox <[email protected]>
 *
 * @version 1.0
 *
 * This class provides the function of an enumeration.
 * The values of Enum elements are unique (even between different Enums)
 * as you would expect them to be.
 *
 * Constructing a new Enum:
 * ========================
 *
 * In the following example we construct an enum called "UserState"
 * with the elements "inactive", "active", "banned" and "deleted".
 * 
 * <code>
 * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');
 * </code>
 *
 * Using Enums:
 * ============
 *
 * The following example demonstrates how to compare two Enum elements
 *
 * <code>
 * var_dump(UserState::inactive == UserState::banned); // result: false
 * var_dump(UserState::active == UserState::active); // result: true
 * </code>
 *
 * Special Enum methods:
 * =====================
 *
 * Get the number of elements in an Enum:
 *
 * <code>
 * echo UserState::CountEntries(); // result: 4
 * </code>
 *
 * Get a list with all elements of the Enum:
 *
 * <code>
 * $allUserStates = UserState::GetEntries();
 * </code>
 *
 * Get a name of an element:
 *
 * <code>
 * echo UserState::GetName(UserState::deleted); // result: deleted
 * </code>
 *
 * Get an integer ID for an element (e.g. to store as a value in a database table):
 * This is simply the index of the element (beginning with 1).
 * Note that this ID is only unique for this Enum but now between different Enums.
 *
 * <code>
 * echo UserState::GetDatabaseID(UserState::active); // result: 2
 * </code>
 */
class Enum
{

    /**
     * @var Enum $instance The only instance of Enum (Singleton)
     */
    private static $instance;

    /**
     * @var array $enums    An array of all enums with Enum names as keys
     *          and arrays of element names as values
     */
    private $enums;

    /**
     * Constructs (the only) Enum instance
     */
    private function __construct()
    {
        $this->enums = array();
    }

    /**
     * Constructs a new enum
     *
     * @param string $name The class name for the enum
     * @param mixed $_ A list of strings to use as names for enum entries
     */
    public static function Create($name, $_)
    {
        // Create (the only) Enum instance if this hasn't happened yet
        if (self::$instance===null)
        {
            self::$instance = new Enum();
        }

        // Fetch the arguments of the function
        $args = func_get_args();
        // Exclude the "name" argument from the array of function arguments,
        // so only the enum element names remain in the array
        array_shift($args);
        self::$instance->add($name, $args);
    }

    /**
     * Creates an enumeration if this hasn't happened yet
     * 
     * @param string $name The class name for the enum
     * @param array $fields The names of the enum elements
     */
    private function add($name, $fields)
    {
        if (!array_key_exists($name, $this->enums))
        {
            $this->enums[$name] = array();

            // Generate the code of the class for this enumeration
            $classDeclaration =     "class " . $name . " {\n"
                        . "private static \$name = '" . $name . "';\n"
                        . $this->getClassConstants($name, $fields)
                        . $this->getFunctionGetEntries($name)
                        . $this->getFunctionCountEntries($name)
                        . $this->getFunctionGetDatabaseID()
                        . $this->getFunctionGetName()
                        . "}";

            // Create the class for this enumeration
            eval($classDeclaration);
        }
    }

    /**
     * Returns the code of the class constants
     * for an enumeration. These are the representations
     * of the elements.
     * 
     * @param string $name The class name for the enum
     * @param array $fields The names of the enum elements
     *
     * @return string The code of the class constants
     */
    private function getClassConstants($name, $fields)
    {
        $constants = '';

        foreach ($fields as $field)
        {
            // Create a unique ID for the Enum element
            // This ID is unique because class and variables
            // names can't contain a semicolon. Therefore we
            // can use the semicolon as a separator here.
            $uniqueID = $name . ";" . $field;
            $constants .=   "const " . $field . " = '". $uniqueID . "';\n";
            // Store the unique ID
            array_push($this->enums[$name], $uniqueID);
        }

        return $constants;
    }

    /**
     * Returns the code of the function "GetEntries()"
     * for an enumeration
     * 
     * @param string $name The class name for the enum
     *
     * @return string The code of the function "GetEntries()"
     */
    private function getFunctionGetEntries($name) 
    {
        $entryList = '';        

        // Put the unique element IDs in single quotes and
        // separate them with commas
        foreach ($this->enums[$name] as $key => $entry)
        {
            if ($key > 0) $entryList .= ',';
            $entryList .= "'" . $entry . "'";
        }

        return  "public static function GetEntries() { \n"
            . " return array(" . $entryList . ");\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "CountEntries()"
     * for an enumeration
     * 
     * @param string $name The class name for the enum
     *
     * @return string The code of the function "CountEntries()"
     */
    private function getFunctionCountEntries($name) 
    {
        // This function will simply return a constant number (e.g. return 5;)
        return  "public static function CountEntries() { \n"
            . " return " . count($this->enums[$name]) . ";\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "GetDatabaseID()"
     * for an enumeration
     * 
     * @return string The code of the function "GetDatabaseID()"
     */
    private function getFunctionGetDatabaseID()
    {
        // Check for the index of this element inside of the array
        // of elements and add +1
        return  "public static function GetDatabaseID(\$entry) { \n"
            . "\$key = array_search(\$entry, self::GetEntries());\n"
            . " return \$key + 1;\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "GetName()"
     * for an enumeration
     *
     * @return string The code of the function "GetName()"
     */
    private function getFunctionGetName()
    {
        // Remove the class name from the unique ID 
        // and return this value (which is the element name)
        return  "public static function GetName(\$entry) { \n"
            . "return substr(\$entry, strlen(self::\$name) + 1 , strlen(\$entry));\n"
            . "}\n";
    }

}


?>

How to enumerate an enum

It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (string name in Enum.GetNames(typeof(Suits)))
    {
        System.Console.WriteLine(name);
    }
}

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (var suit in Enum.GetValues(typeof(Suits)))
    {
        System.Console.WriteLine(suit.ToString());
    }
}

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

Java getting the Enum name given the Enum Value

You should replace your getEnumNameForValue by a call to the name() method.

foreach vs someList.ForEach(){}

One thing to be wary of is how to exit from the Generic .ForEach method - see this discussion. Although the link seems to say that this way is the fastest. Not sure why - you'd think they would be equivalent once compiled...

for each loop in Objective-C for accessing NSMutable dictionary

Fast enumeration was added in 10.5 and in the iPhone OS, and it's significantly faster, not just syntactic sugar. If you have to target the older runtime (i.e. 10.4 and backwards), you'll have to use the old method of enumerating:

NSDictionary *myDict = ... some keys and values ...
NSEnumerator *keyEnum = [myDict keyEnumerator];
id key;

while ((key = [keyEnum nextObject]))
{
    id value = [myDict objectForKey:key];
    ... do work with "value" ...
}

You don't release the enumerator object, and you can't reset it. If you want to start over, you have to ask for a new enumerator object from the dictionary.

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

How to sort a list of objects based on an attribute of the objects?

If the attribute you want to sort by is a property, then you can avoid importing operator.attrgetter and use the property's fget method instead.

For example, for a class Circle with a property radius we could sort a list of circles by radii as follows:

result = sorted(circles, key=Circle.radius.fget)

This is not the most well-known feature but often saves me a line with the import.

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

How do I retrieve an HTML element's actual width and height?

NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

Iterate through <select> options

$.each($("#MySelect option"), function(){
                    alert($(this).text() + " - " + $(this).val());                    
                });

batch script - read line by line

For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
    ECHO %%A
)

To explain:

(path\with spaces\to\my.log)

Will not parse, because spaces. If it becomes:

("path\with spaces\to\my.log")

It will be handled as a string rather than a file path.

"usebackq delims=" 

See docs will allow the path to be used as a path (thanks to Stephan).

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I was also facing the same issue until I added the type="module" to the script.

Before it was like this

<script src="../src/main.js"></script>

And after changing it to

<script type="module" src="../src/main.js"></script>

It worked perfectly.

Routing HTTP Error 404.0 0x80070002

Uncheck this in Windows Explorer.

"Hide file type extensions for known types"

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

What regular expression will match valid international phone numbers?

Modified @Eric's regular expression - added a list of all country codes (got them from xxxdepy @ Github. I hope you will find it helpful:

/(\+|00)(297|93|244|1264|358|355|376|971|54|374|1684|1268|61|43|994|257|32|229|226|880|359|973|1242|387|590|375|501|1441|591|55|1246|673|975|267|236|1|61|41|56|86|225|237|243|242|682|57|269|238|506|53|5999|61|1345|357|420|49|253|1767|45|1809|1829|1849|213|593|20|291|212|34|372|251|358|679|500|33|298|691|241|44|995|44|233|350|224|590|220|245|240|30|1473|299|502|594|1671|592|852|504|385|509|36|62|44|91|246|353|98|964|354|972|39|1876|44|962|81|76|77|254|996|855|686|1869|82|383|965|856|961|231|218|1758|423|94|266|370|352|371|853|590|212|377|373|261|960|52|692|389|223|356|95|382|976|1670|258|222|1664|596|230|265|60|262|264|687|227|672|234|505|683|31|47|977|674|64|968|92|507|64|51|63|680|675|48|1787|1939|850|351|595|970|689|974|262|40|7|250|966|249|221|65|500|4779|677|232|503|378|252|508|381|211|239|597|421|386|46|268|1721|248|963|1649|235|228|66|992|690|993|670|676|1868|216|90|688|886|255|256|380|598|1|998|3906698|379|1784|58|1284|1340|84|678|681|685|967|27|260|263)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{4,20}$/

When should you use a class vs a struct in C++?

Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...But that's really just taking advantage of struct's default protection level being public...

Declaring an HTMLElement Typescript

Note that const declarations are block-scoped.

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

So the value of definitelyAnElement is not accessible outside of the {}.

(I would have commented above, but I do not have enough Reputation apparently.)

"relocation R_X86_64_32S against " linking Error

Assuming you are generating a shared library, most probably what happens is that the variant of liblog4cplus.a you are using wasn't compiled with -fPIC. In linux, you can confirm this by extracting the object files from the static library and checking their relocations:

ar -x liblog4cplus.a  
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'

If the output is empty, then the static library is not position-independent and cannot be used to generate a shared object.

Since the static library contains object code which was already compiled, providing the -fPIC flag won't help.

You need to get ahold of a version of liblog4cplus.a compiled with -fPIC and use that one instead.

Dynamic SELECT TOP @var In SQL Server

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

How can I make my custom objects Parcelable?

Android parcable has some unique things. Those are given bellow:

  1. You have to read Parcel as the same order where you put data on parcel.
  2. Parcel will empty after read from parcel. That is if you have 3 data on your parcel. Then after read 3 times parcel will be empty.

Example: To make a class Parceble it must be implement Parceble. Percable has 2 method:

int describeContents();
void writeToParcel(Parcel var1, int var2);

Suppose you have a Person class and it has 3 field, firstName,lastName and age. After implementing Parceble interface. this interface is given bellow:

import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

}

Here writeToParcel method we are writing/adding data on Parcel in an order. After this we have to add bellow code for reading data from parcel:

protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

Here, Person class is taking a parcel and getting data in same an order during writing.

Now during intent getExtra and putExtra code is given bellow:

Put in Extra:

Person person=new Person();
                person.setFirstName("First");
                person.setLastName("Name");
                person.setAge(30);

                Intent intent = new Intent(getApplicationContext(), SECOND_ACTIVITY.class);
                intent.putExtra()
                startActivity(intent); 

Get Extra:

Person person=getIntent().getParcelableExtra("person");

Full Person class is given bellow:

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;



    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

    protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

}

Hope this will help you 
Thanks :)

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

NSRange to Range<String.Index>

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

       let strString = ((textField.text)! as NSString).stringByReplacingCharactersInRange(range, withString: string)

 }

How to measure the a time-span in seconds using System.currentTimeMillis()?

Java 8 now provides the most concise method to get current Unix Timestamp:

Instant.now().getEpochSecond();

R memory management / cannot allocate vector of size n Mb

Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix package for e.g.) for sparse matrices.

Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc() to clear now unused memory, or, better only create the object you need in one session.

If the above cannot help, get a 64-bit machine with as much RAM as you can afford, and install 64-bit R.

If you cannot do that there are many online services for remote computing.

If you cannot do that the memory-mapping tools like package ff (or bigmemory as Sascha mentions) will help you build a new solution. In my limited experience ff is the more advanced package, but you should read the High Performance Computing topic on CRAN Task Views.

C# : Converting Base Class to Child Class

I don't think you can downcast an object, however there is a simple way to "downcast" the object outside the box. It isn't type safe, but it works. First serialize the object into json, then deserialize it into the child class object. It works the same as if you were passing the object between apis. So, while there are some people who may say "this doesn't work or isn't good", I would argue that it is exactly the way our internet currently works, so... why not use that method? No mapping required as long as parameter names are the same, and they will be if it is a child class. Note: This will likely not copy any private fields; if you have a constructor with parameters, this probably needs to be tested as well to ensure there aren't side effects.

Here's my toolbox:

public static string ConvertToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj);
}
public static T ConvertToObject<T>(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return Activator.CreateInstance<T>();
    }
    return JsonConvert.DeserializeObject<T>(json);
}

Here's how to use it:

var sfcl = networkClient.ConvertToJson().ConvertToObject<SkyfilterClient>();

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

You might want to use python's rpy2 module. However, the "right" way to do this is with R CMD BATCH. You can modify this to write to STDOUT, but the default is to write to a .Rout file. See example below:

[ramanujan:~]$cat foo.R
print(rnorm(10))
[ramanujan:~]$R CMD BATCH foo.R
[ramanujan:~]$cat foo.Rout

R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]


 ~/.Rprofile loaded.
Welcome at  Fri Apr 17 13:33:17 2009
> print(rnorm(10))
 [1]  1.5891276  1.1219071 -0.6110963  0.1579430 -0.3104579  1.0072677 -0.1303165  0.6998849  1.9918643 -1.2390156
>

Goodbye at  Fri Apr 17 13:33:17 2009
> proc.time()
   user  system elapsed
  0.614   0.050   0.721

Note: you'll want to try out the --vanilla and other options to remove all the startup cruft.

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

Styling input buttons for iPad and iPhone

Please add this css code

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

check if file exists on remote host with ssh

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists"

The above will run the echo command on the machine you're running the ssh command from. To get the remote server to run the command:

ssh -q $HOST "[[ ! -f $FILE_PATH ]] && touch $FILE_PATH"

Convert char array to a int number in C

So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},
}

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach

 SqlParameter @TableName = new SqlParameter()
        {
            ParameterName = "@TableName",
            DbType = DbType.String,
            Value = "Trans"
        };

SqlParameter @FieldName = new SqlParameter()
        {
            ParameterName = "@FieldName",
            DbType = DbType.String,
            Value = "HLTransNbr"
        };


object[] parameters = new object[] { @TableName, @FieldName };

List<Sample> x = this.Database.SqlQuery<Sample>("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();


public class Sample
{
    public string TableName { get; set; }
    public string FieldName { get; set; }
    public int NextNum { get; set; }
}

UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line

 List<Sample> x = this.Database.SqlQuery<Sample>(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();

How to add a spinner icon to button when it's in the Loading state?

Simple solution for Bootstrap 3 using CSS3 animations.

Put the following in your CSS:

.glyphicon.spinning {
    animation: spin 1s infinite linear;
    -webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg); }
    to { transform: scale(1) rotate(360deg); }
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg); }
    to { -webkit-transform: rotate(360deg); }
}

Then just add the spinning class to a glyphicon while loading to get your spinning icon:

<button class="btn btn-lg btn-warning">
    <span class="glyphicon glyphicon-refresh spinning"></span> Loading...    
</button>

Based on http://www.bootply.com/128062#

  • Note: IE9 and below do not support CSS3 animations.

What is the idiomatic Go equivalent of C's ternary operator?

Foreword: Without arguing that if else is the way to go, we can still play with and find pleasure in language-enabled constructs.

The following If construct is available in my github.com/icza/gox library with lots of other methods, being the gox.If type.


Go allows to attach methods to any user-defined types, including primitive types such as bool. We can create a custom type having bool as its underlying type, and then with a simple type conversion on the condition, we have access to its methods. Methods that receive and select from the operands.

Something like this:

type If bool

func (c If) Int(a, b int) int {
    if c {
        return a
    }
    return b
}

How can we use it?

i := If(condition).Int(val1, val2)  // Short variable declaration, i is of type int
     |-----------|  \
   type conversion   \---method call

For example a ternary doing max():

i := If(a > b).Int(a, b)

A ternary doing abs():

i := If(a >= 0).Int(a, -a)

This looks cool, it's simple, elegant, and efficient (it's also eligible for inlining).

One downside compared to a "real" ternary operator: it always evaluates all operands.

To achieve deferred and only-if-needed evaluation, the only option is to use functions (either declared functions or methods, or function literals), which are only called when / if needed:

func (c If) Fint(fa, fb func() int) int {
    if c {
        return fa()
    }
    return fb()
}

Using it: Let's assume we have these functions to calculate a and b:

func calca() int { return 3 }
func calcb() int { return 4 }

Then:

i := If(someCondition).Fint(calca, calcb)

For example, the condition being current year > 2020:

i := If(time.Now().Year() > 2020).Fint(calca, calcb)

If we want to use function literals:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return 3 },
    func() int { return 4 },
)

Final note: if you would have functions with different signatures, you could not use them here. In that case you may use a function literal with matching signature to make them still applicable.

For example if calca() and calcb() would have parameters too (besides the return value):

func calca2(x int) int { return 3 }
func calcb2(x int) int { return 4 }

This is how you could use them:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return calca2(0) },
    func() int { return calcb2(0) },
)

Try these examples on the Go Playground.

Looking for a short & simple example of getters/setters in C#

Getters and Setters in C# are something that simplifies the code.

private string name = "spots";

public string Name
{
    get { return name; }
    set { name = value; }
}

And calling it (assume we have a person obj with a name property):

Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"

This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:

public string foobar {get; set;}

This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!

Invariant Violation: Objects are not valid as a React child

In my case it was because of a dynamic array which had to be injected at runtime.

I just added the null checks for object and it worked fine.

Before:

...
render(
...
    <div> {props.data.roles[0]} </div>
...
);

After:

...
let items = (props && props.data && props.data.roles)? props.data.roles: [];
render(
...
    <div> {items[i]} </div>
...
);

npm not working - "read ECONNRESET"

Remove your proxy settings at home and switch on at Office networks, This may be irritating, But It worked for me:

npm config set proxy http://xxx.xxx.xxx.4:8080   
npm config set https-proxy http://xxx.xxx.xxx.4:8080

and

npm config rm proxy   
npm config rm https-proxy

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

One of the basic and simple thing which leads to this error is: No Internet Connection

Turn on the Internet Connection of your device first.

(May be we'll forget to do so)

Professional jQuery based Combobox control?

For large datasets, how about JQuery UI Autocomplete, which is basically the "official" version of Jorn Zaeferrer's Autocomplete plugin?

I also wrote a straight JQuery combobox plugin that's gotten pretty good feedback from its users. It's explicitly not meant for large datasets though; I figure that if you want something that prunes the list based on what the user types, you're better off with Jorn's autocompletion plugin.

PHP sessions that have already been started

It would be more efficient:

@session_start();

Avoiding error handler in the screen

Best,

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

what does numpy ndarray shape do?

array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

enter image description here

Ignore Duplicates and Create New List of Unique Values in Excel

All you have to do is : Go to Data tab Chose advanced in Sort & Filter In actions select : copy to another location if want a new list - Copy to any location In list range chose the list you want to get the records off . And the most important thing is to check : Unique records only .

Passing command line arguments in Visual Studio 2010?

Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)

Greetings mic enter image description here

NSURLConnection Using iOS Swift

An abbreviated version of your code worked for me,

class Remote: NSObject {

    var data = NSMutableData()

    func connect(query:NSString) {
        var url =  NSURL.URLWithString("http://www.google.com")
        var request = NSURLRequest(URL: url)
        var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
    }


     func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("didReceiveResponse")
    }

    func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
        self.data.appendData(conData)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println(self.data)
    }


    deinit {
        println("deiniting")
    }
}

This is the code I used in the calling class,

class ViewController: UIViewController {

    var remote = Remote()


    @IBAction func downloadTest(sender : UIButton) {
        remote.connect("/apis")
    }

}

You didn't specify in your question where you had this code,

var remote = Remote()
remote.connect("/apis")

If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.

How can I create a blank/hardcoded column in a sql query?

The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.

See http://www.cfquickdocs.com/cf9/#queryaddcolumn

Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

Magento addFieldToFilter: Two fields, match as OR, not AND

This is the real magento way:

    $collection=Mage::getModel('sales/order')
                ->getCollection()
                ->addFieldToFilter(
                        array(
                            'customer_firstname',//attribute_1 with key 0
                            'remote_ip',//attribute_2 with key 1
                        ),
                        array(
                            array('eq'=>'gabe'),//condition for attribute_1 with key 0
                            array('eq'=>'127.0.0.1'),//condition for attribute_2
                                )
                            )
                        );

SQL query to select dates between two dates

Select 
    * 
from 
    Calculation 
where 
    EmployeeId=1 and Date between #2011/02/25# and #2011/02/27#;

SQL order string as number

This works for me.

select * from tablename
order by cast(columnname as int) asc

Focus Next Element In Tab Index

refer this pure js npm library for such tab navigation strategies.
keyboard-navigator
this small library handles tab key,arrow key navigation,retaining focus on dom updates,modal focus trap, fallback focus.

How can I get the console logs from the iOS Simulator?

[iOS Logger]

You can use the Console application(select your device in Devices) on your Mac to see a log message that were sent using NSLog, os_log, Logger (you will not see logs from print function).

Also please check (Action -> Include <Info/Debug> Messages)

enter image description here

Please note that if you want to see a log from WebView(UIWebView or WKWebView) you should use Safary -> Develop -> device

[Find crash log]

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

"Cannot update paths and switch to branch at the same time"

This simple thing worked for me!

If it says it can't do 2 things at same time, separate them.

git branch branch_name origin/branch_name 

git checkout branch_name

How do you disable viewport zooming on Mobile Safari?

In Safari 9.0 and up you can use shrink-to-fit in viewport meta tag as shown below

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

Getting attribute using XPath

You can try below xPath pattern,

  XPathExpression expr = xPath.compile("/bookstore/book/title[@lang='eng']")

How do I get the path of the assembly the code is in?

I use this to get the path to the Bin Directory:

var i = Environment.CurrentDirectory.LastIndexOf(@"\");
var path = Environment.CurrentDirectory.Substring(0,i); 

You get this result:

"c:\users\ricooley\documents\visual studio 2010\Projects\Windows_Test_Project\Windows_Test_Project\bin"

Does IMDB provide an API?

The IMDb has a public API that, although undocumented, is fast and reliable (used on the official website through AJAX).

Search Suggestions API

// 1) Vanilla JavaScript (JSON-P)
function addScript(src) { var s = document.createElement('script'); s.src = src; document.head.appendChild(s); }
window.imdb$foo = function (results) {
  /* ... */
};
addScript('https://sg.media-imdb.com/suggests/f/foo.json');

// 2) Using jQuery (JSON-P)
jQuery.ajax({
    url: 'https://sg.media-imdb.com/suggests/f/foo.json',
    dataType: 'jsonp',
    cache: true,
    jsonp: false,
    jsonpCallback: 'imdb$foo'
}).then(function (results) {
    /* ... */
});

// 3) Pure JSON (with jQuery)
// Use a local proxy that strips the "padding" of JSON-P,
// e.g. "imdb$foo(" and ")", leaving pure JSON only.
jQuery.getJSON('/api/imdb/?q=foo', function (results) {
    /* ... */
});

// 4) Pure JSON (ES2017 and Fetch API)
// Using a custom proxy at "/api" that strips the JSON-P padding.
const resp = await fetch('/api/imdb/?q=foo');
const results = await resp.json();

Advanced Search


Beware that these APIs are unofficial and could change at any time!


Update (January 2019): The Advanced API no longer exists. The good news is, that the Suggestions API now supports the "advanced" features of searching by film titles and actor names as well.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

You can use another shell to execute the same command:

Error I get when i execute:

[jenkins@localhost jenkins_data]$ docker exec -it mysqldb \bin\bash
OCI runtime exec failed: exec failed: container_linux.go:345: starting container process caused "exec: \"binsh\": executable file not found in $PATH": unknown

Solution: When I execute it with below command, using bash shell it works:

[jenkins@localhost jenkins_data]$ docker exec -it mysqldb bash
root@<container-ID>:/#

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

Why has it failed to load main-class manifest attribute from a JAR file?

I discovered that I was also having this error in NetBeans. I hope the following is helpful.

  1. Make sure that when you go to Project Configuration you set the main class you intend for running.
  2. Do a Build or Clean Build
  3. Place the jar file where you wish and try: java -jar "YourProject.jar" again at the command line.

This was the problem I was getting because I had other "test" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.

many blessings, John P

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

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

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

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

How can I show the table structure in SQL Server query?

To print a schema, I use jade and do an export to a file of the database then bring it into word to format and print

git discard all changes and pull from upstream

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

Get Current Session Value in JavaScript?

Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Already Answered here

How to start jenkins on different port rather than 8080 using command prompt in Windows?

For Fedora, RedHat, CentOS and alike, any customization should be done within /etc/sysconfig/jenkins instead of /etc/init.d/jenkins. The purpose of the first file is exactly the customization of the second file.

So, within /etc/sysconfig/jenkins, there is a the JENKINS_PORT variable that holds the port number on which Jenkins is running.

What is the difference between POST and GET?

GET and POST are two different types of HTTP requests.

According to Wikipedia:

GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

and

POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.


HTTP/1.1 specification (RFC 2616) section 9 Method Definitions contains more information on GET and POST as well as the other HTTP methods, if you are interested.

In addition to explaining the intended uses of each method, the spec also provides at least one practical reason for why GET should only be used to retrieve data:

Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead


Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.

How to check if a text field is empty or not in swift

Swift 4.x Solution


@IBOutlet var yourTextField: UITextField!

 override func viewDidLoad() {
     ....
     yourTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
  }

 @objc func actionTextFieldIsEditingChanged(sender: UITextField) {
     if sender.text.isEmpty {
       // textfield is empty
     } else {
       // text field is not empty
     }
  }

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Code:
Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

How to remove numbers from string using Regex.Replace?

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Copy tables from one database to another in SQL Server

If it’s one table only then all you need to do is

  • Script table definition
  • Create new table in another database
  • Update rules, indexes, permissions and such
  • Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

Test if string is URL encoded in PHP

I found.
The url is For Exapmle: https://example.com/xD?foo=bar&uri=https%3A%2F%2Fexample.com%2FxD
You need Found $_GET['uri'] is encoded or not:

preg_match("/.*uri=(.*)&?.*/", $_SERVER['REQUEST_URI'], $r);
if (isset($_GET['uri']) && urldecode($r['1']) === $r['1']) {
  // Code Here if url is not encoded
}

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

How to calculate distance between two locations using their longitude and latitude value

Get KM from lat long

public static float getKmFromLatLong(float lat1, float lng1, float lat2, float lng2){
            Location loc1 = new Location("");
            loc1.setLatitude(lat1);
            loc1.setLongitude(lng1);
            Location loc2 = new Location("");
            loc2.setLatitude(lat2);
            loc2.setLongitude(lng2);
            float distanceInMeters = loc1.distanceTo(loc2);
            return distanceInMeters/1000;
        }

Creating a very simple linked list

I am giving an extract from the book "C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari"

Here’s a demonstration on the use of LinkedList:

var tune = new LinkedList<string>();
tune.AddFirst ("do"); // do
tune.AddLast ("so"); // do - so
tune.AddAfter (tune.First, "re"); // do - re- so
tune.AddAfter (tune.First.Next, "mi"); // do - re - mi- so
tune.AddBefore (tune.Last, "fa"); // do - re - mi - fa- so
tune.RemoveFirst(); // re - mi - fa - so
tune.RemoveLast(); // re - mi - fa
LinkedListNode<string> miNode = tune.Find ("mi");
tune.Remove (miNode); // re - fa
tune.AddFirst (miNode); // mi- re - fa
foreach (string s in tune) Console.WriteLine (s);

Table is marked as crashed and should be repaired

Here is where the repair button is:

alt text

When is the @JsonProperty property used and what is it used for?

As you know, this is all about serialize and desalinize an object. Suppose there is an object:

public class Parameter {
  public String _name;
  public String _value; 
}

The serialization of this object is:

{
  "_name": "...",
  "_value": "..."
}

The name of variable is directly used to serialize data. If you are about to remove system api from system implementation, in some cases, you have to rename variable in serialization/deserialization. @JsonProperty is a meta data to tell serializer how to serial object. It is used to:

  • variable name
  • access (READ, WRITE)
  • default value
  • required/optional

from example:

public class Parameter {
  @JsonProperty(
        value="Name",
        required=true,
        defaultValue="No name",
        access= Access.READ_WRITE)
  public String _name;
  @JsonProperty(
        value="Value",
        required=true,
        defaultValue="Empty",
        access= Access.READ_WRITE)
  public String _value; 
}

How do I fix the multiple-step OLE DB operation errors in SSIS?

This error will also occur when trying to do an insert and a field is coded not null and nulls are trying to be inserted.

Update UI from Thread in Android

The most simplest solution I have seen to supply a short execution to the UI thread is via the post() method of a view. This is needed since UI methods are not re-entrant. The method for this is:

package android.view;

public class View;

public boolean post(Runnable action);

The post() method corresponds to the SwingUtilities.invokeLater(). Unfortunately I didn't find something simple that corresponds to the SwingUtilities.invokeAndWait(), but one can build the later based on the former with a monitor and a flag.

So what you save by this is creating a handler. You simply need to find your view and then post on it. You can find your view via findViewById() if you tend to work with id-ed resources. The resulting code is very simple:

/* inside your non-UI thread */

view.post(new Runnable() {
        public void run() {
            /* the desired UI update */
        }
    });
}

Note: Compared to SwingUtilities.invokeLater() the method View.post() does return a boolean, indicating whether the view has an associated event queue. Since I used the invokeLater() resp. post() anyway only for fire and forget, I did not check the result value. Basically you should call post() only after onAttachedToWindow() has been called on the view.

Best Regards

How to sum a list of integers with java streams?

You can use reduce method:

long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, (x, y) -> x + y);

or

long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, Integer::sum);

How do you set the Content-Type header for an HttpClient request?

If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too:

using Flurl.Http;

var result = await "http://example.com/"
    .WithHeader("Accept", "application/json")
    .PostJsonAsync(new { ... })
    .ReceiveJson<TResult>();

Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms.

PM> Install-Package Flurl.Http

How do I convert a list of ascii values to a string in python?

def working_ascii():
    """
        G    r   e    e    t    i     n   g    s    !
        71, 114, 101, 101, 116, 105, 110, 103, 115, 33
    """

    hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
    pmsg = ''.join(chr(i) for i in hello)
    print(pmsg)

    for i in range(33, 256):
        print(" ascii: {0} char: {1}".format(i, chr(i)))

working_ascii()

Something like 'contains any' for Java set?

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

What is the { get; set; } syntax in C#?

Its basically a shorthand. You can write public string Name { get; set; } like in many examples, but you can also write it:

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value ; } // value is a special keyword here
}

Why it is used? It can be used to filter access to a property, for example you don't want names to include numbers.

Let me give you an example:

private class Person {
    private int _age;  // Person._age = 25; will throw an error
    public int Age{
        get { return _age; }  // example: Console.WriteLine(Person.Age);
        set { 
            if ( value >= 0) {
                _age = value; }  // valid example: Person.Age = 25;
        }
    }
}

Officially its called Auto-Implemented Properties and its good habit to read the (programming guide). I would also recommend tutorial video C# Properties: Why use "get" and "set".

WCF, Service attribute value in the ServiceHost directive could not be found

Option One:

This message is often due to an IIS 7 config problem. If you are used to creating a virtual directory pointing to the folder where your service resides, that no longer works. Now, you need to use the "Create Application..." option instead.

Other Options:

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Laravel Mail::send() sending to multiple to or bcc addresses

it works for me fine, if you a have string, then simply explode it first.

$emails = array();

Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
    foreach ($emails as $email) {
        $message->to($email);
    }

    $message->subject('My Email');
});

IntelliJ IDEA JDK configuration on Mac OS

Quite late to this party, today I had the same problem. The right answer on macOs I think is use jenv

brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11

And then add into Intellij IDEA as new SDK the following path:

~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

Percentage width in a RelativeLayout

I have solved this creating a custom View:

public class FractionalSizeView extends View {
  public FractionalSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FractionalSizeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width * 70 / 100, 0);
  }
}

This is invisible strut I can use to align other views within RelativeLayout.

AngularJS sorting rows by table header

You can use this code without arrows.....i.e by clicking on header it automatically shows ascending and descending order of elements

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="scripts/angular.min.js"></script>
    <script src="Scripts/Script.js"></script>
    <style>
        table {
            border-collapse: collapse;
            font-family: Arial;
        }

        td {
            border: 1px solid black;
            padding: 5px;
        }

        th {
            border: 1px solid black;
            padding: 5px;
            text-align: left;
        }
    </style>
</head>
<body ng-app="myModule">
    <div ng-controller="myController">

        <br /><br />
        <table>
            <thead>
                <tr>
                    <th>
                        <a href="#" ng-click="orderByField='name'; reverseSort = !reverseSort">
                            Name
                        </a>
                    </th>
                    <th>
                        <a href="#" ng-click="orderByField='dateOfBirth'; reverseSort = !reverseSort">
                            Date Of Birth
                        </a>
                    </th>
                    <th>
                        <a href="#" ng-click="orderByField='gender'; reverseSort = !reverseSort">
                           Gender
                        </a>
                    </th>
                    <th>
                        <a href="#" ng-click="orderByField='salary'; reverseSort = !reverseSort">
                            Salary
                        </a>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in employees | orderBy:orderByField:reverseSort">
                    <td>
                        {{ employee.name }}
                    </td>
                    <td>
                        {{ employee.dateOfBirth | date:"dd/MM/yyyy" }}
                    </td>
                    <td>
                        {{ employee.gender }}
                    </td>
                    <td>
                        {{ employee.salary  }}
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        var app = angular
        .module("myModule", [])
        .controller("myController", function ($scope) {

            var employees = [
                {
                    name: "Ben", dateOfBirth: new Date("November 23, 1980"),
                    gender: "Male", salary: 55000
                },
                {
                    name: "Sara", dateOfBirth: new Date("May 05, 1970"),
                    gender: "Female", salary: 68000
                },
                {
                    name: "Mark", dateOfBirth: new Date("August 15, 1974"),
                    gender: "Male", salary: 57000
                },
                {
                    name: "Pam", dateOfBirth: new Date("October 27, 1979"),
                    gender: "Female", salary: 53000
                },
                {
                    name: "Todd", dateOfBirth: new Date("December 30, 1983"),
                    gender: "Male", salary: 60000
                }
            ];

            $scope.employees = employees;
            $scope.orderByField = 'name';
            $scope.reverseSort = false;

        });
    </script>
</body>
</html>

Why use Redux over Facebook Flux?

You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks

Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.

Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

Adding double quote delimiters into csv file

open powershell and run below command:

import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv  -NoTypeInformation -Encoding UTF8

Catch an exception thrown by an async void method

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async Task Foo()
{
    var x = await DoSomethingAsync();
}

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          // The exception will be caught because you've awaited
          // the call in an async method.
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've
             waited for the completion of the call. */
    }
} 

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

Auto-center map with multiple markers in Google Maps API v3

I've tryied all answers of this topic, but just this below worked fine on my project.

Angular 7 and AGM Core 1.0.0-beta.7

<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
  <agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
    *ngFor="let localizacao of localizacoesTec">
  </agm-marker>
</agm-map>

The properties [agmFitBounds]="true" at agm-marker and [fitBounds]="true" at agm-map does the job

Missing MVC template in Visual Studio 2015

For me, I saw none of the MVC templates (except the bottom two), after installing Update 3 which installed all the Core stuff.

missing mvc

Solution

I downloaded most recent core preview...

corepreview

It prompted me for "repair" and after it was done, bringing up VS indicated it was "Installing Templates" and they appeared!

Warning

Update 3 is a game changer in that the "preferred" way of doing things is to use dotnetcore. For example a console application now uses the new file stucture, other projects such as a Test Project still use the same folder structure as before. But MVC has changed. I'm not even sure what other "Web Developer Tools" work with dotnetcore right now.

How to Use UTF-8 Collation in SQL Server database?

UTF-8 is not a character set, it's an encoding. The character set for UTF-8 is Unicode. If you want to store Unicode text you use the nvarchar data type.

If the database would use UTF-8 to store text, you would still not get the text out as encoded UTF-8 data, you would get it out as decoded text.

You can easily store UTF-8 encoded text in the database, but then you don't store it as text, you store it as binary data (varbinary).

How can I implement prepend and append with regular JavaScript?

You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element? If so here's how you can do it pretty easily:

//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");

//append text
someDiv.innerHTML += "Add this text to the end";

//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;

Pretty easy.

How do I force Kubernetes to re-pull an image?

Apparently now when you run a rolling-update with the --image argument the same as the existing container image, you must also specify an --image-pull-policy. The following command should force a pull of the image when it is the same as the container image:

kubectl rolling-update myapp --image=us.gcr.io/project-107012/myapp:5c3dda6b --image-pull-policy Always

Firestore Getting documents id from collection

For angular6+

    this.shirtCollection = afs.collection<Shirt>('shirts');
    this.shirts = this.shirtCollection.snapshotChanges().pipe(
        map(actions => {
        return actions.map(a => {
            const data = a.payload.doc.data() as Shirt;
            const id = a.payload.doc.id;
            return { id, ...data };
        });
        })
    );

Does C have a string type?

To note it in the languages you mentioned:

Java:

String str = new String("Hello");

Python:

str = "Hello"

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.

C:

char * str = "Hello";  // the string "Hello\0" is pointed to by the character pointer
                       // str. This "string" can not be modified (read only)

or

char str[] = "Hello";  // the characters: 'H''e''l''l''o''\0' have been copied to the 
                       // array str. You can change them via: str[x] = 't'

A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0'). Note that the sentinel character is auto-magically appended for you in the cases above.

How can I inspect element in chrome when right click is disabled?

Use Ctrl+Shift+C (or Cmd+Shift+C on Mac) to open the DevTools in Inspect Element mode, or toggle Inspect Element mode if the DevTools are already open.

compression and decompression of string data in java

The above Answer solves our problem but in addition to that. if we are trying to decompress a uncompressed("not a zip format") byte[] . we will get "Not in GZIP format" exception message.

For solving that we can add addition code in our Class.

public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}

My Complete Compression Class with compress/decompress would look like:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompression {
  public static byte[] compress(final String str) throws IOException {
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return obj.toByteArray();
  }

  public static String decompress(final byte[] compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
    if (isCompressed(compressed)) {
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    } else {
      outStr.append(compressed);
    }
    return outStr.toString();
  }

  public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
  }
}

Python Finding Prime Factors

def find_prime_facs(n):
  list_of_factors=[]
  i=2
  while n>1:
    if n%i==0:
      list_of_factors.append(i)
      n=n/i
      i=i-1
    i+=1  
  return list_of_factors

window.location.reload with clear cache

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

How do I clear all variables in the middle of a Python script?

The globals() function returns a dictionary, where keys are names of objects you can name (and values, by the way, are ids of these objects) The exec() function takes a string and executes it as if you just type it in a python console. So, the code is

for i in list(globals().keys()):
    if(i[0] != '_'):
        exec('del {}'.format(i))

grep --ignore-case --only

It should be a problem in your version of grep.

Your test cases are working correctly here on my machine:

$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC

And my version is:

$ grep --version
grep (GNU grep) 2.10

Is it possible to clone html element objects in JavaScript / JQuery?

You need to select "#foo2" as your selector. Then, get it with html().

Here is the html:

<div id="foo1">

</div>
<div id="foo2">
    <div>Foo Here</div>
</div>?

Here is the javascript:

$("#foo2").click(function() {
    //alert("clicked");
    var value=$(this).html();
    $("#foo1").html(value);
});?

Here is the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

HTML5 validation when the input type is not "submit"

Try this out:

<script type="text/javascript">
    function test
    {
        alert("hello world");  //write your logic here like ajax
    }
</script>

<form action="javascript:test();" >
    firstName : <input type="text" name="firstName" id="firstName" required/><br/>
    lastName : <input type="text" name="lastName" id="lastName" required/><br/>
    email : <input type="email" name="email" id="email"/><br/>
    <input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

data.map is not a function

data is not an array, it is an object with an array of products so iterate over data.products

var allProducts = data.products.map(function (item) {
    return new getData(item);
});

How to show PIL images on the screen?

You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:

import Tkinter as tk
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
#window.geometry("500x500") # (optional)    
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()

For Python 3, replace import Tkinter as tk with import tkinter as tk.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

angularjs to output plain text instead of html

<div ng-bind-html="myText"></div> No need to put into html {{}} interpolation tags like you did {{myText}}.

and don't forget to use ngSanitize in module like e.g. var app = angular.module("myApp", ['ngSanitize']);

and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize

Getting request payload from POST request in Java servlet

You can use Buffer Reader from request to read

    // Read from request
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append(System.lineSeparator());
    }
    String data = buffer.toString()

What is the best regular expression to check if a string is a valid URL?

How about this:

^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})$

These are the test cases:

Test cases

You can try it out in here : https://regex101.com/r/mS9gD7/41

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Same problem with Sourcetree On Mac

Solution: Delete the password in keychain access.

enter image description here

https://community.atlassian.com/t5/Sourcetree-questions/SourceTree-quot-fatal-Authentication-failed-for-quot/qaq-p/201844

When you try to push again it will ask for your password.

how to remove untracked files in Git?

You may also return to the previous state of the local repo in another way:

  1. Add the untracked files to the staging area with git add.
  2. return to the previous state of the local repo with git reset --hard.

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

TypeError: 'int' object is not subscriptable

Try this instead:

sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln

sumall is a number, and you can't access its digits using the subscript notation (sumall[0], sumall[1]). For that to work, you'll need to transform it back to a string.

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

python for increment inner loop

It seems that you want to use step parameter of range function. From documentation:

range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
 >>> range(0, 10, 3) [0, 3, 6, 9]
 >>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
 >>> range(0) []
 >>> range(1, 0) []

In your case to get [0,2,4] you can use:

range(0,6,2)

OR in your case when is a var:

idx = None
for i in range(len(str1)):
    if idx and i < idx:
        continue
    for j in range(len(str2)):
        if str1[i+j] != str2[j]:
            break
    else:
        idx = i+j

Remove all multiple spaces in Javascript and replace with single space

you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp

here best solution

str = str.replace(/\s{2,}/g, ' ');

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one() {_x000D_
    function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
    alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
    alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
_x000D_
_x000D_

A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

To remove the frame of the chart

for spine in plt.gca().spines.values():
  spine.set_visible(False)

I hope this could work

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^ symbol.

curl http://localhost:7101/module/url ^
  -d @D:/request.xml ^
  -H "Content-Type: text/xml" ^
  -H "SOAPAction: process" ^
  -H "Authorization: Basic xyz" ^
  -X POST

Cmake doesn't find Boost

You can also specify the version of Boost that you would like CMake to use by passing -DBOOST_INCLUDEDIR or -DBOOST_ROOT pointing to the location of correct version boost headers

Example:

cmake -DBOOST_ROOT=/opt/latestboost

This will also be useful when multiple boost versions are on the same system.

Using jquery to delete all elements with a given id

As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:

var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');

for(var i = spans.length; i--;) {
    var span = spans[i];
    if(span.className.match(/\btheclass\b/)) {
        span.parentNode.removeChild(span);
    }
}

getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.

Working Demo

Handler vs AsyncTask vs Thread

It depends which one to chose is based on the requirement

Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread

If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper

AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance

Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.

How do I set a value in CKEditor with Javascript?

I tried this and worked for me.

success: function (response) {
    document.getElementById('packageItems').value = response.package_items;

    ClassicEditor
    .create(document.querySelector('#packageItems'), {
        removePlugins: ['dragdrop']
    })
    .then(function (editor) {
        editor.setData(response.package_items);
    })
    .catch(function (err) {
        console.error(err);
    });
},

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

Combine or merge JSON on node.js without jQuery

Let object1 and object2 be two JSON object.

var object1 = [{"name": "John"}];
var object2 = [{"location": "San Jose"}];

object1.push(object2);

This will simply append object2 in object1:

[{"name":"John"},{"location":"San Jose"}]

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

python capitalize first letter only

As seeing here answered by Chen Houwu, it's possible to use string package:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

How to parse a date?

We now have a more modern way to do this work.

java.time

The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.

Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.

By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.

String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.

System.out.println ( "zdt : " + zdt );

When run.

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

Adjust Time Zone

For fun let's adjust to the India time zone.

ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

Convert to j.u.Date

If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Convert Pandas column containing NaNs to dtype `int`

use pd.to_numeric()

df["DateColumn"] = pd.to_numeric(df["DateColumn"])

simple and clean

How can I read an input string of unknown length?

Safer and faster (doubling capacity) version:

char *readline(char *prompt) {
  size_t size = 80;
  char *str = malloc(sizeof(char) * size);
  int c;
  size_t len = 0;
  printf("%s", prompt);
  while (EOF != (c = getchar()) && c != '\r' && c != '\n') {
    str[len++] = c;
    if(len == size) str = realloc(str, sizeof(char) * (size *= 2));
  }
  str[len++]='\0';
  return realloc(str, sizeof(char) * len);
}

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I ran into this in IntelliJ and fixed it by adding the following to my pom:

<!-- logging dependencies -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
        <exclusions>
            <exclusion>
                <!-- Defined below -->
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Is there a way to specify how many characters of a string to print out using printf()?

Print first four characters:

printf("%.4s\n", "A string that is more than 8 chars");

See this link for more information (check .precision -section)

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

Finding the id of a parent div using Jquery

To get the id of the parent div:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

To resolve this, you should open up a terminal window and type this command:

sudo chown -R user ~/.composer (with user being your current user, in your case, kramer65)

After you have ran this command, you should have permission to run your composer global require command.

You may also need to remove the .composer file from the current directory, to do this open up a terminal window and type this command:

sudo rm -rf .composer

How to show imageView full screen on imageView click?

Use Immersive Full-Screen Mode

enter image description here

call fullScreen() on ImageView click.

 public void fullScreen() {

        // BEGIN_INCLUDE (get_current_ui_flags)
        // The UI options currently enabled are represented by a bitfield.
        // getSystemUiVisibility() gives us that bitfield.
        int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
        int newUiOptions = uiOptions;
        // END_INCLUDE (get_current_ui_flags)
        // BEGIN_INCLUDE (toggle_ui_flags)
        boolean isImmersiveModeEnabled =
                ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
        if (isImmersiveModeEnabled) {
            Log.i(TAG, "Turning immersive mode mode off. ");
        } else {
            Log.i(TAG, "Turning immersive mode mode on.");
        }

        // Navigation bar hiding:  Backwards compatible to ICS.
        if (Build.VERSION.SDK_INT >= 14) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }

        // Status bar hiding: Backwards compatible to Jellybean
        if (Build.VERSION.SDK_INT >= 16) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
        }

        // Immersive mode: Backward compatible to KitKat.
        // Note that this flag doesn't do anything by itself, it only augments the behavior
        // of HIDE_NAVIGATION and FLAG_FULLSCREEN.  For the purposes of this sample
        // all three flags are being toggled together.
        // Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
        // Sticky immersive mode differs in that it makes the navigation and status bars
        // semi-transparent, and the UI flag does not get cleared when the user interacts with
        // the screen.
        if (Build.VERSION.SDK_INT >= 18) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }

        getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
        //END_INCLUDE (set_ui_flags)
    }

Read more

Example Download

Why use HttpClient for Synchronous Connection

I'd re-iterate Donny V. answer and Josh's

"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."

(and upvote if I had the reputation.)

I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.

Hence HttpClient is preferable.

Access all Environment properties as a Map or Properties object

This is an old question, but the accepted answer has a serious flaw. If the Spring Environment object contains any overriding values (as described in Externalized Configuration), there is no guarantee that the map of property values it produces will match those returned from the Environment object. I found that simply iterating through the PropertySources of the Environment did not, in fact, give any overriding values. Instead it produced the original value, the one that should have been overridden.

Here is a better solution. This uses the EnumerablePropertySources of the Environment to iterate through the known property names, but then reads the actual value out of the real Spring environment. This guarantees that the value is the one actually resolved by Spring, including any overriding values.

Properties props = new Properties();
MutablePropertySources propSrcs = ((AbstractEnvironment) springEnv).getPropertySources();
StreamSupport.stream(propSrcs.spliterator(), false)
        .filter(ps -> ps instanceof EnumerablePropertySource)
        .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
        .flatMap(Arrays::<String>stream)
        .forEach(propName -> props.setProperty(propName, springEnv.getProperty(propName)));

Origin is not allowed by Access-Control-Allow-Origin

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.

In Chrome, use this extension. If you are on Mozilla check this answer.

How to do this in Laravel, subquery where in

You can use Eloquent in different queries and make things easier to understand and mantain:

$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
                   ->select('product_id'); //don't need ->get() or ->first()

and then we put all together:

Products::whereIn('id', $productCategory)
          ->where('active', 1)
          ->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
          ->get();//runs all queries at once

This will generate the same query that you wrote in your question.

selectOneMenu ajax events

You could check whether the value of your selectOneMenu component belongs to the list of subjects.

Namely:

public void subjectSelectionChanged() {
    // Cancel if subject is manually written
    if (!subjectList.contains(aktNachricht.subject)) { return; }
    // Write your code here in case the user selected (or wrote) an item of the list
    // ....
}

Supposedly subjectList is a collection type, like ArrayList. Of course here your code will run in case the user writes an item of your selectOneMenu list.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

I found this free website that will make for you the policy AND host it:

https://www.freeprivacypolicy.com/

Then add it to the play store under Store Listing - at the bottom add the public link for the policy that you got from https://www.freeprivacypolicy.com/

Valid characters of a hostname?

A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.

This is provided in http://support.microsoft.com/kb/149044

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

Android Studio: Default project directory

At some point I too tried to do this, but the Android Studio doesn’t work quite like Eclipse does.

It's simpler: if you create a project at, say /home/USER/Projects/AndroidStudio/MyApplication from there on all new projects will default to /home/USER/Projects/AndroidStudio.

You can also edit ~/.AndroidStudioPreview/config/options/ide.general.xml (in linux) and change the line that reads <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" /> to <option name="lastProjectLocation" value="$USER_HOME$/Projects/AndroidStudio" />, but be aware that as soon as you create a project anywhere else this will change to that place and all new projects will default to it.

Hope this helps, but the truth is there really isn't much more to it other than what I explained here.

Let me know if you need anything else.

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

How can I use break or continue within for loop in Twig template?

I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:

{% for basename, perms in permsByBasenames %} 
    {% if basename == 'agency' %}
        {# do nothing #}
    {% else %}
        <a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
    {% endif %}
{% endfor %}

OR I simply skip it if it doesn't meet my criteria:

{% for tr in time_reports %}
    {% if not tr.isApproved %}
        .....
    {% endif %}
{% endfor %}

estimating of testing effort as a percentage of development time

From my experience, 25% effort is spent on Analysis; 50% for Design, Development and Unit Test; remaining 25% for testing. Most projects will fit within a +/-10% variance of this rule of thumb depending on the nature of the project, knowledge of resources, quality of inputs & outputs, etc. One can add a project management overhead within these percentages or as an overhead on top within a 10-15% range.

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

Your error is because you have:

     JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id

You have two instances of the same table, but the database can't determine which is which. To fix this, you need to use table aliases:

     JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id

It's good habit to always alias your tables, unless you like writing the full table name all the time when you don't have situations like these.

The next issues to address will be:

SELECT article.* , section.title, category.title, user.name, user.name

1) Never use SELECT * - always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.

2) You'll get ambiguous column errors relating to the user.name columns because again, the database can't tell which table instance to pull data from. Using table aliases fixes the issue:

SELECT article.* , section.title, category.title, u.name, u2.name

Parsing domain from a URL

I'm adding this answer late since this is the answer that pops up most on Google...

You can use PHP to...

$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"

to grab the host but not the private domain to which the host refers. (Example www.google.co.uk is the host, but google.co.uk is the private domain)

To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/

The below code works when an array of public suffixes has been created already. Simply call

$domain = get_private_domain("www.google.co.uk");

with the remaining code...

// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];

function get_public_suffix($host) {
  $parts = split("\.", $host);
  while (count($parts) > 0) {
    if (is_public_suffix(join(".", $parts)))
      return join(".", $parts);

    array_shift($parts);
  }

  return false;
}

function is_public_suffix($host) {
  global $suffix;
  return isset($suffix[$host]);
}

function get_private_domain($host) {
  $public = get_public_suffix($host);
  $public_parts = split("\.", $public);
  $all_parts = split("\.", $host);

  $private = [];

  for ($x = 0; $x < count($public_parts); ++$x) 
    $private[] = array_pop($all_parts);

  if (count($all_parts) > 0)
    $private[] = array_pop($all_parts);

  return join(".", array_reverse($private));
}

How do I clear my local working directory in Git?

You could create a commit which contains an empty working copy.

This is a generally safe, non-destructive approach because it does not involve the use of any brute-force reset mechanisms. First you hide all managed content with git checkout empty, then you are free to manually review and remove whatever unmanaged content remains.

## create a stand-alone, tagged, empty commit
true | git mktree | xargs git commit-tree | xargs git tag empty

## clear the working copy
git checkout empty

Your working copy should now be clear of any managed content. All that remains are unmanaged files and the .git folder itself.

To re-populate your working copy...

git checkout master ## or whatever branch you will be using

If you're a forward thinking individual, you might start your repository off on the right foot by basing everything on an initial empty commit...

git init
git commit --allow-empty --allow-empty-message -m ""
git tag empty
...

There are various uses for a tagged empty worktree. My favorite at the moment is to depopulate the root under a set of git worktree subfolders.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

An established connection was aborted by the software in your host machine

If you develop in multiple IDE's or other programs that connect to AVD you should try closing them too.

Netbeans also can cause conflicts with eclipse if you set it up for NBAndroid.

How do I remove all .pyc files from a project?

$ find . -name '*.pyc' -delete

This is faster than

$ find . -name "*.pyc" -exec rm -rf {} \;

Bind class toggle to window scroll event

Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:

.directive('changeClassOnScroll', function ($window) {
  return {
    restrict: 'A',
    scope: {
        offset: "@",
        scrollClass: "@"
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= parseInt(scope.offset)) {
                element.addClass(scope.scrollClass);
            } else {
                element.removeClass(scope.scrollClass);
            }
        });
    }
  };
})

So you can use it like this:

<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>

or

<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>

How do I output lists as a table in Jupyter notebook?

I recently used prettytable for rendering a nice ASCII table. It's similar to the postgres CLI output.

import pandas as pd
from prettytable import PrettyTable

data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])

def generate_ascii_table(df):
    x = PrettyTable()
    x.field_names = df.columns.tolist()
    for row in df.values:
        x.add_row(row)
    print(x)
    return x

generate_ascii_table(df)

Output:

+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
|  1  |  2  |   3   |
|  4  |  5  |   6   |
|  7  |  8  |   9   |
+-----+-----+-------+

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ G2        : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

Using C++ base class constructors?

No, that's not how it is done. Normal way to initialize the base class is in the initialization list :

class A
{
public: 
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};


void main()
{
    B b(10);
}

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to use sed to extract substring

sed 's/[^"]*"\([^"]*\).*/\1/'

does the job.

explanation of the part inside ' '

  • s - tells sed to substitute
  • / - start of regex string to search for
  • [^"]* - any character that is not ", any number of times. (matching parameter name=)
  • " - just a ".
  • ([^"]*) - anything inside () will be saved for reference to use later. The \ are there so the brackets are not considered as characters to search for. [^"]* means the same as above. (matching RemoteHost for example)
  • .* - any character, any number of times. (matching " access="readWrite"> /parameter)
  • / - end of the search regex, and start of the substitute string.
  • \1 - reference to that string we found in the brackets above.
  • / end of the substitute string.

basically s/search for this/replace with this/ but we're telling him to replace the whole line with just a piece of it we found earlier.

How to add conditional attribute in Angular 2?

Here, the paragraph is printed only 'isValid' is true / it contains any value

<p *ngIf="isValid ? true : false">Paragraph</p>

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

Checking if object is empty, works with ng-show but not from controller?

Check Empty object

$scope.isValid = function(value) {
    return !value
}

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

Laravel Soft Delete posts

In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task. In Model, inside the class just write 'use SoftDeletes'. Example

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

And In Controller, you can do deletion. Example

User::where('email', '[email protected]')->delete();

or

User::where('email', '[email protected]')->softDeletes();

Make sure that you must have 'deleted_at' column in the users Table.

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

Shell equality operators (=, ==, -eq)

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

Finally, I usually prefer to use the form if [ "$a" == "$b" ]

How to Execute a Python File in Notepad ++?

@Ramiz Uddin's answer definitely deserves more visibility :

  • Open Notepad++
  • On the menu go to: RunRun.. (F5)
  • Type in: cmd /K python "$(FULL_CURRENT_PATH)"

Iterating through a range of dates in Python

Why not try:

import datetime as dt

start_date = dt.datetime(2012, 12,1)
end_date = dt.datetime(2012, 12,5)

total_days = (end_date - start_date).days + 1 #inclusive 5 days

for day_number in range(total_days):
    current_date = (start_date + dt.timedelta(days = day_number)).date()
    print current_date

Recursively add the entire folder to a repository

SETUP

  • local repository at a local server
  • client is connected to the local server via LAN

UPDATE(Sep 2020): use foldername/\* instead of foldername/\\*:

git add foldername/\*

To make it to the server...

git commit -m "comments..."
git push remote_server_name master

Mostly, users will assign remote_server_name as origin...

git remote add remote_server_name username@git_server_ip:/path/to/git_repo

Unable to access JSON property with "-" dash

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax

This is the wrong way

json.first.second.third['comment']

and will will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 

Regexp Java for password validation

For anyone interested in minimum requirements for each type of character, I would suggest making the following extension over Tomalak's accepted answer:

^(?=(.*[0-9]){%d,})(?=(.*[a-z]){%d,})(?=(.*[A-Z]){%d,})(?=(.*[^0-9a-zA-Z]){%d,})(?=\S+$).{%d,}$

Notice that this is a formatting string and not the final regex pattern. Just substitute %d with the minimum required occurrences for: digits, lowercase, uppercase, non-digit/character, and entire password (respectively). Maximum occurrences are unlikely (unless you want a max of 0, effectively rejecting any such characters) but those could be easily added as well. Notice the extra grouping around each type so that the min/max constraints allow for non-consecutive matches. This worked wonders for a system where we could centrally configure how many of each type of character we required and then have the website as well as two different mobile platforms fetch that information in order to construct the regex pattern based on the above formatting string.

Is it possible to set async:false to $.getJSON call

In my case, Jay D is right. I have to add this before the call.

$.ajaxSetup({
    async: false
});

In my previous code, I have this:

var jsonData= (function() {
    var result;
    $.ajax({
        type:'GET',
        url:'data.txt',
        dataType:'json',
        async:false,
        success:function(data){
            result = data;
        }
    });
    return result;
})();
alert(JSON.stringify(jsonData));

It works find. Then I change to

var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

The alert is undefined.

If I add those three lines, the alert shows the data again.

$.ajaxSetup({
    async: false
});
var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

Extracting jar to specified directory

There is no such option available in jar command itself. Look into the documentation:

-C dir Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument. Its operation is intended to be similar to the -C option of the UNIX tar utility. For example: jar uf foo.jar -C classes bar.class changes to the classes directory and add the bar.class from that directory to foo.jar. The following command, jar uf foo.jar -C classes . -C bin xyz.class changes to the classes directory and adds to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then changes back to the original directory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files bar1 and bar2, then here's what the jar file contains using jar tf foo.jar: META-INF/

META-INF/MANIFEST.MF

bar1

bar2

xyz.class

Twitter Bootstrap dropdown menu

<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>