Programs & Examples On #Livedocx

HTML+CSS: How to force div contents to stay in one line?

Try this:

div {
    border: 1px solid black;
    width: 70px;
    overflow: hidden;
    white-space: nowrap;
}

Could not find or load main class

I had almost the same problem, but with the following variation:

  1. I've imported a ready-to-use maven project into Eclipse IDE from PC1 (project was working there perfectly) to another PC2
  2. when was trying to run the project on PC 2 got the same error "Could not find or load main class"
  3. I've checked PATH variable (it had many values in my case) and added JAVA_HOME variable (in my case it was JAVA_HOME = C:\Program Files\Java\jdk1.7.0_03) After restarting Ecplise it still didn't work
  4. I've tried to run simple HelloWorld.java on PC2 (in another project) - it worked
  5. So I've added HelloWorld class to the imported recently project, executed it there and - huh - my main class in that project started to run normally also.

That's quite odd behavour, I cannot completely understand it. Hope It'll help somebody. too.

Getting Textbox value in Javascript

The ID you are trying is an serverside.

That is going to render in the browser differently.

try to get the ID by watching the html in the Browser.

var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;

this may works.

Or do that ClientID method. That also works but ultimately the browser will get the same thing what i had written.

How to fix SSL certificate error when running Npm on Windows?

I happened to encounter this similar SSL problem a few days ago. The problem is your npm does not set root certificate for the certificate used by https://registry.npmjs.org.

Solutions:

  1. Use wget https://registry.npmjs.org/coffee-script --ca-certificate=./DigiCertHighAssuranceEVRootCA.crt to fix wget problem
  2. Use npm config set cafile /path/to/DigiCertHighAssuranceEVRootCA.crt to set root certificate for your npm program.

you can download root certificate from : https://www.digicert.com/CACerts/DigiCertHighAssuranceEVRootCA.crt

Notice: Different program may use different way of managing root certificate, so do not mix browser's with others.

Analysis:

let's fix your wget https://registry.npmjs.org/coffee-script problem first. your snippet says:


        ERROR: cannot verify registry.npmjs.org's certificate,
        issued by /C=US/ST=CA/L=Oakland/O=npm/OU=npm 
       Certificate Authority/CN=npmCA/[email protected]:
       Unable to locally verify the issuer's authority.

This means that your wget program cannot verify https://registry.npmjs.org's certificate. There are two reasons that may cause this problem:

  1. Your wget program does not have this domain's root certificate. The root certificate usually ship with system.
  2. The domain does not pack root certificate into his certificate.

So the solution is explicitly set root certificate for https://registry.npmjs.org. We can use openssl to make sure that the reason bellow is the problem.

Try openssl s_client -host registry.npmjs.org -port 443 on the command line and we will get this message (first several lines):


    CONNECTED(00000003)
    depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3
    verify error:num=20:unable to get local issuer certificate
    verify return:0
    ---
    Certificate chain
     0 s:/C=US/ST=California/L=San Francisco/O=Fastly, Inc./CN=a.sni.fastly.net
       i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3
     1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3
       i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
    ---

This line verify error:num=20:unable to get local issuer certificate makes sure that https://registry.npmjs.org does not pack root certificate. So we Google DigiCert High Assurance EV Root CA root Certificate.

In a Dockerfile, How to update PATH environment variable?

[I mentioned this in response to the selected answer, but it was suggested to make it more prominent as an answer of its own]

It should be noted that

ENV PATH="/opt/gtk/bin:${PATH}" 

may not be the same as

ENV PATH="/opt/gtk/bin:$PATH" 

The former, with curly brackets, might provide you with the host's PATH. The documentation doesn't suggest this would be the case, but I have observed that it is. This is simple to check just do RUN echo $PATH and compare it to RUN echo ${PATH}

Java finished with non-zero exit value 2 - Android Gradle

This issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in build.gradle, OR by adding multidex support.

So, If you have to keep libraries and methods, then you can enable multi dex support by declaring it in the gradle config.

defaultConfig {        
    // Enabling multidex support.
    multiDexEnabled true
}

You can read more about multidex support and developing apps with more than 65K methods here.

How do I close a single buffer (out of many) in Vim?

Rather than browse the ouput of the :ls command and delete (unload, wipe..) a buffer by specifying its number, I find that using file names is often more effective.

For instance, after I opened a couple of .txt file to refresh my memories of some fine point.. copy and paste a few lines of text to use as a template of sorts.. etc. I would type the following:

:bd txt <Tab>

Note that the matching string does not have to be at the start of the file name.

The above displays the list of file names that match 'txt' at the bottom of the screen and keeps the :bd command I initially typed untouched, ready to be completed.

Here's an example:

doc1.txt doc2.txt
:bd txt 

I could backspace over the 'txt' bit and type in the file name I wish to delete, but where this becomes really convenient is that I don't have to: if I hit the Tab key a second time, Vim automatically completes my command with the first match:

:bd doc1.txt

If I want to get rid of this particular buffer I just need to hit Enter.

And if the buffer I want to delete happens to be the second (third.. etc.) match, I only need to keep hitting the Tab key to make my :bd command cycle through the list of matches.

Naturally, this method can also be used to switch to a given buffer via such commands as :b.. :sb.. etc.

This approach is particularly useful when the 'hidden' Vim option is set, because the buffer list can quickly become quite large, covering several screens, and making it difficult to spot the particular buffer I am looking for.

To make the most of this feature, it's probably best to read the following Vim help file and tweak the behavior of Tab command-line completion accordingly so that it best suits your workflow:

:help wildmode

The behavior I described above results from the following setting, which I chose for consistency's sake in order to emulate bash completion:

:set wildmode=list:longest,full

As opposed to using buffer numbers, the merit of this approach is that I usually remember at least part of a given file name letting me target the buffer directly rather than having to first look up its number via the :ls command.

python capitalize first letter only

Only because no one else has mentioned it:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

However, this would also give

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

i.e. it doesn't just capitalize the first alphabetic character. But then .capitalize() has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob', so meh.

Extract text from a string

If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

Where should I put the log4j.properties file?

You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
     dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

Convert NSDate to NSString

there are a number of NSDate helpers on the web, I tend to use:

https://github.com/billymeltdown/nsdate-helper/

Readme extract below:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:

‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)

JAX-RS — How to return JSON and HTTP status code together?

If your WS-RS needs raise an error why not just use the WebApplicationException?

@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("{id}")
public MyEntity getFoo(@PathParam("id") long id,  @QueryParam("lang")long idLanguage) {

if (idLanguage== 0){
    // No URL parameter idLanguage was sent
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.entity("Missing idLanguage parameter on request");
    Response response = builder.build();
    throw new WebApplicationException(response);
    }
... //other stuff to return my entity
return myEntity;
}

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

How can I read comma separated values from a text file in Java?

To split your String by comma(,) use str.split(",") and for tab use str.split("\\t")

    try {
        BufferedReader in = new BufferedReader(
                               new FileReader("G:\\RoutePPAdvant2.txt"));
        String str;

        while ((str = in.readLine())!= null) {
            String[] ar=str.split(",");
            ...
        }
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error");
    }

Onclick on bootstrap button

Seem no solutions fix the problem:

$(".anima-area").on('click', function (e) {
            return false; //return true;
});
$(".anima-area").on('click', function (e) {
            e.preventDefault();
});
 $(".anima-area").click(function (r) {
           e.preventDefault();
});
$(".anima-area").click(function () {
           return false; //return true;
});

Bootstrap button always maintain th pressed status and block all .click code. If i remove .click function button comeback to work good.

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

How to pretty print XML from the command line?

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml

What is the inclusive range of float and double in Java?

Java's Primitive Data Types

boolean: 1-bit. May take on the values true and false only.

byte: 1 signed byte (two's complement). Covers values from -128 to 127.

short: 2 bytes, signed (two's complement), -32,768 to 32,767

int: 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.

long: 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float: 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

double: 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char: 2 bytes, unsigned, Unicode, 0 to 65,535

How to exclude records with certain values in sql select

One way:

SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
    SELECT * FROM StoreClients sc2 
    WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)

PHP: trying to create a new line with "\n"

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;

Android Preventing Double Click On A Button

If on click of the button, you're opening a new fragment, just add android:clickable="true" to the root view of the new fragment being opened.

Console app arguments, how arguments are passed to Main method

you can pass also by making function and then in this function you call main method and pass argument to main method

static int Main(string[] args)
    {


        foreach (string b in args)
            Console.WriteLine(b+"   ");

        Console.ReadKey();
        aa();
        return 0;

    }
    public static void aa()
    {
        string []aaa={"Adil"};

        Console.WriteLine(Main(aaa));
    }

Console.WriteLine and generic List

If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach.

First let's think about the clarity and brevity in the calling code.

You can do foreach in a number of ways:

  1. for loop
  2. foreach loop
  3. Collection.ForEach

Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.

list.ForEach(i => Console.Write("{0}\t", i));

So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.

According to Duston Campbell's performance measurements of foreach the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.

The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.

So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):

public static void WriteLine(this List<int> theList)
{
  foreach (int i in list)
  {
    Console.Write("{0}\t", t.ToString());
  }
  Console.WriteLine();
}

This code is going to used in many places so we should carry out the following improvements:

  • Instead of using foreach we should use the fastest way of iterating the collection which is a for loop with a cached count.
  • Currently only List can be passed as an argument. As a library function we can generalise it through a small amount of effort.
  • Using List limits us to just Lists, Using IList allows this code to work with Arrays too.
  • Since the extension method will be on an IList we need to change the name to make it clearer what we are writing to:

Here's how the code for the function would look:

public static void WriteToConsole<T>(this IList<T> collection)
{
    int count = collection.Count();
    for(int i = 0;  i < count; ++i)
    {
        Console.Write("{0}\t", collection[i].ToString(), delimiter);
    }
    Console.WriteLine();
}

We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:

public static void WriteToConsole<T>(this IList<T> collection)
{
    WriteToConsole<T>(collection, "\t");
}

public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
    int count = collection.Count();
    for(int i = 0;  i < count; ++i)
    {
         Console.Write("{0}{1}", collection[i].ToString(), delimiter);
    }
    Console.WriteLine();
}

So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleWritelineTest
{
    public static class Extensions
    {
        public static void WriteToConsole<T>(this IList<T> collection)
        {
            WriteToConsole<T>(collection, "\t");
        }

        public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
        {
            int count = collection.Count();
            for(int i = 0;  i < count; ++i)
            {
                Console.Write("{0}{1}", collection[i].ToString(), delimiter);
            }
            Console.WriteLine();
        }
    }

    internal class Foo
    {
        override public string ToString()
        {
            return "FooClass";
        }
    }

    internal class Program
    {

        static void Main(string[] args)
        {
            var myIntList = new List<int> {1, 2, 3, 4, 5};
            var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
            var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
            // Using the standard delimiter /t
            myIntList.WriteToConsole();
            myDoubleList.WriteToConsole();
            myDoubleArray.WriteToConsole();
            myFooList.WriteToConsole();
            // Using our own delimiter ~
            myIntList.WriteToConsole("~");
            Console.Read();
        }
    }
}

=======================================================

You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:

list.ForEach(i => Console.Write("{0}\t", i));

That is unless we make one more refinement to our extension methods and add FastForEach as below:

public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
    {
        int count = collection.Count();
        for (int i = 0; i < count; ++i)
        {
            actionToPerform(collection[i]);    
        }
        Console.WriteLine();
    }

This allows us to execute any arbitrary code against every element in the collection using the fastest possible iteration method.

We can even change the WriteToConsole function to use FastForEach

public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
     collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}

So now the entire source code, including an example usage of FastForEach is:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleWritelineTest
{
    public static class Extensions
    {
        public static void WriteToConsole<T>(this IList<T> collection)
        {
            WriteToConsole<T>(collection, "\t");
        }

        public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
        {
             collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
        }

        public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
        {
            int count = collection.Count();
            for (int i = 0; i < count; ++i)
            {
                actionToPerform(collection[i]);    
            }
            Console.WriteLine();
        }
    }

    internal class Foo
    {
        override public string ToString()
        {
            return "FooClass";
        }
    }

    internal class Program
    {

        static void Main(string[] args)
        {
            var myIntList = new List<int> {1, 2, 3, 4, 5};
            var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
            var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};

            // Using the standard delimiter /t
            myIntList.WriteToConsole();
            myDoubleList.WriteToConsole();
            myDoubleArray.WriteToConsole();
            myFooList.WriteToConsole();

            // Using our own delimiter ~
            myIntList.WriteToConsole("~");

            // What if we want to write them to separate lines?
            myIntList.FastForEach(item => Console.WriteLine(item.ToString()));
            Console.Read();
        }
    }
}

Simplest/cleanest way to implement a singleton in JavaScript

This should work:

function Klass() {
   var instance = this;
   Klass = function () { return instance; }
}

Removing all empty elements from a hash / YAML?

I know this thread is a bit old but I came up with a better solution which supports Multidimensional hashes. It uses delete_if? except its multidimensional and cleans out anything with a an empty value by default and if a block is passed it is passed down through it's children.

# Hash cleaner
class Hash
    def clean!
        self.delete_if do |key, val|
            if block_given?
                yield(key,val)
            else
                # Prepeare the tests
                test1 = val.nil?
                test2 = val === 0
                test3 = val === false
                test4 = val.empty? if val.respond_to?('empty?')
                test5 = val.strip.empty? if val.is_a?(String) && val.respond_to?('empty?')

                # Were any of the tests true
                test1 || test2 || test3 || test4 || test5
            end
        end

        self.each do |key, val|
            if self[key].is_a?(Hash) && self[key].respond_to?('clean!')
                if block_given?
                    self[key] = self[key].clean!(&Proc.new)
                else
                    self[key] = self[key].clean!
                end
            end
        end

        return self
    end
end

How to get the IP address of the docker host from inside a docker container

Try this:

docker run --rm -i --net=host alpine ifconfig

Why not use Double or Float to represent currency?

From Bloch, J., Effective Java, 2nd ed, Item 48:

The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.

For example, suppose you have $1.03 and you spend 42c. How much money do you have left?

System.out.println(1.03 - .42);

prints out 0.6100000000000001.

The right way to solve this problem is to use BigDecimal, int or long for monetary calculations.

Though BigDecimal has some caveats (please see currently accepted answer).

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

These strange errors occured recently on my OSX machine.

I could help myself the quick & dirty way by running:

sudo chmod -R 777 /usr/local/lib/node_modules/

Something seemed to have messed up the access rights of all global node modules.

Passing variables in remote ssh command

It is also possible to pass environment variables explicitly through ssh. It does require some server-side set-up through, so this this not a universal answer.

In my case, I wanted to pass a backup repository encryption key to a command on the backup storage server without having that key stored there, but note that any environment variable is visible in ps! The solution of passing the key on stdin would work as well, but I found it too cumbersome. In any case, here's how to pass an environment variable through ssh:

On the server, edit the sshd_config file, typically /etc/ssh/sshd_config and add an AcceptEnv directive matching the variables you want to pass. See man sshd_config. In my case, I want to pass variables to borg backup so I chose:

AcceptEnv BORG_*

Now, on the client use the -o SendEnv option to send environment variables. The following command line sets the environment variable BORG_SECRET and then flags it to be sent to the client machine (called backup). It then runs printenv there and filters the output for BORG variables:

$ BORG_SECRET=magic-happens ssh -o SendEnv=BORG_SECRET backup printenv | egrep BORG
BORG_SECRET=magic-happens

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I found this question because I was having issues with the OPTIONS request most browsers send. My app was routing the OPTIONS requests and using my IoC to construct lots of objects and some were throwing exceptions on this odd request type for various reasons.

Basically put in an ignore route for all OPTIONS requests if they are causing you problems:

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

More info: Stop Web API processing OPTIONS requests

How can I create download link in HTML?

To link to the file, do the same as any other page link:

<a href="...">link text</a>

To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:

AddType application/octet-stream EXTENSION

How do I define and use an ENUM in Objective-C?

I recommend using NS_OPTIONS or NS_ENUM. You can read more about it here: http://nshipster.com/ns_enum-ns_options/

Here's an example from my own code using NS_OPTIONS, I have an utility that sets a sublayer (CALayer) on a UIView's layer to create a border.

The h. file:

typedef NS_OPTIONS(NSUInteger, BSTCMBorder) {
    BSTCMBOrderNoBorder     = 0,
    BSTCMBorderTop          = 1 << 0,
    BSTCMBorderRight        = 1 << 1,
    BSTCMBorderBottom       = 1 << 2,
    BSTCMBOrderLeft         = 1 << 3
};

@interface BSTCMBorderUtility : NSObject

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color;

@end

The .m file:

@implementation BSTCMBorderUtility

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color
{

    // Make a left border on the view
    if (border & BSTCMBOrderLeft) {

    }

    // Make a right border on the view
    if (border & BSTCMBorderRight) {

    }

    // Etc

}

@end

How could I use requests in asyncio?

To use requests (or any other blocking libraries) with asyncio, you can use BaseEventLoop.run_in_executor to run a function in another thread and yield from it to get the result. For example:

import asyncio
import requests

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = yield from future1
    response2 = yield from future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

This will get both responses in parallel.

With python 3.5 you can use the new await/async syntax:

import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

See PEP0492 for more.

Getting Error "Form submission canceled because the form is not connected"

if you are seeing this error in React JS when you try to submit the form by pressing enter, make sure all your buttons in the form that do not submit the form have a type="button".

If you have only one button with type="submit" pressing Enter will submit the form as expected.

References:
https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/ https://github.com/facebook/react/issues/2093

What characters are forbidden in Windows and Linux directory names?

For Windows you can check it using PowerShell

$PathInvalidChars = [System.IO.Path]::GetInvalidPathChars() #36 chars

To display UTF-8 codes you can convert

$enc = [system.Text.Encoding]::UTF8
$PathInvalidChars | foreach { $enc.GetBytes($_) }

$FileNameInvalidChars = [System.IO.Path]::GetInvalidFileNameChars() #41 chars

$FileOnlyInvalidChars = @(':', '*', '?', '\', '/') #5 chars - as a difference

Redraw datatables after using ajax to refresh the table content?

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.

How to check if an alert exists using WebDriver?

I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
    System.out.println("alert was not present");
else
    System.out.println("alert was present");

Is there a way to detach matplotlib plots so that the computation can continue?

While not directly answering OPs request, Im posting this workaround since it may help somebody in this situation:

  • Im creating an .exe with pyinstaller since I cannot install python where I need to generate the plots, so I need the python script to generate the plot, save it as .png, close it and continue with the next, implemented as several plots in a loop or using a function.

for this Im using:

import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches='tight', dpi=250) 
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode
plt.show(block=False) 
#and the following closes the plot while next iteration will generate new instance.
plt.close() 

Where "var" identifies the plot in the loop so it wont be overwritten.

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

How to fix corrupt HDFS FIles

the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html

su - <$hdfs_user>

bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files 

-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ;  hadoop fs -setrep 3 $hdfsfile; done

How to set viewport meta for iPhone that handles rotation properly?

For anybody still interested:

http://wiki.phonegap.com/w/page/16494815/Preventing-Scrolling-on-iPhone-Phonegap-Applications

From the page:

<meta name="viewport" content="user-scalable=no,width=device-width" />

This instructs Safari to prevent the user from zooming into the page with the "pinch" gesture and fixes the width of the view port to the width of the screen, which ever orientation the iPhone is in.

What is the list of supported languages/locales on Android?

Following jrub post on May 4 '2015, I'm adding updated locale list. Executed on a Nexus 6P with Android 7.0 Nougat and English US locale.

af_ [Afrikaans]
af_NA [Afrikaans (Namibia)]
af_ZA [Afrikaans (South Africa)]
agq_ [Aghem]
agq_CM [Aghem (Cameroon)]
ak_ [Akan]
ak_GH [Akan (Ghana)]
am_ [Amharic]
am_ET [Amharic (Ethiopia)]
ar_ [Arabic]
ar_001 [Arabic (World)]
ar_AE [Arabic (United Arab Emirates)]
ar_BH [Arabic (Bahrain)]
ar_DJ [Arabic (Djibouti)]
ar_DZ [Arabic (Algeria)]
ar_EG [Arabic (Egypt)]
ar_EH [Arabic (Western Sahara)]
ar_ER [Arabic (Eritrea)]
ar_IL [Arabic (Israel)]
ar_IQ [Arabic (Iraq)]
ar_JO [Arabic (Jordan)]
ar_KM [Arabic (Comoros)]
ar_KW [Arabic (Kuwait)]
ar_LB [Arabic (Lebanon)]
ar_LY [Arabic (Libya)]
ar_MA [Arabic (Morocco)]
ar_MR [Arabic (Mauritania)]
ar_OM [Arabic (Oman)]
ar_PS [Arabic (Palestine)]
ar_QA [Arabic (Qatar)]
ar_SA [Arabic (Saudi Arabia)]
ar_SD [Arabic (Sudan)]
ar_SO [Arabic (Somalia)]
ar_SS [Arabic (South Sudan)]
ar_SY [Arabic (Syria)]
ar_TD [Arabic (Chad)]
ar_TN [Arabic (Tunisia)]
ar_YE [Arabic (Yemen)]
as_ [Assamese]
as_IN [Assamese (India)]
asa_ [Asu]
asa_TZ [Asu (Tanzania)]
az_ [Azerbaijani (Cyrillic)]
az_ [Azerbaijani (Latin)]
az_ [Azerbaijani]
az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
az_AZ [Azerbaijani (Latin,Azerbaijan)]
bas_ [Basaa]
bas_CM [Basaa (Cameroon)]
be_ [Belarusian]
be_BY [Belarusian (Belarus)]
bem_ [Bemba]
bem_ZM [Bemba (Zambia)]
bez_ [Bena]
bez_TZ [Bena (Tanzania)]
bg_ [Bulgarian]
bg_BG [Bulgarian (Bulgaria)]
bm_ [Bambara]
bm_ML [Bambara (Mali)]
bn_ [Bengali]
bn_BD [Bengali (Bangladesh)]
bn_IN [Bengali (India)]
bo_ [Tibetan]
bo_CN [Tibetan (China)]
bo_IN [Tibetan (India)]
br_ [Breton]
br_FR [Breton (France)]
brx_ [Bodo]
brx_IN [Bodo (India)]
bs_ [Bosnian (Cyrillic)]
bs_ [Bosnian (Latin)]
bs_ [Bosnian]
bs_BA [Bosnian (Cyrillic,Bosnia & Herzegovina)]
bs_BA [Bosnian (Latin,Bosnia & Herzegovina)]
ca_ [Catalan]
ca_AD [Catalan (Andorra)]
ca_ES [Catalan (Spain)]
ca_FR [Catalan (France)]
ca_IT [Catalan (Italy)]
ce_ [Chechen]
ce_RU [Chechen (Russia)]
cgg_ [Chiga]
cgg_UG [Chiga (Uganda)]
chr_ [Cherokee]
chr_US [Cherokee (United States)]
cs_ [Czech]
cs_CZ [Czech (Czech Republic)]
cy_ [Welsh]
cy_GB [Welsh (United Kingdom)]
da_ [Danish]
da_DK [Danish (Denmark)]
da_GL [Danish (Greenland)]
dav_ [Taita]
dav_KE [Taita (Kenya)]
de_ [German]
de_AT [German (Austria)]
de_BE [German (Belgium)]
de_CH [German (Switzerland)]
de_DE [German (Germany)]
de_LI [German (Liechtenstein)]
de_LU [German (Luxembourg)]
dje_ [Zarma]
dje_NE [Zarma (Niger)]
dsb_ [Lower Sorbian]
dsb_DE [Lower Sorbian (Germany)]
dua_ [Duala]
dua_CM [Duala (Cameroon)]
dyo_ [Jola-Fonyi]
dyo_SN [Jola-Fonyi (Senegal)]
dz_ [Dzongkha]
dz_BT [Dzongkha (Bhutan)]
ebu_ [Embu]
ebu_KE [Embu (Kenya)]
ee_ [Ewe]
ee_GH [Ewe (Ghana)]
ee_TG [Ewe (Togo)]
el_ [Greek]
el_CY [Greek (Cyprus)]
el_GR [Greek (Greece)]
en_ [English]
en_001 [English (World)]
en_150 [English (Europe)]
en_AG [English (Antigua & Barbuda)]
en_AI [English (Anguilla)]
en_AS [English (American Samoa)]
en_AT [English (Austria)]
en_AU [English (Australia)]
en_BB [English (Barbados)]
en_BE [English (Belgium)]
en_BI [English (Burundi)]
en_BM [English (Bermuda)]
en_BS [English (Bahamas)]
en_BW [English (Botswana)]
en_BZ [English (Belize)]
en_CA [English (Canada)]
en_CC [English (Cocos (Keeling) Islands)]
en_CH [English (Switzerland)]
en_CK [English (Cook Islands)]
en_CM [English (Cameroon)]
en_CX [English (Christmas Island)]
en_CY [English (Cyprus)]
en_DE [English (Germany)]
en_DG [English (Diego Garcia)]
en_DK [English (Denmark)]
en_DM [English (Dominica)]
en_ER [English (Eritrea)]
en_FI [English (Finland)]
en_FJ [English (Fiji)]
en_FK [English (Falkland Islands (Islas Malvinas))]
en_FM [English (Micronesia)]
en_GB [English (United Kingdom)]
en_GD [English (Grenada)]
en_GG [English (Guernsey)]
en_GH [English (Ghana)]
en_GI [English (Gibraltar)]
en_GM [English (Gambia)]
en_GU [English (Guam)]
en_GY [English (Guyana)]
en_HK [English (Hong Kong)]
en_IE [English (Ireland)]
en_IL [English (Israel)]
en_IM [English (Isle of Man)]
en_IN [English (India)]
en_IO [English (British Indian Ocean Territory)]
en_JE [English (Jersey)]
en_JM [English (Jamaica)]
en_KE [English (Kenya)]
en_KI [English (Kiribati)]
en_KN [English (St. Kitts & Nevis)]
en_KY [English (Cayman Islands)]
en_LC [English (St. Lucia)]
en_LR [English (Liberia)]
en_LS [English (Lesotho)]
en_MG [English (Madagascar)]
en_MH [English (Marshall Islands)]
en_MO [English (Macau)]
en_MP [English (Northern Mariana Islands)]
en_MS [English (Montserrat)]
en_MT [English (Malta)]
en_MU [English (Mauritius)]
en_MW [English (Malawi)]
en_MY [English (Malaysia)]
en_NA [English (Namibia)]
en_NF [English (Norfolk Island)]
en_NG [English (Nigeria)]
en_NL [English (Netherlands)]
en_NR [English (Nauru)]
en_NU [English (Niue)]
en_NZ [English (New Zealand)]
en_PG [English (Papua New Guinea)]
en_PH [English (Philippines)]
en_PK [English (Pakistan)]
en_PN [English (Pitcairn Islands)]
en_PR [English (Puerto Rico)]
en_PW [English (Palau)]
en_RW [English (Rwanda)]
en_SB [English (Solomon Islands)]
en_SC [English (Seychelles)]
en_SD [English (Sudan)]
en_SE [English (Sweden)]
en_SG [English (Singapore)]
en_SH [English (St. Helena)]
en_SI [English (Slovenia)]
en_SL [English (Sierra Leone)]
en_SS [English (South Sudan)]
en_SX [English (Sint Maarten)]
en_SZ [English (Swaziland)]
en_TC [English (Turks & Caicos Islands)]
en_TK [English (Tokelau)]
en_TO [English (Tonga)]
en_TT [English (Trinidad & Tobago)]
en_TV [English (Tuvalu)]
en_TZ [English (Tanzania)]
en_UG [English (Uganda)]
en_UM [English (U.S. Outlying Islands)]
en_US [English (United States)]
en_US [English (United States,Computer)]
en_VC [English (St. Vincent & Grenadines)]
en_VG [English (British Virgin Islands)]
en_VI [English (U.S. Virgin Islands)]
en_VU [English (Vanuatu)]
en_WS [English (Samoa)]
en_ZA [English (South Africa)]
en_ZM [English (Zambia)]
en_ZW [English (Zimbabwe)]
eo_ [Esperanto]
es_ [Spanish]
es_419 [Spanish (Latin America)]
es_AR [Spanish (Argentina)]
es_BO [Spanish (Bolivia)]
es_CL [Spanish (Chile)]
es_CO [Spanish (Colombia)]
es_CR [Spanish (Costa Rica)]
es_CU [Spanish (Cuba)]
es_DO [Spanish (Dominican Republic)]
es_EA [Spanish (Ceuta & Melilla)]
es_EC [Spanish (Ecuador)]
es_ES [Spanish (Spain)]
es_GQ [Spanish (Equatorial Guinea)]
es_GT [Spanish (Guatemala)]
es_HN [Spanish (Honduras)]
es_IC [Spanish (Canary Islands)]
es_MX [Spanish (Mexico)]
es_NI [Spanish (Nicaragua)]
es_PA [Spanish (Panama)]
es_PE [Spanish (Peru)]
es_PH [Spanish (Philippines)]
es_PR [Spanish (Puerto Rico)]
es_PY [Spanish (Paraguay)]
es_SV [Spanish (El Salvador)]
es_US [Spanish (United States)]
es_UY [Spanish (Uruguay)]
es_VE [Spanish (Venezuela)]
et_ [Estonian]
et_EE [Estonian (Estonia)]
eu_ [Basque]
eu_ES [Basque (Spain)]
ewo_ [Ewondo]
ewo_CM [Ewondo (Cameroon)]
fa_ [Persian]
fa_AF [Persian (Afghanistan)]
fa_IR [Persian (Iran)]
ff_ [Fulah]
ff_CM [Fulah (Cameroon)]
ff_GN [Fulah (Guinea)]
ff_MR [Fulah (Mauritania)]
ff_SN [Fulah (Senegal)]
fi_ [Finnish]
fi_FI [Finnish (Finland)]
fil_ [Filipino]
fil_PH [Filipino (Philippines)]
fo_ [Faroese]
fo_DK [Faroese (Denmark)]
fo_FO [Faroese (Faroe Islands)]
fr_ [French]
fr_BE [French (Belgium)]
fr_BF [French (Burkina Faso)]
fr_BI [French (Burundi)]
fr_BJ [French (Benin)]
fr_BL [French (St. Barthélemy)]
fr_CA [French (Canada)]
fr_CD [French (Congo (DRC))]
fr_CF [French (Central African Republic)]
fr_CG [French (Congo (Republic))]
fr_CH [French (Switzerland)]
fr_CI [French (Côte d’Ivoire)]
fr_CM [French (Cameroon)]
fr_DJ [French (Djibouti)]
fr_DZ [French (Algeria)]
fr_FR [French (France)]
fr_GA [French (Gabon)]
fr_GF [French (French Guiana)]
fr_GN [French (Guinea)]
fr_GP [French (Guadeloupe)]
fr_GQ [French (Equatorial Guinea)]
fr_HT [French (Haiti)]
fr_KM [French (Comoros)]
fr_LU [French (Luxembourg)]
fr_MA [French (Morocco)]
fr_MC [French (Monaco)]
fr_MF [French (St. Martin)]
fr_MG [French (Madagascar)]
fr_ML [French (Mali)]
fr_MQ [French (Martinique)]
fr_MR [French (Mauritania)]
fr_MU [French (Mauritius)]
fr_NC [French (New Caledonia)]
fr_NE [French (Niger)]
fr_PF [French (French Polynesia)]
fr_PM [French (St. Pierre & Miquelon)]
fr_RE [French (Réunion)]
fr_RW [French (Rwanda)]
fr_SC [French (Seychelles)]
fr_SN [French (Senegal)]
fr_SY [French (Syria)]
fr_TD [French (Chad)]
fr_TG [French (Togo)]
fr_TN [French (Tunisia)]
fr_VU [French (Vanuatu)]
fr_WF [French (Wallis & Futuna)]
fr_YT [French (Mayotte)]
fur_ [Friulian]
fur_IT [Friulian (Italy)]
fy_ [Western Frisian]
fy_NL [Western Frisian (Netherlands)]
ga_ [Irish]
ga_IE [Irish (Ireland)]
gd_ [Scottish Gaelic]
gd_GB [Scottish Gaelic (United Kingdom)]
gl_ [Galician]
gl_ES [Galician (Spain)]
gsw_ [Swiss German]
gsw_CH [Swiss German (Switzerland)]
gsw_FR [Swiss German (France)]
gsw_LI [Swiss German (Liechtenstein)]
gu_ [Gujarati]
gu_IN [Gujarati (India)]
guz_ [Gusii]
guz_KE [Gusii (Kenya)]
gv_ [Manx]
gv_IM [Manx (Isle of Man)]
ha_ [Hausa]
ha_GH [Hausa (Ghana)]
ha_NE [Hausa (Niger)]
ha_NG [Hausa (Nigeria)]
haw_ [Hawaiian]
haw_US [Hawaiian (United States)]
hi_ [Hindi]
hi_IN [Hindi (India)]
hr_ [Croatian]
hr_BA [Croatian (Bosnia & Herzegovina)]
hr_HR [Croatian (Croatia)]
hsb_ [Upper Sorbian]
hsb_DE [Upper Sorbian (Germany)]
hu_ [Hungarian]
hu_HU [Hungarian (Hungary)]
hy_ [Armenian]
hy_AM [Armenian (Armenia)]
ig_ [Igbo]
ig_NG [Igbo (Nigeria)]
ii_ [Sichuan Yi]
ii_CN [Sichuan Yi (China)]
in_ [Indonesian]
in_ID [Indonesian (Indonesia)]
is_ [Icelandic]
is_IS [Icelandic (Iceland)]
it_ [Italian]
it_CH [Italian (Switzerland)]
it_IT [Italian (Italy)]
it_SM [Italian (San Marino)]
iw_ [Hebrew]
iw_IL [Hebrew (Israel)]
ja_ [Japanese]
ja_JP [Japanese (Japan)]
jgo_ [Ngomba]
jgo_CM [Ngomba (Cameroon)]
ji_ [Yiddish]
ji_001 [Yiddish (World)]
jmc_ [Machame]
jmc_TZ [Machame (Tanzania)]
ka_ [Georgian]
ka_GE [Georgian (Georgia)]
kab_ [Kabyle]
kab_DZ [Kabyle (Algeria)]
kam_ [Kamba]
kam_KE [Kamba (Kenya)]
kde_ [Makonde]
kde_TZ [Makonde (Tanzania)]
kea_ [Kabuverdianu]
kea_CV [Kabuverdianu (Cape Verde)]
khq_ [Koyra Chiini]
khq_ML [Koyra Chiini (Mali)]
ki_ [Kikuyu]
ki_KE [Kikuyu (Kenya)]
kk_ [Kazakh]
kk_KZ [Kazakh (Kazakhstan)]
kkj_ [Kako]
kkj_CM [Kako (Cameroon)]
kl_ [Kalaallisut]
kl_GL [Kalaallisut (Greenland)]
kln_ [Kalenjin]
kln_KE [Kalenjin (Kenya)]
km_ [Khmer]
km_KH [Khmer (Cambodia)]
kn_ [Kannada]
kn_IN [Kannada (India)]
ko_ [Korean]
ko_KP [Korean (North Korea)]
ko_KR [Korean (South Korea)]
kok_ [Konkani]
kok_IN [Konkani (India)]
ks_ [Kashmiri]
ks_IN [Kashmiri (India)]
ksb_ [Shambala]
ksb_TZ [Shambala (Tanzania)]
ksf_ [Bafia]
ksf_CM [Bafia (Cameroon)]
ksh_ [Colognian]
ksh_DE [Colognian (Germany)]
kw_ [Cornish]
kw_GB [Cornish (United Kingdom)]
ky_ [Kyrgyz]
ky_KG [Kyrgyz (Kyrgyzstan)]
lag_ [Langi]
lag_TZ [Langi (Tanzania)]
lb_ [Luxembourgish]
lb_LU [Luxembourgish (Luxembourg)]
lg_ [Ganda]
lg_UG [Ganda (Uganda)]
lkt_ [Lakota]
lkt_US [Lakota (United States)]
ln_ [Lingala]
ln_AO [Lingala (Angola)]
ln_CD [Lingala (Congo (DRC))]
ln_CF [Lingala (Central African Republic)]
ln_CG [Lingala (Congo (Republic))]
lo_ [Lao]
lo_LA [Lao (Laos)]
lrc_ [Northern Luri]
lrc_IQ [Northern Luri (Iraq)]
lrc_IR [Northern Luri (Iran)]
lt_ [Lithuanian]
lt_LT [Lithuanian (Lithuania)]
lu_ [Luba-Katanga]
lu_CD [Luba-Katanga (Congo (DRC))]
luo_ [Luo]
luo_KE [Luo (Kenya)]
luy_ [Luyia]
luy_KE [Luyia (Kenya)]
lv_ [Latvian]
lv_LV [Latvian (Latvia)]
mas_ [Masai]
mas_KE [Masai (Kenya)]
mas_TZ [Masai (Tanzania)]
mer_ [Meru]
mer_KE [Meru (Kenya)]
mfe_ [Morisyen]
mfe_MU [Morisyen (Mauritius)]
mg_ [Malagasy]
mg_MG [Malagasy (Madagascar)]
mgh_ [Makhuwa-Meetto]
mgh_MZ [Makhuwa-Meetto (Mozambique)]
mgo_ [Meta']
mgo_CM [Meta' (Cameroon)]
mk_ [Macedonian]
mk_MK [Macedonian (Macedonia (FYROM))]
ml_ [Malayalam]
ml_IN [Malayalam (India)]
mn_ [Mongolian]
mn_MN [Mongolian (Mongolia)]
mr_ [Marathi]
mr_IN [Marathi (India)]
ms_ [Malay]
ms_BN [Malay (Brunei)]
ms_MY [Malay (Malaysia)]
ms_SG [Malay (Singapore)]
mt_ [Maltese]
mt_MT [Maltese (Malta)]
mua_ [Mundang]
mua_CM [Mundang (Cameroon)]
my_ [Burmese]
my_MM [Burmese (Myanmar (Burma))]
mzn_ [Mazanderani]
mzn_IR [Mazanderani (Iran)]
naq_ [Nama]
naq_NA [Nama (Namibia)]
nb_ [Norwegian Bokmål]
nb_NO [Norwegian Bokmål (Norway)]
nb_SJ [Norwegian Bokmål (Svalbard & Jan Mayen)]
nd_ [North Ndebele]
nd_ZW [North Ndebele (Zimbabwe)]
ne_ [Nepali]
ne_IN [Nepali (India)]
ne_NP [Nepali (Nepal)]
nl_ [Dutch]
nl_AW [Dutch (Aruba)]
nl_BE [Dutch (Belgium)]
nl_BQ [Dutch (Caribbean Netherlands)]
nl_CW [Dutch (Curaçao)]
nl_NL [Dutch (Netherlands)]
nl_SR [Dutch (Suriname)]
nl_SX [Dutch (Sint Maarten)]
nmg_ [Kwasio]
nmg_CM [Kwasio (Cameroon)]
nn_ [Norwegian Nynorsk]
nn_NO [Norwegian Nynorsk (Norway)]
nnh_ [Ngiemboon]
nnh_CM [Ngiemboon (Cameroon)]
nus_ [Nuer]
nus_SS [Nuer (South Sudan)]
nyn_ [Nyankole]
nyn_UG [Nyankole (Uganda)]
om_ [Oromo]
om_ET [Oromo (Ethiopia)]
om_KE [Oromo (Kenya)]
or_ [Oriya]
or_IN [Oriya (India)]
os_ [Ossetic]
os_GE [Ossetic (Georgia)]
os_RU [Ossetic (Russia)]
pa_ [Punjabi (Arabic)]
pa_ [Punjabi (Gurmukhi)]
pa_ [Punjabi]
pa_IN [Punjabi (Gurmukhi,India)]
pa_PK [Punjabi (Arabic,Pakistan)]
pl_ [Polish]
pl_PL [Polish (Poland)]
ps_ [Pashto]
ps_AF [Pashto (Afghanistan)]
pt_ [Portuguese]
pt_AO [Portuguese (Angola)]
pt_BR [Portuguese (Brazil)]
pt_CV [Portuguese (Cape Verde)]
pt_GW [Portuguese (Guinea-Bissau)]
pt_MO [Portuguese (Macau)]
pt_MZ [Portuguese (Mozambique)]
pt_PT [Portuguese (Portugal)]
pt_ST [Portuguese (São Tomé & Príncipe)]
pt_TL [Portuguese (Timor-Leste)]
qu_ [Quechua]
qu_BO [Quechua (Bolivia)]
qu_EC [Quechua (Ecuador)]
qu_PE [Quechua (Peru)]
rm_ [Romansh]
rm_CH [Romansh (Switzerland)]
rn_ [Rundi]
rn_BI [Rundi (Burundi)]
ro_ [Romanian]
ro_MD [Romanian (Moldova)]
ro_RO [Romanian (Romania)]
rof_ [Rombo]
rof_TZ [Rombo (Tanzania)]
ru_ [Russian]
ru_BY [Russian (Belarus)]
ru_KG [Russian (Kyrgyzstan)]
ru_KZ [Russian (Kazakhstan)]
ru_MD [Russian (Moldova)]
ru_RU [Russian (Russia)]
ru_UA [Russian (Ukraine)]
rw_ [Kinyarwanda]
rw_RW [Kinyarwanda (Rwanda)]
rwk_ [Rwa]
rwk_TZ [Rwa (Tanzania)]
sah_ [Sakha]
sah_RU [Sakha (Russia)]
saq_ [Samburu]
saq_KE [Samburu (Kenya)]
sbp_ [Sangu]
sbp_TZ [Sangu (Tanzania)]
se_ [Northern Sami]
se_FI [Northern Sami (Finland)]
se_NO [Northern Sami (Norway)]
se_SE [Northern Sami (Sweden)]
seh_ [Sena]
seh_MZ [Sena (Mozambique)]
ses_ [Koyraboro Senni]
ses_ML [Koyraboro Senni (Mali)]
sg_ [Sango]
sg_CF [Sango (Central African Republic)]
shi_ [Tachelhit (Latin)]
shi_ [Tachelhit (Tifinagh)]
shi_ [Tachelhit]
shi_MA [Tachelhit (Latin,Morocco)]
shi_MA [Tachelhit (Tifinagh,Morocco)]
si_ [Sinhala]
si_LK [Sinhala (Sri Lanka)]
sk_ [Slovak]
sk_SK [Slovak (Slovakia)]
sl_ [Slovenian]
sl_SI [Slovenian (Slovenia)]
smn_ [Inari Sami]
smn_FI [Inari Sami (Finland)]
sn_ [Shona]
sn_ZW [Shona (Zimbabwe)]
so_ [Somali]
so_DJ [Somali (Djibouti)]
so_ET [Somali (Ethiopia)]
so_KE [Somali (Kenya)]
so_SO [Somali (Somalia)]
sq_ [Albanian]
sq_AL [Albanian (Albania)]
sq_MK [Albanian (Macedonia (FYROM))]
sq_XK [Albanian (Kosovo)]
sr_ [Serbian (Cyrillic)]
sr_ [Serbian (Latin)]
sr_ [Serbian]
sr_BA [Serbian (Cyrillic,Bosnia & Herzegovina)]
sr_BA [Serbian (Latin,Bosnia & Herzegovina)]
sr_ME [Serbian (Cyrillic,Montenegro)]
sr_ME [Serbian (Latin,Montenegro)]
sr_RS [Serbian (Cyrillic,Serbia)]
sr_RS [Serbian (Latin,Serbia)]
sr_XK [Serbian (Cyrillic,Kosovo)]
sr_XK [Serbian (Latin,Kosovo)]
sv_ [Swedish]
sv_AX [Swedish (Åland Islands)]
sv_FI [Swedish (Finland)]
sv_SE [Swedish (Sweden)]
sw_ [Swahili]
sw_CD [Swahili (Congo (DRC))]
sw_KE [Swahili (Kenya)]
sw_TZ [Swahili (Tanzania)]
sw_UG [Swahili (Uganda)]
ta_ [Tamil]
ta_IN [Tamil (India)]
ta_LK [Tamil (Sri Lanka)]
ta_MY [Tamil (Malaysia)]
ta_SG [Tamil (Singapore)]
te_ [Telugu]
te_IN [Telugu (India)]
teo_ [Teso]
teo_KE [Teso (Kenya)]
teo_UG [Teso (Uganda)]
th_ [Thai]
th_TH [Thai (Thailand)]
ti_ [Tigrinya]
ti_ER [Tigrinya (Eritrea)]
ti_ET [Tigrinya (Ethiopia)]
to_ [Tongan]
to_TO [Tongan (Tonga)]
tr_ [Turkish]
tr_CY [Turkish (Cyprus)]
tr_TR [Turkish (Turkey)]
twq_ [Tasawaq]
twq_NE [Tasawaq (Niger)]
tzm_ [Central Atlas Tamazight]
tzm_MA [Central Atlas Tamazight (Morocco)]
ug_ [Uyghur]
ug_CN [Uyghur (China)]
uk_ [Ukrainian]
uk_UA [Ukrainian (Ukraine)]
ur_ [Urdu]
ur_IN [Urdu (India)]
ur_PK [Urdu (Pakistan)]
uz_ [Uzbek (Arabic)]
uz_ [Uzbek (Cyrillic)]
uz_ [Uzbek (Latin)]
uz_ [Uzbek]
uz_AF [Uzbek (Arabic,Afghanistan)]
uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
uz_UZ [Uzbek (Latin,Uzbekistan)]
vai_ [Vai (Latin)]
vai_ [Vai (Vai)]
vai_ [Vai]
vai_LR [Vai (Latin,Liberia)]
vai_LR [Vai (Vai,Liberia)]
vi_ [Vietnamese]
vi_VN [Vietnamese (Vietnam)]
vun_ [Vunjo]
vun_TZ [Vunjo (Tanzania)]
wae_ [Walser]
wae_CH [Walser (Switzerland)]
xog_ [Soga]
xog_UG [Soga (Uganda)]
yav_ [Yangben]
yav_CM [Yangben (Cameroon)]
yo_ [Yoruba]
yo_BJ [Yoruba (Benin)]
yo_NG [Yoruba (Nigeria)]
zgh_ [Standard Moroccan Tamazight]
zgh_MA [Standard Moroccan Tamazight (Morocco)]
zh_ [Chinese (Simplified Han)]
zh_ [Chinese (Traditional Han)]
zh_ [Chinese]
zh_CN [Chinese (Simplified Han,China)]
zh_HK [Chinese (Simplified Han,Hong Kong)]
zh_HK [Chinese (Traditional Han,Hong Kong)]
zh_MO [Chinese (Simplified Han,Macau)]
zh_MO [Chinese (Traditional Han,Macau)]
zh_SG [Chinese (Simplified Han,Singapore)]
zh_TW [Chinese (Traditional Han,Taiwan)]
zu_ [Zulu]
zu_ZA [Zulu (South Africa)]

How do I center text vertically and horizontally in Flutter?

Overview: I used the Flex widget to center text on my page using the MainAxisAlignment.center along the horizontal axis. I use the container padding to create a margin space around my text.

  Flex(
            direction: Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                Container(
                    padding: EdgeInsets.all(20),
                    child:
                        Text("No Records found", style: NoRecordFoundStyle))
  ])

How to detect installed version of MS-Office?

        public string WinWordVersion
        {
            get
            {
                string _version = string.Empty;
                Word.Application WinWord = new Word.Application();   

                switch (WinWord.Version.ToString())
                {
                    case "7.0":  _version = "95";
                        break;
                    case "8.0": _version = "97";
                        break;
                    case "9.0": _version = "2000";
                        break;
                    case "10.0": _version = "2002";
                        break;
                    case "11.0":  _version = "2003";
                        break;
                    case "12.0": _version = "2007";
                        break;
                    case "14.0": _version = "2010";
                        break;
                    case "15.0":  _version = "2013";
                        break;
                    case "16.0": _version = "2016";
                        break;
                    default:                            
                        break;
                }

                return WinWord.Caption + " " + _version;
            }
        }

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.

Example:

$bytes = random_bytes(20);
var_dump(bin2hex($bytes));

The above example will output something similar to:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

More info: http://php.net/manual/en/function.random-bytes.php

PHP 5 (outdated)

I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.

A quick, short and to the point answer is:

bin2hex(openssl_random_pseudo_bytes($bytes))

which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.


Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
    $range = $max - $min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        $rnd = $rnd & $filter; // discard irrelevant bits
    } while ($rnd > $range);
    return $min + $rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited

    for ($i=0; $i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

crypto_rand_secure($min, $max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.

getToken($length) creates an alphabet to use within the token and then creates a string of length $length.

Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322

Android: keep Service running when app is killed

In your service, add the following code.

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }

Undefined Reference to

g++ test.cpp LinearNode.cpp LinkedList.cpp -o test

HTTP Range header

Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.

In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.

How to get records randomly from the oracle database?

SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

C++ Fatal Error LNK1120: 1 unresolved externals

My problem was int Main() instead of int main()

good luck

When to use .First and when to use .FirstOrDefault with LINQ?

Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First() statement in a method threw the exception may be difficult.

The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.

That's why I always use FirstOrDefault() even though I know a null entry would constitute an exceptional situation.

var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
   throw new Exception(string.Format("Can't find customer {0}.", customerId));
}

Delete everything in a MongoDB database

in case you'd need to drop everything at once: (drop all databases at once)

mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'

Log4net rolling daily filename with date in the file name

Using Log4Net 1.2.13 we use the following configuration settings to allow date time in the file name.

<file type="log4net.Util.PatternString" value="E:/logname-%utcdate{yyyy-MM-dd}.txt" />

Which will provide files in the following convention: logname-2015-04-17.txt

With this it's usually best to have the following to ensure you're holding 1 log per day.

<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />

If size of file is a concern the following allows 500 files of 5MB in size until a new day spawns. CountDirection allows Ascending or Descending numbering of files which are no longer current.

 <maxSizeRollBackups value="500" />
 <maximumFileSize value="5MB" />
 <rollingStyle value="Composite" />
 <datePattern value="yyyyMMdd" />
 <CountDirection value="1"/>
 <staticLogFileName value="true" />

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Disable Tensorflow debugging information

Yeah, I'm using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don't seem to exist anymore.

I stepped around in PDB and found this to work:

# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])

I then add my own logger API (in this case file-based)

logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)

# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)

How to undo a successful "git cherry-pick"?

git reflog can come to your rescue.

Type it in your console and you will get a list of your git history along with SHA-1 representing them.

Simply checkout any SHA-1 that you wish to revert to


Before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

How do I generate a random int number?

Beware that new Random() is seeded on current timestamp.

If you want to generate just one number you can use:

new Random().Next( int.MinValue, int.MaxValue )

For more information, look at the Random class, though please note:

However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

So do not use this code to generate a series of random number.

Correct redirect URI for Google API and OAuth 2.0

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

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

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

How do I run a terminal inside of Vim?

The main new feature of Vim 8.1 is support for running a terminal in a Vim window.

:term will open the terminal in another window inside Vim.

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.

However, there is an easy "hack" for fixing this issue:

Before you execute your command(s) you first have to disable the foreign key constraints check using this command:

SET FOREIGN_KEY_CHECKS = 0;

Then you are able to execute your command(s).

After you are done, don't forget to enable the foreign key constraints check again, using this command:

SET FOREIGN_KEY_CHECKS = 1;

Good luck with your endeavor.

What's the difference between HEAD, working tree and index, in Git?

Your working tree is what is actually in the files that you are currently working on.

HEAD is a pointer to the branch or commit that you last checked out, and which will be the parent of a new commit if you make it. For instance, if you're on the master branch, then HEAD will point to master, and when you commit, that new commit will be a descendent of the revision that master pointed to, and master will be updated to point to the new commit.

The index is a staging area where the new commit is prepared. Essentially, the contents of the index are what will go into the new commit (though if you do git commit -a, this will automatically add all changes to files that Git knows about to the index before committing, so it will commit the current contents of your working tree). git add will add or update files from the working tree into your index.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

Eslint: How to disable "unexpected console statement" in Node.js?

You should update eslint config file to fix this permanently. Else you can temporarily enable or disable eslint check for console like below

/* eslint-disable no-console */
console.log(someThing);
/* eslint-enable no-console */

How do you create a custom AuthorizeAttribute in ASP.NET Core?

You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.

public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
    {
        var attributes = new List<TAttribute>();

        var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
        if (action != null)
        {
            attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
            attributes.AddRange(GetAttributes(action.MethodInfo));
        }

        return HandleRequirementAsync(context, requirement, attributes);
    }

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

    private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
    {
        return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
    }
}

Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
    public string Name { get; }

    public PermissionAttribute(string name) : base("Permission")
    {
        Name = name;
    }
}

Then create a Requirement to add to your Policy

public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
    //Add any custom requirement properties if you have them
}

Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.

public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
    {
        foreach (var permissionAttribute in attributes)
        {
            if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
            {
                return;
            }
        }

        context.Succeed(requirement);
    }

    private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
    {
        //Implement your custom user permission logic here
    }
}

And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.

        services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Permission", policyBuilder =>
            {
                policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
            });
        });

Now you can simply decorate your Controllers and Actions with your custom attribute.

[Permission("AccessCustomers")]
public class CustomersController
{
    [Permission("AddCustomer")]
    IActionResult AddCustomer([FromBody] Customer customer)
    {
        //Add customer
    }
}

Distribution certificate / private key not installed

In my case Xcode was not accessing certificates from the keychain, I followed these steps:

  1. delete certificates from the keychain.
  2. restart the mac.
  3. generate new certificates.
  4. install new certificates.
  5. clean build folder.
  6. build project.
  7. again clean build folder.
  8. archive now. It works That's it.

Android - Pulling SQlite database android device

 adb shell "run-as [package.name] chmod -R 777 /data/data/[package.name]/databases" 
 adb shell "mkdir -p /sdcard/tempDB" 
 adb shell "cp -r /data/data/[package.name]/databases/ /sdcard/tempDB/." 
 adb pull sdcard/tempDB/ . 
 adb shell "rm -r /sdcard/tempDB/*"

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

It works; just thought this would be helpful to someone in the future.

If you are working with MAMP, as a security measure, the $cfg['Servers'][$i]['AllowNoPassword'] = true; usually will be missing in the config.inc.php file so if you want to use phpMyAdmin without a password for root then simply add it preferably after the $cfg['Servers'][$i]['AllowDeny']['rules'] = array(); statement.

Then Restart your server just to be sure and you will be good to go.

how to stop Javascript forEach?

I guess you want to use Array.prototype.find Find will break itself when it finds your specific value in the array.

var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

Display tooltip on Label's hover?

You can use the css-property content and attr to display the content of an attribute in an :after pseudo element. You could either use the default title attribute (which is a semantic solution), or create a custom attribute, e.g. data-title.

HTML:

<label for="male" data-title="Please, refer to Wikipedia!">Male</label>

CSS:

label[data-title]{
  position: relative;
  &:hover:after{
    font-size: 1rem;
    font-weight: normal;
    display: block;
    position: absolute;
    left: -8em;
    bottom: 2em;
    content:  attr(data-title);
    background-color: white;
    width: 20em;
    text-aling: center;
  }
}

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

How can I make SQL case sensitive string comparison on MySQL?

http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

col_name COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_bin

If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation.

How to stop Python closing immediately when executed in Microsoft Windows

Late in here, but in case someone comes here from google---

Go to the location of your .py file. Press SHIFT then right click anywhere and choose open command prompt from here. Once it's up, Just add

"python NameOfTheProg.py" to the cmd line

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

In my case running Yosemite in VMWare Workstation 10.0.5 I had to:

1) Set kext to dev mode (might not be needed anymore .... try first without it)

sudo nvram boot-args="kext-dev-mode=1" 

Then reboot (power down VM) for step 2) below.

Details here: http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

2) Add vhv.enable = "TRUE" to my VMX file and restart the VM

Details discussed here: https://communities.vmware.com/thread/416997?start=15&tstart=0

3) Install HAXM 1.1.1 as discussed above from the Intel 's site

(would love to post more links -> but have limit for 2 -> so vote for me so next time you will gert more .. :-))

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I'm not sure of a way to do this in 3D, but in 2D you can use the compass command.

How to get an input text value in JavaScript

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

Turn off deprecated errors in PHP 5.3

I tend to use this method

$errorlevel=error_reporting();
$errorlevel=error_reporting($errorlevel & ~E_DEPRECATED);

In this way I do not turn off accidentally something I need

Python equivalent to 'hold on' in Matlab

You can use the following:

plt.hold(True)

Select All distinct values in a column using LINQ

var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

App not setup: This app is still in development mode

2020 UPDATE

Visit https://developers.facebook.com/apps/ and select your application.

Go to Settings -> Basic. Add a Contact Email and a Privacy Policy URL. The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

React native text going off my screen, refusing to wrap. What to do?

<Text style={{width: 200}} numberOfLines={1} ellipsizeMode="tail">Your text here</Text>

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

Detect element content changes with jQuery

These are mutation events.

I have not used mutation event APIs in jQuery, but a cursory search led me to this project on GitHub. I am unaware of the project's maturity.

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How to delete a cookie using jQuery?

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

How to create module-wide variables in Python?

Explicit access to module level variables by accessing them explicity on the module


In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

# db.py
import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = "Locally scoped db_name variable. Doesn't do anything here."
    else:
        msg = "Database is already initialized to {0}."
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
import db

if (db.db_name == 'mongo'):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value 
# that "db.db_name" has at import time of "client_c".

if (db_name == 'mongo'):  # checking is fine if "db.db_name" doesn't change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

Long Press in JavaScript?

$(document).ready(function () {
    var longpress = false;

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");
    });

    var startTime, endTime;
    $("button").on('mousedown', function () {
        startTime = new Date().getTime();
    });

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;
    });
});

DEMO

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.

<system.web>
      <customErrors mode="Off" />

First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.

Get to the detailed error first and update your question.

UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.

Changing Java Date one hour back

Just subtract the number of milliseconds in an hour from the date.

currentDate.setTime(currentDate.getTime() - 3600 * 1000));

How do I allow HTTPS for Apache on localhost?

Another simple method is using Python Server in Ubuntu.

  1. Generate server.xml with the following command in terminal:

    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes

    Note: Assuming you have openssl installed.

  2. Save below code in a file named simple-https-server.py in any directory you want to run the server.

    import BaseHTTPServer, SimpleHTTPServer
    import ssl
    
    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
    httpd.serve_forever()
    
  3. Run the server from terminal:

    python simple-https-server.py

  4. Visit the page at:

    https://localhost:4443

Extra notes::

  1. You can change the port in simple-https-server.py file in line

    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)

  2. You can change localhost to your IP in the same line above:

    httpd = BaseHTTPServer.HTTPServer(('10.7.1.3', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)

    and access the page on any device your network connected. This is very handy in cases like "you have to test HTML5 GeoLocation API in a mobile, and Chrome restricts the API in secure connections only".

Gist: https://gist.github.com/dergachev/7028596

http://www.piware.de/2011/01/creating-an-https-server-in-python/

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

Put spacing between divs in a horizontal row?

A possible idea would be to:

  1. delete the width: 25%; float:left; from the style of your divs
  2. wrap each of the four colored divs in a div that has style="width: 25%; float:left;"

The advantage with this approach is that all four columns will have equal width and the gap between them will always be 5px * 2.

Here's what it looks like:

_x000D_
_x000D_
.cellContainer {_x000D_
  width: 25%;_x000D_
  float: left;_x000D_
}
_x000D_
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: red;">A</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: orange;">B</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: green;">C</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: blue;">D</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to return multiple objects from a Java method?

Before Java 5, I would kind of agree that the Map solution isn't ideal. It wouldn't give you compile time type checking so can cause issues at runtime. However, with Java 5, we have Generic Types.

So your method could look like this:

public Map<String, MyType> doStuff();

MyType of course being the type of object you are returning.

Basically I think that returning a Map is the right solution in this case because that's exactly what you want to return - a mapping of a string to an object.

No provider for HttpClient

You are getting error for HttpClient so, you are missing HttpClientModule for that.

You should import it in app.module.ts file like this -

import { HttpClientModule } from '@angular/common/http';

and mention it in the NgModule Decorator like this -

@NgModule({
...
imports:[ HttpClientModule ]
...
})

If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.

How to check if a Docker image with a specific tag exist locally?

You can use like the following:

[ ! -z $(docker images -q someimage:sometag) ] || echo "does not exist"

Or:

[ -z $(docker images -q someimage:sometag) ] || echo "already exists"

angular.js ng-repeat li items with html content

You can use NGBindHTML or NGbindHtmlUnsafe this will not escape the html content of your model.

http://jsfiddle.net/n9rQr/

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts"  ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

This works, anyway you should be very careful when using unsanitized html content, you should really trust the source of the content.

Sorting a DropDownList? - C#, ASP.NET

Assuming you are running the latest version of the .Net Framework this will work:

List<string> items = GetItemsFromSomewhere();
items.Sort((x, y) => string.Compare(x, y));
DropDownListId.DataSource = items;
DropDownListId.DataBind();

How do I force files to open in the browser instead of downloading (PDF)?

If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.

If a .zip is not an option, then use headers in PHP to force the download

header('Content-Type: application/force-download'); 
header('Content-Description: File Transfer'); 

How to clean project cache in Intellij idea like Eclipse's clean?

If you are using Maven, run this command in your project directory

mvn clean package

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

FirstOrDefault: Default value other than null

I know its been a while but Ill add to this, based on the most popular answer but with a little extension Id like to share the below:

static class ExtensionsThatWillAppearOnIEnumerables
{
    public static T FirstOr<T>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T> alternate)
    {
        var thing = source.FirstOrDefault(predicate);
        if (thing != null)
            return thing;
        return alternate();
    }
}

This allows me to call it inline as such with my own example I was having issues with:

_controlDataResolvers.FirstOr(x => x.AppliesTo(item.Key), () => newDefaultResolver()).GetDataAsync(conn, item.ToList())

So for me I just wanted a default resolver to be used inline, I can do my usual check and then pass in a function so a class isn't instantiated even if unused, its a function to execute when required instead!

How do I switch between command and insert mode in Vim?

Looks like your Vim is launched in easy mode. See :help easy.

This happens when Vim is invoked with the -y argument or as evim, or maybe you have a :set insertmode somewhere in your .vimrc configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim Enter.

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

Just open the Application Console.app on mac osX.

You can find it under Applications > Utilities > Console.

On the left side of the application all your connected devices are listed.

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

How to grep, excluding some patterns?

Just use awk, it's much simpler than grep in letting you clearly express compound conditions.

If you want to skip lines that contains both loom and gloom:

awk '/loom/ && !/gloom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

or if you want to print them:

awk '/(^|[^g])loom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

and if the reality is you just want lines where loom appears as a word by itself:

awk '/\<loom\>/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

Eclipse cannot load SWT libraries

on my Ubuntu 12.04 32 bit. I edit the command to:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86/

And on Ubuntu 12.04 64 bit try:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86_64/

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Quick easy way to migrate SQLite3 to MySQL?

There is no need to any script,command,etc...

you have to only export your sqlite database as a .csv file and then import it in Mysql using phpmyadmin.

I used it and it worked amazing...

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

They changed the packaging for psycopg2. Installing the binary version fixed this issue for me. The above answers still hold up if you want to compile the binary yourself.

See http://initd.org/psycopg/docs/news.html#what-s-new-in-psycopg-2-8.

Binary packages no longer installed by default. The ‘psycopg2-binary’ package must be used explicitly.

And http://initd.org/psycopg/docs/install.html#binary-install-from-pypi

So if you don't need to compile your own binary, use:

pip install psycopg2-binary

Javascript: The prettiest way to compare one value against multiple values

Don't try to be too sneaky, especially when it needlessly affects performance. If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||
    foobar === bar ||
    foobar === baz ||
    foobar === pew) {
     //do something
}

How to timeout a thread

Assuming the thread code is out of your control:

From the Java documentation mentioned above:

What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

Bottom Line:

Make sure all threads can be interrupted, or else you need specific knowledge of the thread - like having a flag to set. Maybe you can require that the task be given to you along with the code needed to stop it - define an interface with a stop() method. You can also warn when you failed to stop a task.

How to set selected value on select using selectpicker plugin from bootstrap

You can set the selected value by calling the val method on the element.

$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);

This will select all items in a multi-select.

$('.selectpicker').selectpicker('selectAll');

details are available on site : https://silviomoreto.github.io/bootstrap-select/methods/

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

Insert into ... values ( SELECT ... FROM ... )

Instead of VALUES part of INSERT query, just use SELECT query as below.

INSERT INTO table1 ( column1 , 2, 3... )
SELECT col1, 2, 3... FROM table2

How to select a single child element using jQuery?

No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery's magic.

If you want to access the underlying element, you have three options...

  1. Do not use jQuery
  2. Use [0] to reference it
  3. Extend jQuery to do what you want...

    $.fn.child = function(s) {
        return $(this).children(s)[0];
    }
    

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

How do I sort a list of dictionaries by a value of the dictionary?

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness (as pointed out in comments by fitzgeraldsteele), add reverse=True to sort descending

newlist = sorted(l, key=itemgetter('name'), reverse=True)

Upper memory limit?

Not only are you reading the whole of each file into memory, but also you laboriously replicate the information in a table called list_of_lines.

You have a secondary problem: your choices of variable names severely obfuscate what you are doing.

Here is your script rewritten with the readlines() caper removed and with meaningful names:

file_A1_B1 = open("A1_B1_100000.txt", "r")
file_A2_B2 = open("A2_B2_100000.txt", "r")
file_A1_B2 = open("A1_B2_100000.txt", "r")
file_A2_B1 = open("A2_B1_100000.txt", "r")
file_write = open ("average_generations.txt", "w")
mutation_average = open("mutation_average", "w") # not used
files = [file_A2_B2,file_A2_B2,file_A1_B2,file_A2_B1]
for afile in files:
    table = []
    for aline in afile:
        values = aline.split('\t')
        values.remove('\n') # why?
        table.append(values)
    row_count = len(table)
    row0length = len(table[0])
    print_counter = 4
    for column_index in range(row0length):
        column_total = 0
        for row_index in range(row_count):
            number = float(table[row_index][column_index])
            column_total = column_total + number
        column_average = column_total/row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1
file_write.write('\n')

It rapidly becomes apparent that (1) you are calculating column averages (2) the obfuscation led some others to think you were calculating row averages.

As you are calculating column averages, no output is required until the end of each file, and the amount of extra memory actually required is proportional to the number of columns.

Here is a revised version of the outer loop code:

for afile in files:
    for row_count, aline in enumerate(afile, start=1):
        values = aline.split('\t')
        values.remove('\n') # why?
        fvalues = map(float, values)
        if row_count == 1:
            row0length = len(fvalues)
            column_index_range = range(row0length)
            column_totals = fvalues
        else:
            assert len(fvalues) == row0length
            for column_index in column_index_range:
                column_totals[column_index] += fvalues[column_index]
    print_counter = 4
    for column_index in column_index_range:
        column_average = column_totals[column_index] / row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1

PowerShell : retrieve JSON object by field value

Hows about this:

$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value

which would select from json structured

{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}

This is based on this accessing values in powershell SO question . Isn't powershell fabulous!

ASP.NET Web API : Correct way to return a 401/unauthorised response

Just return the following:

return Unauthorized();

Is there an easy way to check the .NET Framework version?

It used to be easy, but Microsoft decided to make a breaking change: Before version 4.5, each version of .NET resided in its own directory below C:\Windows\Microsoft.NET\Framework (subdirectories v1.0.3705, v1.1.4322, v2.0.50727, v3.0, v3.5 and v4.0.30319).

Since version 4.5 this has been changed: Each version of .NET (i.e. 4.5.x, 4.6.x, 4.7.x, 4.8.x, ...) is being installed in the same subdirectory v4.0.30319 - so you are no longer able to check the installed .NET version by looking into Microsoft.NET\Framework.

To check the .NET version, Microsoft has provided two different sample scripts depending on the .NET version that is being checked, but I don't like having two different C# scripts for this. So I tried to combine them into one, here's the script GetDotNetVersion.cs I created (and updated it for 4.7.1 framework):

using System;
using Microsoft.Win32;
public class GetDotNetVersion
{
    public static void Main(string[] args)
    {
        Console.WriteLine((args != null && args.Length > 0) 
                          ? "Command line arguments: " + string.Join(",", args) 
                          : "");

        string maxDotNetVersion = GetVersionFromRegistry();
        if (String.Compare(maxDotNetVersion, "4.5") >= 0)
        {
            string v45Plus = GetDotNetVersion.Get45PlusFromRegistry();
            if (v45Plus != "") maxDotNetVersion = v45Plus;
        }
        Console.WriteLine("*** Maximum .NET version number found is: " + maxDotNetVersion + "***");
    }

    private static string Get45PlusFromRegistry()
    {
        String dotNetVersion = "";
        const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
        {
            if (ndpKey != null && ndpKey.GetValue("Release") != null)
            {
                dotNetVersion = CheckFor45PlusVersion((int)ndpKey.GetValue("Release"));
                Console.WriteLine(".NET Framework Version: " + dotNetVersion);
            }
            else
            {
                Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
            }
        }
        return dotNetVersion;
    }

    // Checking the version using >= will enable forward compatibility.
    private static string CheckFor45PlusVersion(int releaseKey)
    {
        if (releaseKey >= 528040) return "4.8 or later";
        if (releaseKey >= 461808) return "4.7.2";
        if (releaseKey >= 461308) return "4.7.1";
        if (releaseKey >= 460798) return "4.7";
        if (releaseKey >= 394802) return "4.6.2";
        if (releaseKey >= 394254) return "4.6.1";
        if (releaseKey >= 393295) return "4.6";
        if ((releaseKey >= 379893)) return "4.5.2";
        if ((releaseKey >= 378675)) return "4.5.1";
        if ((releaseKey >= 378389)) return "4.5";

        // This code should never execute. A non-null release key should mean
        // that 4.5 or later is installed.
        return "No 4.5 or later version detected";
    }

    private static string GetVersionFromRegistry()
    {
        String maxDotNetVersion = "";
        // Opens the registry key for the .NET Framework entry.
        using (RegistryKey ndpKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "")
                                        .OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5 
            // or later, you can use:
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            foreach (string versionKeyName in ndpKey.GetSubKeyNames())
            {
                if (versionKeyName.StartsWith("v"))
                {
                    RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                    string name = (string)versionKey.GetValue("Version", "");
                    string sp = versionKey.GetValue("SP", "").ToString();
                    string install = versionKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                    {
                        Console.WriteLine(versionKeyName + "  " + name);
                        if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                    }
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            Console.WriteLine(versionKeyName + "  " + name + "  SP" + sp);
                            if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                        }

                    }
                    if (name != "")
                    {
                        continue;
                    }
                    foreach (string subKeyName in versionKey.GetSubKeyNames())
                    {
                        RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                        name = (string)subKey.GetValue("Version", "");
                        if (name != "")
                        {
                            sp = subKey.GetValue("SP", "").ToString();
                        }
                        install = subKey.GetValue("Install", "").ToString();
                        if (install == "")
                        {
                            //no install info, must be later.
                            Console.WriteLine(versionKeyName + "  " + name);
                            if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                        }
                        else
                        {
                            if (sp != "" && install == "1")
                            {
                                Console.WriteLine("  " + subKeyName + "  " + name + "  SP" + sp);
                                if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                            }
                            else if (install == "1")
                            {
                                Console.WriteLine("  " + subKeyName + "  " + name);
                                if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                            } // if
                        } // if
                    } // for
                } // if
            } // foreach
        } // using
        return maxDotNetVersion;
    }
    
} // class

On my machine it outputs:

v2.0.50727 2.0.50727.4927 SP2
v3.0 3.0.30729.4926 SP2
v3.5 3.5.30729.4926 SP1
v4
Client 4.7.03056
Full 4.7.03056
v4.0
Client 4.0.0.0
.NET Framework Version: 4.7.2 or later
**** Maximum .NET version number found is: 4.7.2 or later ****

The only thing that needs to be maintained over time is the build number once a .NET version greater than 4.7.1 comes out - that can be done easily by modifying the function CheckFor45PlusVersion, you need to know the release key for the new version then you can add it. For example:

if (releaseKey >= 461308) return "4.7.1 or later";

This release key is still the latest one and valid for the Fall Creators update of Windows 10. If you're still running other (older) Windows versions, there is another one as per this documentation from Microsoft:

.NET Framework 4.7.1 installed on all other Windows OS versions 461310

So, if you need that as well, you'll have to add

if (releaseKey >= 461310) return "4.7.1 or later";

to the top of the function CheckFor45PlusVersion. Likewise it works for newer versions. For example, I have added the check for 4.8 recently. You can find those build numbers usually at Microsoft.


Note: You don't need Visual Studio to be installed, not even PowerShell - you can use csc.exe to compile and run the script above, which I have described here.


Update: The question is about the .NET Framework, for the sake of completeness I'd like to mention how to query the version of .NET Core as well - compared with the above, that is easy: Open a command shell and type:

dotnet --info Enter

and it will list the .NET Core version number, the Windows version and the versions of each related runtime DLL as well. Sample output:

.NET Core SDK (reflecting any global.json):
  Version: 2.1.300
  Commit: adab45bf0c

Runtime Environment:
  OS Name: Windows
  OS Version: 10.0.15063
  OS Platform: Windows
  RID: win10-x64
  Base Path: C:\Program Files\dotnet\sdk\2.1.300


Host (useful for support):
  Version: 2.1.0
  Commit: caa7b7e2ba

.NET Core SDKs installed:
  1.1.9 [C:\Program Files\dotnet\sdk]
  2.1.102 [C:\Program Files\dotnet\sdk]
  ...
  2.1.300 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.0 [C:\Program
  Files\dotnet\shared\Microsoft.AspNetCore.All]
  ...
  Microsoft.NETCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Note that

  • if you only need the version number without all the additional information, you can use
    dotnet --version.

  • on a 64 bit Windows PC, it is possible to install the x86 version side by side with the x64 version of .NET Core. If that is the case, you will only get the version that comes first in the environment variable PATH. That is especially important if you need to keep it up to date and want to know each version. To query both versions, use:

C:\Program Files\dotnet\dotnet.exe --version
3.0.100-preview6-012264
C:\Program Files (x86)\dotnet\dotnet.exe --version
3.0.100-preview6-012264

In the example above, both are the same, but if you forgot to update both instances, you might get different results! Note that Program Files is for the 64bit version, and Program Files (x86) is the 32bit version.


Update: If you prefer to keep the build numbers in a list rather than in a cascade of if-statements (as Microsoft suggested), then you can use this code for CheckFor45PlusVersion instead:

private static string CheckFor45PlusVersion(int releaseKey)
{
    var release = new Dictionary<int, string>()
    {
            { 378389, "4.5" },
            { 378675, "4.5.1" }, { 379893, "4.5.2" },
            { 393295, "4.6" },
            { 394254, "4.6.1" }, { 394802, "4.6.2" },
            { 460798, "4.7" },
            { 461308, "4.7.1" }, { 461808, "4.7.2" },
            { 528040, "4.8 or later" }
    };
    int result = -1;
    foreach(var k in release.OrderBy(k=>k.Key))
    {
        if (k.Key <= releaseKey) result = k.Key; else break;
    };
    return (result > 0) ? release[result] : "No 4.5 or later version detected";
}

Running Python code in Vim

You can extends for any language with 1 keybinding with augroup command, for example:

augroup rungroup
    autocmd!
    autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
    autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END

android pinch zoom

For android 2.2+ (api level8), you can use ScaleGestureDetector.

you need a member:

private ScaleGestureDetector mScaleDetector;

in your constructor (or onCreate()) you add:

mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
        return false;
    }
});

You override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().

Uploading file using POST request in Node.js

Looks like you're already using request module.

in this case all you need to post multipart/form-data is to use its form feature:

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:

form.append('file', fs.createReadStream(filepath));

request will extract all related metadata by itself.

For more information on posting multipart/form-data see node-form-data module, which is internally used by request.

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

How to set a ripple effect on textview or imageview on Android?

Using libraries. This is one of them. Just add its dependency and put below code in xml before each elements that needs ripple effect:

<com.balysv.materialripple.MaterialRippleLayout
android:id="@+id/ripple"
android:layout_width="match_parent"
android:layout_height="wrap_content">

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

How do I read all classes from a Java package in the classpath?

If you have Spring in you classpath then the following will do it.

Find all classes in a package that are annotated with XmlRootElement:

private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class> candidates = new ArrayList<Class>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                               resolveBasePackage(basePackage) + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return candidates;
}

private String resolveBasePackage(String basePackage) {
    return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}

private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
    try {
        Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
        if (c.getAnnotation(XmlRootElement.class) != null) {
            return true;
        }
    }
    catch(Throwable e){
    }
    return false;
}

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

We had the same issue, in making a websocket connection to the Load Balancer. The issue is in LB, accepting http connection on port 80 and forwarding the request to node (tomcat app on port 8080). We have changed this to accept tcp (http has been changed as 'tcp') connection on port 80. So the first handshake request is forwarded to Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.

below command has been used to test the websocket handshake process.

curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL

  • Rebuilt URL to: http:LB URL/
  • Trying LB URL...
  • TCP_NODELAY set
  • Connected to LB URL (LB URL) port 80 (#0)

    GET / HTTP/1.1 Host: localhost User-Agent: curl/7.60.0 Accept: / Connection: Upgrade Upgrade: websocket Origin: http://LB URL:80

  • Recv failure: Connection reset by peer
  • Closing connection 0 curl: (56) Recv failure: Connection reset by peer

Using "like" wildcard in prepared statement

String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";


PreparedStatement preparedStatement=con.prepareStatement(query);


// where seleced and SelectedStr are String Variables in my program

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

How to share data between different threads In C# using AOP?

When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.

  Worker myWorker = new Worker( /* arguments */ );

  Thread myThread = new Thread(new ThreadStart(myWorker.doWork));

  myThread.Start();

Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

Set mouse focus and move cursor to end of input using jQuery

I have found the same thing as suggested above by a few folks. If you focus() first, then push the val() into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val() into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus().

$('element_identifier').focus().val('some_value') 

should do the trick (it always has for me anyway).

How can I install pip on Windows?

To install pip globally on Python 2.x, easy_install appears to be the best solution as Adrián states.

However the installation instructions for pip recommend using virtualenv since every virtualenv has pip installed in it automatically. This does not require root access or modify your system Python installation.

Installing virtualenv still requires easy_install though.

2018 update:

Python 3.3+ now includes the venv module for easily creating virtual environments like so:

python3 -m venv /path/to/new/virtual/environment

See documentation for different platform methods of activating the environment after creation, but typically one of:

$ source <venv>/bin/activate 

C:\> <venv>\Scripts\activate.bat

How can I do time/hours arithmetic in Google Spreadsheet?

In the case you want to format it within a formula (for example, if you are concatenating strings and values), the aforementioned format option of Google is not available, but you can use the TEXT formula:

=TEXT(B1-C1,"HH:MM:SS")

Therefore, for the questioned example, with concatenation:

="The number of " & TEXT(B1,"HH") & " hour slots in " & TEXT(C1,"HH") _
& " is " & TEXT(C1/B1,"HH")

Cheers

Moment.js transform to date object

moment has updated the js lib as of 06/2018.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.

Gson: Is there an easier way to serialize a map

Map<String, Object> config = gson.fromJson(reader, Map.class);

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

I was having the same issue and fixed it by changing the default program to open .ps1 files to PowerShell. It was set to Notepad.

How to resolve Unneccessary Stubbing exception

For me neither the @Rule nor the @RunWith(MockitoJUnitRunner.Silent.class) suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.

We could get rid of the UnnecessaryStubbingException by using:

Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());

instead of:

when(mockedService.getUserById(any())).thenReturn(new User());

Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)

Using Environment Variables with Vue.js

In vue-cli version 3:

There are the three options for .env files: Either you can use .env or:

  • .env.test
  • .env.development
  • .env.production

You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

What is the correct way of reading from a TCP socket in C/C++?

Several pointers:

You need to handle a return value of 0, which tells you that the remote host closed the socket.

For nonblocking sockets, you also need to check an error return value (-1) and make sure that errno isn't EINPROGRESS, which is expected.

You definitely need better error handling - you're potentially leaking the buffer pointed to by 'buffer'. Which, I noticed, you don't allocate anywhere in this code snippet.

Someone else made a good point about how your buffer isn't a null terminated C string if your read() fills the entire buffer. That is indeed a problem, and a serious one.

Your buffer size is a bit small, but should work as long as you don't try to read more than 256 bytes, or whatever you allocate for it.

If you're worried about getting into an infinite loop when the remote host sends you a malformed message (a potential denial of service attack) then you should use select() with a timeout on the socket to check for readability, and only read if data is available, and bail out if select() times out.

Something like this might work for you:

fd_set read_set;
struct timeval timeout;

timeout.tv_sec = 60; // Time out after a minute
timeout.tv_usec = 0;

FD_ZERO(&read_set);
FD_SET(socketFileDescriptor, &read_set);

int r=select(socketFileDescriptor+1, &read_set, NULL, NULL, &timeout);

if( r<0 ) {
    // Handle the error
}

if( r==0 ) {
    // Timeout - handle that. You could try waiting again, close the socket...
}

if( r>0 ) {
    // The socket is ready for reading - call read() on it.
}

Depending on the volume of data you expect to receive, the way you scan the entire message repeatedly for the "end;" token is very inefficient. This is better done with a state machine (the states being 'e'->'n'->'d'->';') so that you only look at each incoming character once.

And seriously, you should consider finding a library to do all this for you. It's not easy getting it right.

how to increase java heap memory permanently?

if you need to increase reserved memory, there are VM parameters -Xms and -Xmx, usage e.g. -Xms512m -Xmx512m . There is also parameter -XX:MaxPermSize=256m which changes memory reserved for permanent generation

If your application runs as windows service, in Control panels -> Administration tools -> Services you can add some run parameters to your service

Copy array by value

Using jQuery deep copy could be made as following:

var arr2 = $.extend(true, [], arr1);

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader

Leave only two decimal places after the dot

yourValue.ToString("0.00") will work.

How to customize a Spinner in Android

The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html

Basically, follow these steps:

  1. Create custom layout xml file for your dropdown item, let's say I will call it spinner_item.xml
  2. Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:

    public class CustomArrayAdapter extends ArrayAdapter<String>{
    
    private List<String> objects;
    private Context context;
    
    public CustomArrayAdapter(Context context, int resourceId,
         List<String> objects) {
         super(context, resourceId, objects);
         this.objects = objects;
         this.context = context;
    }
    
    @Override
    public View getDropDownView(int position, View convertView,
        ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return getCustomView(position, convertView, parent);
    }
    
    public View getCustomView(int position, View convertView, ViewGroup parent) {
    
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(  Context.LAYOUT_INFLATER_SERVICE );
    View row=inflater.inflate(R.layout.spinner_item, parent, false);
    TextView label=(TextView)row.findViewById(R.id.spItem);
     label.setText(objects.get(position));
    
    if (position == 0) {//Special style for dropdown header
          label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
    }
    
    return row;
    }
    
    }
    
  3. In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:

    Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
    ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
    sp.setAdapter(myAdapter);
    

where options is the list of dropdown item string.

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

How can I tail a log file in Python?

The only portable way to tail -f a file appears to be, in fact, to read from it and retry (after a sleep) if the read returns 0. The tail utilities on various platforms use platform-specific tricks (e.g. kqueue on BSD) to efficiently tail a file forever without needing sleep.

Therefore, implementing a good tail -f purely in Python is probably not a good idea, since you would have to use the least-common-denominator implementation (without resorting to platform-specific hacks). Using a simple subprocess to open tail -f and iterating through the lines in a separate thread, you can easily implement a non-blocking tail operation in Python.

Example implementation:

import threading, Queue, subprocess
tailq = Queue.Queue(maxsize=10) # buffer at most 100 lines

def tail_forever(fn):
    p = subprocess.Popen(["tail", "-f", fn], stdout=subprocess.PIPE)
    while 1:
        line = p.stdout.readline()
        tailq.put(line)
        if not line:
            break

threading.Thread(target=tail_forever, args=(fn,)).start()

print tailq.get() # blocks
print tailq.get_nowait() # throws Queue.Empty if there are no lines to read

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

Convert string to Python class object?

You could do something like:

globals()[class_name]

How do I create an executable in Visual Studio 2013 w/ C++?

Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->

JAVA_HOME directory in Linux

http://www.gnu.org/software/sed/manual/html_node/Print-bash-environment.html#Print-bash-environment

If you really want to get some info about your BASH put that script in your .bashrc and watch it fly by. You can scroll around and look it over.

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

When using a Settings.settings file in .NET, where is the config actually stored?

It depends on whether the setting you have chosen is at "User" scope or "Application" scope.

User scope

User scope settings are stored in

C:\Documents and Settings\ username \Local Settings\Application Data\ ApplicationName

You can read/write them at runtime.

For Vista and Windows 7, folder is

C:\Users\ username \AppData\Local\ ApplicationName

or

C:\Users\ username \AppData\Roaming\ ApplicationName

Application scope

Application scope settings are saved in AppName.exe.config and they are readonly at runtime.

How do I add a delay in a JavaScript loop?

Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:

function timeout(range, time, callback){
    var i = range[0];                
    callback(i);
    Loop();
    function Loop(){
        setTimeout(function(){
            i++;
            if (i<range[1]){
                callback(i);
                Loop();
            }
        }, time*1000)
    } 
}

For example:

//This function prints the loop number every second
timeout([0, 5], 1, function(i){
    console.log(i);
});

Would be equivalent to:

//This function prints the loop number instantly
for (var i = 0; i<5; i++){
    console.log(i);
}

How to check if a string starts with a specified string?

You can use a simple regex (updated version from user viriathus as eregi is deprecated)

if (preg_match('#^http#', $url) === 1) {
    // Starts with http (case sensitive).
}

or if you want a case insensitive search

if (preg_match('#^http#i', $url) === 1) {
    // Starts with http (case insensitive).
}

Regexes allow to perform more complex tasks

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).
}

Performance wise, you don't need to create a new string (unlike with substr) nor parse the whole string if it doesn't start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). http://www.php.net/manual/en/intro.pcre.php

Copy values from one column to another in the same table

Following worked for me..

  1. Ensure you are not using Safe-mode in your query editor application. If you are, disable it!
  2. Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -

UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';

Good Luck!

Using a PHP variable in a text input value = statement

Solution

You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.

<input type="text" name="idtest" value="<?php echo $idtest; ?>" >

Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.

Bootstrap modal appearing under background

Like Davide Lorigliola, I fixed it by cranking up the z-index:

.modal-backdrop { z-index: -999999; }

go to character in vim

vim +21490go script.py

From the command line will open the file and take you to position 21490 in the buffer.

Triggering it from the command line like this allows you to automate a script to parse the exception message and open the file to the problem position.


Excerpt from man vim:

+{command}

-c {command}

{command} will be executed after the first file has been read. {command} is interpreted as an Ex command. If the {command} contains spaces it must be enclosed in double quotes (this depends on the shell that is used).

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

HTML: How to limit file upload to be only images?

<script>

    function chng()
    {
        var typ=document.getElementById("fiile").value;
        var res = typ.match(".jp");

        if(res)
        {
            alert("sucess");
        }
        else
        {
            alert("Sorry only jpeg images are accepted");
            document.getElementById("fiile").value="; //clear the uploaded file
        }
    }

</script>

Now in the html part

<input type="file" onchange="chng()">

this code will check if the uploaded file is a jpg file or not and restricts the upload of other types

Scheduled run of stored procedure on SQL server

Probably not the answer you are looking for, but I find it more useful to simply use Windows Server Task Scheduler

You can use directly the command sqlcmd.exe -S "." -d YourDataBase -Q "exec SP_YourJob"

Or even create a .bat file. So you can even 2x click on the task on demand.

This has also been approached in this HERE

How to use Apple's new .p8 certificate for APNs in firebase console

Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.

So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.

To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"

enter image description here

Then will generate directly p8 file.

I hope this will solve your issue.

Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/

Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html

Description Box using "onmouseover"

I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.

Here's a simple example.

HTML:

?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????

Basic CSS:

?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?

jQuery:

$("#testText").hover(
   function(e){
       $("#tooltip").show();
   },
   function(e){
       $("#tooltip").hide();
  });??????????

How can I get the sha1 hash of a string in node.js?

You can use:

  const sha1 = require('sha1');
  const crypt = sha1('Text');
  console.log(crypt);

For install:

  sudo npm install -g sha1
  npm install sha1 --save

What is C# analog of C++ std::pair?

I typically extend the Tuple class into my own generic wrapper as follows:

public class Statistic<T> : Tuple<string, T>
{
    public Statistic(string name, T value) : base(name, value) { }
    public string Name { get { return this.Item1; } }
    public T Value { get { return this.Item2; } }
}

and use it like so:

public class StatSummary{
      public Statistic<double> NetProfit { get; set; }
      public Statistic<int> NumberOfTrades { get; set; }

      public StatSummary(double totalNetProfit, int numberOfTrades)
      {
          this.TotalNetProfit = new Statistic<double>("Total Net Profit", totalNetProfit);
          this.NumberOfTrades = new Statistic<int>("Number of Trades", numberOfTrades);
      }
}

StatSummary summary = new StatSummary(750.50, 30);
Console.WriteLine("Name: " + summary.NetProfit.Name + "    Value: " + summary.NetProfit.Value);
Console.WriteLine("Name: " + summary.NumberOfTrades.Value + "    Value: " + summary.NumberOfTrades.Value);

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

How to implement a lock in JavaScript

I've had success mutex-promise.

I agree with other answers that you might not need locking in your case. But it's not true that one never needs locking in Javascript. You need mutual exclusivity when accessing external resources that do not handle concurrency.

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Swift: Sort array of objects alphabetically

Most of these answers are wrong due to the failure to use a locale based comparison for sorting. Look at localizedStandardCompare()

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

Is there a kind of Firebug or JavaScript console debug for Android?

You can type about:debug in some of the mobile browsers to pull up a JavaScript console.

Using an image caption in Markdown Jekyll

<p align="center">
  <img alt="img-name" src="/path/image-name.png" width="300">
  <br>
    <em>caption</em>
</p>

That is the basic caption use. Not necessary to use an extra plugin.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

What is the fastest way to send 100,000 HTTP requests in Python?

[Tool]

Apache Bench is all you need. - A command line computer program (CLI) for measuring the performance of HTTP web servers

A nice blog post for you: https://www.petefreitag.com/item/689.cfm (from Pete Freitag)

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a problem there. When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".

Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().

Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.

T-test in Pandas

it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:

from scipy.stats import ttest_ind

cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']

ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)

it returns a tuple with the t-statistic & the p-value

see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();