Programs & Examples On #Industrial

Changing text color of menu item in navigation drawer

You can use drawables in

app:itemTextColor app:itemIconTint

then you can control the checked state and normal state using a drawable

<android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemHorizontalPadding="@dimen/margin_30"
            app:itemIconTint="@drawable/drawer_item_color"
            app:itemTextColor="@drawable/drawer_item_color"
            android:theme="@style/NavigationView"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_menu">

drawer_item_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/selectedColor" android:state_checked="true" />
    <item android:color="@color/normalColor" />
</selector>

How can I strip first X characters from string using sed?

Rather than removing n characters from the start, perhaps you could just extract the digits directly. Like so...

$ echo "pid: 1234" | grep -Po "\d+"

This may be a more robust solution, and seems more intuitive.

get list of pandas dataframe columns based on data type

Using dtype will give you desired column's data type:

dataframe['column1'].dtype

if you want to know data types of all the column at once, you can use plural of dtype as dtypes:

dataframe.dtypes

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I don't think so. I wanted this the other day. The closest I got was:

SELECT
  o.OrderId,
  CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN o.NegotiatedPrice 
     ELSE o.SuggestedPrice
  END
FROM Order o

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

This works for me, 12.04, python2.7.6

sudo apt-get install libxml2 libxml2-dev libxslt1-dev
sudo apt-get install lxml

Angular 2 router no base href set

With angular 4 you can fix this issue by updating app.module.ts file as follows:

Add import statement at the top as below:

import {APP_BASE_HREF} from '@angular/common';

And add below line inside @NgModule

providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]

Reff: https://angular.io/api/common/APP_BASE_HREF

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Pythonic way to check if a list is sorted or not

As I don't see this option above I will add it to all the answers. Let denote the list by l, then:

import numpy as np

# Trasform the list to a numpy array
x = np.array(l)

# check if ascendent sorted:
all(x[:-1] <= x[1:])

# check if descendent sorted:
all(x[:-1] >= x[1:])

Shuffling a list of objects

In some cases when using numpy arrays, using random.shuffle created duplicate data in the array.

An alternative is to use numpy.random.shuffle. If you're working with numpy already, this is the preferred method over the generic random.shuffle.

numpy.random.shuffle

Example

>>> import numpy as np
>>> import random

Using random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

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


>>> random.shuffle(foo)
>>> foo

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

Using numpy.random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

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


>>> np.random.shuffle(foo)
>>> foo

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

Get Character value from KeyCode in JavaScript... then trim

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode(). For values of keyCode <= 96 it seems to map using the function:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:

chrCode = keyCode

If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    let keyCode = e.keyCode;_x000D_
    let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
    let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
    console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_
_x000D_
_x000D_

Display exact matches only with grep

This may work for you

grep -E '(^|\s)OK($|\s)'

Define a fixed-size list in Java

If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.

If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.

public void fixedAdd(List<Integer> list, int val, int size) {
    list.add(val);
    if(list.size() > size) list.remove(0);
}

LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Just download and install the latest version of Virtual box, run it then run the emulator and viola, it will be up and running. This one worked for me.

How to apply bold text style for an entire row using Apache POI?

This worked for me

    Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
            { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };

    String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };

    int noOfColumns = headers.length;
    int rowCount = 0;

    Row rowZero = sheet.createRow(rowCount++);
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setFont(font);
    for (int col = 1; col <= noOfColumns; col++) {
        Cell cell = rowZero.createCell(col);
        cell.setCellValue(headers[col - 1]);
        cell.setCellStyle(style);
    }

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

Triangle Draw Method

You should try using the Shapes API.

Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas

You should also read up on GeneralPath & Drawing Arbitrary Shapes.

This method is much easy to apply AffineTransformations to

Is there a constraint that restricts my generic method to numeric types?

I was wondering the same as samjudson, why only to integers? and if that is the case, you might want to create a helper class or something like that to hold all the types you want.

If all you want are integers, don't use a generic, that is not generic; or better yet, reject any other type by checking its type.

Sanitizing user input before adding it to the DOM in Javascript

You could use a simple regular expression to assert that the id only contains allowed characters, like so:

if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
    //The id is fine
}
else{
    //The id is illegal
}

My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.

By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.

I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.

In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.

How can strip whitespaces in PHP's variable?

The \s regex argument is not compatible with UTF-8 multybyte strings.

This PHP RegEx is one I wrote to solve this using PCRE (Perl Compatible Regular Expressions) based arguments as a replacement for UTF-8 strings:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

- Example Usage -

Before:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

After:

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

PCRE Argument Listing

Source: https://www.rexegg.com/regex-quickstart.html

Character   Legend  Example Sample Match
\t  Tab T\t\w{2}    T     ab
\r  Carriage return character   see below   
\n  Line feed character see below   
\r\n    Line separator on Windows   AB\r\nCD    AB
    CD
\N  Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h  Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator      
\H  One character that is not a horizontal whitespace       
\v  .NET, JavaScript, Python, Ruby: vertical tab        
\v  Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator      
\V  Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace      
\R  Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)      

Centering a background image, using CSS

background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;

That should work.

If not, why not make a div with the image and use z-index to make it the background? This would be much easier to center than a background image on the body.

Other than that try:

background-position: 0 100px;/*use a pixel value that will center it*/ Or I think you can use 50% if you have set your body min-height to 100%.

body{

    background-repeat:no-repeat;
    background-position: center center;
    background-image:url(../images/images2.jpg);
    color:#FFF;
    font-family:Arial, Helvetica, sans-serif;
    min-height:100%;
}

How do I select a sibling element using jQuery?

$(this).siblings(".bidbutton")

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

How to link home brew python version and set it as default

I think you have to be precise with which version you want to link with the command brew link python like:

brew link python 3

It will give you an error like that:

Linking /usr/local/Cellar/python3/3.5.2... 
Error: Could not symlink bin/2to3-3.5
Target /usr/local/bin/2to3-3.5
already exists. 

You may want to remove it:

rm '/usr/local/bin/2to3-3.5'

To force the link and overwrite all conflicting files:

brew link --overwrite python3

To list all files that would be deleted:

brew link --overwrite --dry-run python3

but you have to copy/paste the command to force the link which is:

brew link --overwrite python3

I think that you must have the version (the newer) installed.

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

A CORS POST request works from plain JavaScript, but why not with jQuery?

Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:

        $.ajax({
            type: "POST",
            crossdomain: true,
            url: "http://localhost:1415/anything",
            dataType: "json",
            data: JSON.stringify({
                anydata1: "any1",
                anydata2: "any2",
            }),
            success: function (result) {
                console.log(result)
            },
            error: function (xhr, status, err) {
                console.error(xhr, status, err);
            }
        });

with this headers on c# server:

                    if (request.HttpMethod == "OPTIONS")
                    {
                          response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                          response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                          response.AddHeader("Access-Control-Max-Age", "1728000");
                    }
                    response.AppendHeader("Access-Control-Allow-Origin", "*");

How to inspect FormData?

I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

trying to align html button at the center of the my page

For me it worked using flexbox.

Add a css class around the parent div / element with :

.parent {
    display: flex;
}

and for the button use:

.button {
    justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

Why do you need to put #!/bin/bash at the beginning of a script file?

The operating system takes default shell to run your shell script. so mentioning shell path at the beginning of script, you are asking the OS to use that particular shell. It is also useful for portability.

How to use the ConfigurationManager.AppSettings

you should use []

var x = ConfigurationManager.AppSettings["APIKey"];

How to read a file from jar in Java?

If you want to read that file from inside your application use:

InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");

The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".

The InputStream reads the content of your file. You can wrap it into an Reader, if you want.

I hope that helps.

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

How to make a div center align in HTML

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.

Java reflection: how to get field value from an object, not knowing its class

Assuming a simple case, where your field is public:

List list; // from your method
for(Object x : list) {
    Class<?> clazz = x.getClass();
    Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
    Object fieldValue = field.get(x);
}

But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).

If you can change your method to return a List<Foo>, this becomes very easy because the iterator then can give you type information:

List<Foo> list; //From your method
for(Foo foo:list) {
    Object fieldValue = foo.fieldName;
}

Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...

List list;
for(Object x: list) {
   if( x instanceof Foo) {
      Object fieldValue = ((Foo)x).fieldName;
   }
}

No reflection needed :)

How can I read input from the console using the Scanner class in Java?

import java.util.*;

class Ss
{
    int id, salary;
    String name;

   void Ss(int id, int salary, String name)
    {
        this.id = id;
        this.salary = salary;
        this.name = name;
    }

    void display()
    {
        System.out.println("The id of employee:" + id);
        System.out.println("The name of employye:" + name);
        System.out.println("The salary of employee:" + salary);
    }
}

class employee
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
        s.display();
    }
}

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

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

Sending Arguments To Background Worker?

You can pass multiple arguments like this.

List<object> arguments = new List<object>();
arguments.Add("first");      //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10);           //argument n

backgroundWorker.RunWorkerAsync(arguments);

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
  List<object> genericlist = e.Argument as List<object>;
  //extract your multiple arguments from 
  //this list and cast them and use them. 
}

Using {% url ??? %} in django templates

I run into same problem.

What I found from documentation, we should use namedspace.

in your case {% url login:login_view %}

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

return(
  data.frame(
    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE
  )
)

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

Delete keychain items when an app is uninstalled

@amro's answer translated to Swift 4.0:

if UserDefaults.standard.object(forKey: "FirstInstall") == nil {
    UserDefaults.standard.set(false, forKey: "FirstInstall")
    UserDefaults.standard.synchronize()
}

Server Client send/receive simple text

The following code send and recieve the current date and time from and to the server

//The following code is for the server application:

namespace Server
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";

        static void Main(string[] args)
        {
            //---listen at the specified IP and port no.---
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            Console.WriteLine("Listening...");
            listener.Start();

            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);

            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);
            client.Close();
            listener.Stop();
            Console.ReadLine();
        }
    }
}

//this is the code for the client

namespace Client
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";
        static void Main(string[] args)
        {
            //---data to send to the server---
            string textToSend = DateTime.Now.ToString();

            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
            Console.ReadLine();
            client.Close();
        }
    }
}

How to show matplotlib plots in python

In case anyone else ends up here using Jupyter Notebooks, you just need

%matplotlib inline

Purpose of "%matplotlib inline"

Convert from days to milliseconds

Its important to mention that once in 4-5 years this method might give a 1 second error, becase of a leap-second (http://www.nist.gov/pml/div688/leapseconds.cfm), and the correct formula for that day would be

(24*60*60 + 1) * 1000

There is a question Are leap seconds catered for by Calendar? and the answer is no.

So, if You're designing super time-dependant software, be careful about this formula.

ImportError: Cannot import name X

As already mentioned, this is caused by a circular dependency. What has not been mentioned is that when you're using Python typing module and you import a class only to be used to annotate Types, you can use Forward references:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

and remove the dependency (the import), e.g. instead of

from my_module import Tree

def func(arg: Tree):
    # code

do:

def func(arg: 'Tree'):
    # code

(note the removed import statement)

get basic SQL Server table structure information

Instead of using count(*) you can SELECT * and you will return all of the details that you want including data_type:

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'

MSDN Docs on INFORMATION_SCHEMA.COLUMNS

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

Get difference between 2 dates in JavaScript?

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

Session variables in ASP.NET MVC

The answer here is correct, I however struggled to implement it in an ASP.NET MVC 3 app. I wanted to access a Session object in a controller and couldn't figure out why I kept on getting a "Instance not set to an instance of an Object error". What I noticed is that in a controller when I tried to access the session by doing the following, I kept on getting that error. This is due to the fact that this.HttpContext is part of the Controller object.

this.Session["blah"]
// or
this.HttpContext.Session["blah"]

However, what I wanted was the HttpContext that's part of the System.Web namespace because this is the one the Answer above suggests to use in Global.asax.cs. So I had to explicitly do the following:

System.Web.HttpContext.Current.Session["blah"]

this helped me, not sure if I did anything that isn't M.O. around here, but I hope it helps someone!

How to check if a list is empty in Python?

I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:

if len(my_list) == 0:
    print "my_list is empty"

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

How to check if a subclass is an instance of a class at runtime?

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

Create Hyperlink in Slack

In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:

  1. Copy a URL to the clipboard
  2. Select the text in a slack message you are writing that you want to be a link
  3. Press ?V on Mac or CtrlV

I couldn't find it documented anywhere, but it works, and seems very handy.

jQuery UI Dialog individual CSS styling

Try these:

#dialog_style1 .ui-dialog-titlebar { display:none; }
#dialog_style2 .ui-dialog-titlebar { color:#aaa; }

The best recommendation I can give for you is to load the page in Firefox, open the dialog and inspect it with Firebug, then try different selectors in the console, and see what works. You may need to use some of the other descendant selectors.

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results

enter image description here

DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size

Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)

DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit

How to trim white spaces of array values in php

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function generateRandomSpaces() {
    $output = '';
    $i = rand(1, 10);
    for ($j = 0; $j <= $i; $j++) {
        $output .= " ";
    }   

    return $output;
}

// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
    $array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces(); 
}

// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";

// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk    : " . $time . " seconds\n"; 

// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    foreach ($array as $index => $elem) {
        $array[$index] = trim($elem);
    }
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";

// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    for ($j = 0; $j < count($array) - 1; $j++) { 
        $array[$j] = trim($array[$j]);
    }
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";

The output of the code above is:

Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds

This values of course may change but I would say foreach is the best option.

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()

How do you make an anchor link non-clickable or disabled?

Bootstrap provide us with .disabled class. Please use it.

But .disabled class only works when the 'a' tag already has class 'btn'. It doesn' t work on any old 'a' tag. The btn class may not be appropriate in some context as it has style connotations. Under the covers, the .disabled class sets pointer-events to none, so you can make CSS to do the same thing as Saroj Aryal and Vitrilo have sugested. (Thank you, Les Nightingill for this advice).

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

bash: pip: command not found

Try using this. Instead of zmq, we can use any package instead of zmq.

sudo apt-get install python3-pip
sudo apt-get update
python3 -m pip install zmq

I was was not able to install this zmq package in my docker image because of the same issue i was getting. So tried this as another way to install and it worked fine for me.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.

How to disable EditText in Android

you can use EditText.setFocusable(false) to disable editing
EditText.setFocusableInTouchMode(true) to enable editing;

How to capture a list of specific type with mockito

The nested generics-problem can be avoided with the @Captor annotation:

public class Test{

    @Mock
    private Service service;

    @Captor
    private ArgumentCaptor<ArrayList<SomeType>> captor;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test 
    public void shouldDoStuffWithListValues() {
        //...
        verify(service).doStuff(captor.capture()));
    }
}

Equivalent of Clean & build in Android Studio?

Also you can edit your Run/Debug configuration and add clean task.

Click on the Edit configuration

Click on the Edit configuration

In the left list of available configurations choose your current configuration and then on the right side of the dialog window in the section Before launch press on plus sign and choose Run Gradle task

choose <code>Run Gradle task</code>

In the new window choose your gradle project and in the field Tasks type clean.

type <code>clean</code>

Then move your gradle clean on top of Gradle-Aware make

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

Which to use <div class="name"> or <div id="name">?

ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.

How can I explicitly free memory in Python?

Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".

The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.

In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when you're all done with them).

How to add an extra column to a NumPy array

I like JoshAdel's answer because of the focus on performance. A minor performance improvement is to avoid the overhead of initializing with zeros, only to be overwritten. This has a measurable difference when N is large, empty is used instead of zeros, and the column of zeros is written as a separate step:

In [1]: import numpy as np

In [2]: N = 10000

In [3]: a = np.ones((N,N))

In [4]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
1 loops, best of 3: 492 ms per loop

In [5]: %timeit b = np.empty((a.shape[0],a.shape[1]+1)); b[:,:-1] = a; b[:,-1] = np.zeros((a.shape[0],))
1 loops, best of 3: 407 ms per loop

jQuery: how do I animate a div rotation?

If you want just a jQuery option, this will work:

$(el).stop().animate(
  {rotation: 360},
  {
    duration: 500,
    step: function(now, fx) {
      $(this).css({"transform": "rotate("+now+"deg)"});
    }
  }
);

This works with jQuery 1.8, which takes care of CSS prefixing automatically. jQuery doesn't animate rotation so I'm putting the transform:rotate() in the custom step function. It might only work starting from 0.

Demo: http://jsfiddle.net/forresto/ShUgD/

IE9 and Mobile Safari 4 support CSS transforms but not CSS transitions, so I came up with this simple shim, using Modernizr feature testing:

if (Modernizr.csstransitions) {
  $(el).css({
    "transition": "all 500ms ease-in-out"
  });
}

$(el).click(function(){
  var rotateTo = 360;
  if (Modernizr.csstransitions) {
    $(el).css({"transform": "rotate("+rotateTo+"deg)"});
  } else {
    $(el).stop().animate(
      {rotation: rotateTo},
      {
        duration: 500,
        step: function(now, fx) {
          $(this).css({"transform": "rotate("+now+"deg)"});
        }
      }
    );
  }
});

The above will use CSS transitions when available.

Where can I download Eclipse Android bundle?

Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from

ADT for Eclipse

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

Git: which is the default configured remote for branch?

Track the remote branch

You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:

Edit your .git/config

[branch "master"]
  remote = origin
  merge = refs/heads/master

Now you can simply git push and git pull.

[source]

Printing 1 to 1000 without loop or conditionals

#include "stdafx.h"
static n=1;
class number {
public:
    number () {
        std::cout << n++ << std::endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    number X[1000];
    return 0;
}

What's the best way to determine the location of the current PowerShell script?

For PowerShell 3.0

$PSCommandPath
    Contains the full path and file name of the script that is being run. 
    This variable is valid in all scripts.

The function is then:

function Get-ScriptDirectory {
    Split-Path -Parent $PSCommandPath
}

jQuery AutoComplete Trigger Change Event

this will work,too

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

// deprecated
//$("#CompanyList").data("autocomplete")._trigger("change")
// use this now
$("#CompanyList").data("ui-autocomplete")._trigger("change")

WampServer orange icon

PLEASE NOTE! If you have gone through all of the above, like "I" did, and still get the Orange icon, and, when you test Port 80 you get "Apache", look at the file: c:/wamp/bin/apache/apache2.4.9/conf/httpd.conf (your apache version number may differ).

In the file, about line # 62, you'll find a note saying to fill in this:

Listen 0.0.0.0:80 Listen [::0]:80

Why?

Change this to Listen on specific IP addresses as shown below to prevent Apache from glomming onto all bound IP addresses.

I changed that to match my localhost IP address and when I restarted Wamp, it quickly went from Red to Green. Success!...3 hours later....

How to pass parameters in $ajax POST?

You can do it using $.ajax or $.post

Using $.ajax :

    $.ajax({
      type: 'post',
      url: 'superman',
      data: { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      success: function (response) {
        alert(response.status);
      },
      error: function () {
        alert("error");
      }
   });

Using $.post :

    $.post('superman',
      { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      function (response, status) {
        alert(response.status);
      }
    );

Load local HTML file in a C# WebBrowser

quite late but it's the first hit i found from google

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;  
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);

Is there a way to make numbers in an ordered list bold?

Answer https://stackoverflow.com/a/21369918/2526049 from dcodesmith has a side effect that turns all types of lists numeric. <ol type="a"> will show 1. 2. 3. 4. rather than a. b. c. d.

ol {
  margin: 0 0 1.5em;
  padding: 0;
  counter-reset: item;
}

ol > li {
  margin: 0;
  padding: 0 0 0 2em;
  text-indent: -2em;
  list-style-type: none;
  counter-increment: item;
}

ol > li:before {
  display: inline-block;
  width: 1em;
  padding-right: 0.5em;
  font-weight: bold;
  text-align: right;
  content: counter(item) ".";
}

/* Add support for non-numeric lists */

ol[type="a"] > li:before {
  content: counter(item, lower-alpha) ".";
}
ol[type="i"] > li:before {
  content: counter(item, lower-roman) ".";
}

The above code adds support for lowercase letters, lowercase roman numerals. At the time of writing browsers do not differentiate between upper and lower case selectors for type so you can only pick uppercase or lowercase for your alternate ol types I guess.

Handle spring security authentication exceptions with @ExceptionHandler

In ResourceServerConfigurerAdapter class, below code snipped worked for me. http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler()).and.csrf().. did not work. That's why I wrote it as separate call.

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler());

        http.csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/subscribers/**").authenticated()
                .antMatchers("/requests/**").authenticated();
    }

Implementation of AuthenticationEntryPoint for catching token expiry and missing authorization header.


public class AuthFailureHandler implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
      throws IOException, ServletException {
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if( e instanceof InsufficientAuthenticationException) {

      if( e.getCause() instanceof InvalidTokenException ){
        httpServletResponse.getOutputStream().println(
            "{ "
                + "\"message\": \"Token has expired\","
                + "\"type\": \"Unauthorized\","
                + "\"status\": 401"
                + "}");
      }
    }
    if( e instanceof AuthenticationCredentialsNotFoundException) {

      httpServletResponse.getOutputStream().println(
          "{ "
              + "\"message\": \"Missing Authorization Header\","
              + "\"type\": \"Unauthorized\","
              + "\"status\": 401"
              + "}");
    }

  }
}

Case insensitive regular expression without re.compile?

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

Pandas column of lists, create a row for each list element

A bit longer than I expected:

>>> df
                samples  subject  trial_num
0  [-0.07, -2.9, -2.44]        1          1
1   [-1.52, -0.35, 0.1]        1          2
2  [-0.17, 0.57, -0.65]        1          3
3  [-0.82, -1.06, 0.47]        2          1
4   [0.79, 1.35, -0.09]        2          2
5   [1.17, 1.14, -1.79]        2          3
>>>
>>> s = df.apply(lambda x: pd.Series(x['samples']),axis=1).stack().reset_index(level=1, drop=True)
>>> s.name = 'sample'
>>>
>>> df.drop('samples', axis=1).join(s)
   subject  trial_num  sample
0        1          1   -0.07
0        1          1   -2.90
0        1          1   -2.44
1        1          2   -1.52
1        1          2   -0.35
1        1          2    0.10
2        1          3   -0.17
2        1          3    0.57
2        1          3   -0.65
3        2          1   -0.82
3        2          1   -1.06
3        2          1    0.47
4        2          2    0.79
4        2          2    1.35
4        2          2   -0.09
5        2          3    1.17
5        2          3    1.14
5        2          3   -1.79

If you want sequential index, you can apply reset_index(drop=True) to the result.

update:

>>> res = df.set_index(['subject', 'trial_num'])['samples'].apply(pd.Series).stack()
>>> res = res.reset_index()
>>> res.columns = ['subject','trial_num','sample_num','sample']
>>> res
    subject  trial_num  sample_num  sample
0         1          1           0    1.89
1         1          1           1   -2.92
2         1          1           2    0.34
3         1          2           0    0.85
4         1          2           1    0.24
5         1          2           2    0.72
6         1          3           0   -0.96
7         1          3           1   -2.72
8         1          3           2   -0.11
9         2          1           0   -1.33
10        2          1           1    3.13
11        2          1           2   -0.65
12        2          2           0    0.10
13        2          2           1    0.65
14        2          2           2    0.15
15        2          3           0    0.64
16        2          3           1   -0.10
17        2          3           2   -0.76

Change the Theme in Jupyter Notebook?

This is easy to do using the jupyter-themes package by Kyle Dunovan. You may be able to install it using conda. Otherwise, you will need to use pip.

Install it with conda:

conda install -c conda-forge jupyterthemes

or pip:

pip install jupyterthemes

You can get the list of available themes with:

jt -l

So change your theme with:

jt -t theme-name

To load a theme, finally, reload the page. The docs and source code are here.

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

Remove the Debug permissions on the Device, with the cell phone connected, then put them back, and ask if you want to allow the PC to have debug, accept and ready permissions: D

Same Navigation Drawer in different Activities

With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.

I've been able to do that.

Jar mismatch! Fix your dependencies

Don't Include the android-support-v4 in the library , instead you can add it to your project as an external jar using build path menu > add external jar

Sometimes you have to clean your project.

Filtering collections in C#

If you're using C# 3.0 you can use linq, way better and way more elegant:

List<int> myList = GetListOfIntsFromSomewhere();

// This will filter out the list of ints that are > than 7, Where returns an
// IEnumerable<T> so a call to ToList is required to convert back to a List<T>.
List<int> filteredList = myList.Where( x => x > 7).ToList();

If you can't find the .Where, that means you need to import using System.Linq; at the top of your file.

Delegation: EventEmitter or Observable in Angular

You can use either:

  1. Behaviour Subject:

BehaviorSubject is a type of subject, a subject is a special type of observable which can act as observable and observer you can subscribe to messages like any other observable and upon subscription, it returns the last value of the subject emitted by the source observable:

Advantage: No Relationship such as parent-child relationship required to pass data between components.

NAV SERVICE

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  private navSubject$ = new BehaviorSubject<number>(0);

  constructor() {  }

  // Event New Item Clicked
  navItemClicked(navItem: number) {
    this.navSubject$.next(number);
  }

 // Allowing Observer component to subscribe emitted data only
  getNavItemClicked$() {
   return this.navSubject$.asObservable();
  }
}

NAVIGATION COMPONENT

@Component({
  selector: 'navbar-list',
  template:`
    <ul>
      <li><a (click)="navItemClicked(1)">Item-1 Clicked</a></li>
      <li><a (click)="navItemClicked(2)">Item-2 Clicked</a></li>
      <li><a (click)="navItemClicked(3)">Item-3 Clicked</a></li>
      <li><a (click)="navItemClicked(4)">Item-4 Clicked</a></li>
    </ul>
})
export class Navigation {
  constructor(private navService:NavService) {}
  navItemClicked(item: number) {
    this.navService.navItemClicked(item);
  }
}

OBSERVING COMPONENT

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  itemClickedSubcription:any

  constructor(private navService:NavService) {}
  ngOnInit() {

    this.itemClickedSubcription = this.navService
                                      .getNavItemClicked$
                                      .subscribe(
                                        item => this.selectedNavItem(item)
                                       );
  }
  selectedNavItem(item: number) {
    this.item = item;
  }

  ngOnDestroy() {
    this.itemClickedSubcription.unsubscribe();
  }
}

Second Approach is Event Delegation in upward direction child -> parent

  1. Using @Input and @Output decorators parent passing data to child component and child notifying parent component

e.g Answered given by @Ashish Sharma.

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

Simple way to read single record from MySQL

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);

There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.

Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

Jenkins returned status code 128 with github

i had sometime ago the same issue. make sure that your ssh key doesn't have password and use not common user account (e.g. better to user account called jenkins or so).

check following article http://fourkitchens.com/blog/2011/09/20/trigger-jenkins-builds-pushing-github

How to create a unique index on a NULL column?

Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html

How to fix "'System.AggregateException' occurred in mscorlib.dll"

As the message says, you have a task which threw an unhandled exception.

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.


(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.

How to make a progress bar

If you are using HTML5 its better to make use of <progress> tag which was newly introduced.

<progress value="22" max="100"></progress>

Or create a progress bar of your own.

Example written in sencha

if (!this.popup) {
            this.popup = new Ext.Panel({
            floating: true,
            modal: false,
            // centered:true,
            style:'background:black;opacity:0.6;margin-top:330px;',
            width: '100%',
            height: '20%',
            styleHtmlContent: true,
            html: '<p align="center" style="color:#FFFFFF;font-size:12px">Downloading Data<hr noshade="noshade"size="7" style="color:#FFFFFF"></p>',

            });
}
this.popup.show('pop');

pandas dataframe groupby datetime month

(update: 2018)

Note that pd.Timegrouper is depreciated and will be removed. Use instead:

 df.groupby(pd.Grouper(freq='M'))

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

On windows Power Shell, you can use the following command:

New-Item <filename.extension>

or

New-Item <filename.extension> -type file

Note: New-Item can be replaced with its alias ni

How to assign text size in sp value using java code

Thanks @John Leehey and @PeterH:

desiredSp = getResources().getDimension(R.dimen.desired_sp);
density = getResources().getDisplayMetrics().density;
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, desiredSp / density);

The thing is if you define R.dimen.desired_sp to 25 in your dimen.xml

  1. On non-HD Device: desiredSp is still 25, density = 1
  2. On HD Device(like Nexus 7 2nd Generation): desiredSp becomes 50 ish, density = 2

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

How to get Top 5 records in SqLite?

TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).

select * from `Table_Name` LIMIT 5;

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Java stack overflow error - how to increase the stack size in Eclipse?

When the argument -Xss doesn't do the job try deleting the temporary files from:

c:\Users\{user}\AppData\Local\Temp\.

This did the trick for me.

clearing a char array c

I thought by setting the first element to a null would clear the entire contents of a char array.

That is not correct as you discovered

However, this only sets the first element to null.

Exactly!

You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.

However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory

How can I get the browser's scrollbar sizes?

This is a great answer: https://stackoverflow.com/a/986977/5914609

However in my case it did not work. And i spent hours searching for the solution.
Finally i've returned to above code and added !important to each style. And it worked.
I can not add comments below the original answer. So here is the fix:

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100% !important";
  inner.style.height = "200px !important";

  var outer = document.createElement('div');
  outer.style.position = "absolute !important";
  outer.style.top = "0px !important";
  outer.style.left = "0px !important";
  outer.style.visibility = "hidden !important";
  outer.style.width = "200px !important";
  outer.style.height = "150px !important";
  outer.style.overflow = "hidden !important";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll !important';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

jQuery how to bind onclick event to dynamically added HTML element

Consider this:

jQuery(function(){
  var close_link = $('<a class="" href="#">Click here to see an alert</a>');
      $('.add_to_this').append(close_link);
      $('.add_to_this').children().each(function()
      {
        $(this).click(function() {
            alert('hello from binded function call');
            //do stuff here...
        });
      });
});

It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.

The best way will probably be - as suggested - to bind it to a specific class via the live method.

What is "Connect Timeout" in sql server connection string?

That is the timeout to create the connection, NOT a timeout for commands executed over that connection.

See for instance http://www.connectionstrings.com/all-sql-server-connection-string-keywords/ (note that the property is "Connect Timeout" (or "Connection Timeout"), not just "Timeout")


From the comments:

It is not possible to set the command timeout through the connection string. However, the SqlCommand has a CommandTimeout property (derived from DbCommand) where you can set a timeout (in seconds) per command.

Do note that when you loop over query results with Read(), the timeout is reset on every read. The timeout is for each network request, not for the total connection.

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

Convert JSON array to Python list

import json

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']

You had everything you needed. data will be a dict, and data['fruits'] will be a list

Where can I find the assembly System.Web.Extensions dll?

Your project is mostly likely targetting .NET Framework 4 Client Profile. Check the application tab in your project properties.

This question has a good answer on the different versions: Target framework, what does ".NET Framework ... Client Profile" mean?

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

What does the function then() mean in JavaScript?

The traditional way to deal with asynchronous calls in JavaScript has been with callbacks. Say we had to make three calls to the server, one after the other, to set up our application. With callbacks, the code might look something like the following (assuming a xhrGET function to make the server call):

// Fetch some server configuration
    xhrGET('/api/server-config', function(config) {
        // Fetch the user information, if he's logged in
        xhrGET('/api/' + config.USER_END_POINT, function(user) {
            // Fetch the items for the user
            xhrGET('/api/' + user.id + '/items', function(items) {
                // Actually display the items here
            });
        });
    });

In this example, we first fetch the server configuration. Then based on that, we fetch information about the current user, and then finally get the list of items for the current user. Each xhrGET call takes a callback function that is executed when the server responds.

Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as callback hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.

The Promise API was designed to solve this nesting problem and the problem of error handling.

The Promise API proposes the following:

  1. Each asynchronous task will return a promise object.
  2. Each promise object will have a then function that can take two arguments, a success handler and an error handler.
  3. The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
  4. The then function will also return a promise, to allow chaining multiple calls.
  5. Each handler (success or error) can return a value, which will be passed to the next function as an argument, in the chain of promises.
  6. If a handler returns a promise (makes another asynchronous request), then the next handler (success or error) will be called only after that request is finished.

So the previous example code might translate to something like the following, using promises and the $http service(in AngularJs):

$http.get('/api/server-config').then(
    function(configResponse) {
        return $http.get('/api/' + configResponse.data.USER_END_POINT);
    }
).then(
    function(userResponse) {
        return $http.get('/api/' + userResponse.data.id + '/items');
    }
).then(
    function(itemResponse) {
        // Display items here
    }, 
    function(error) {
        // Common error handling
    }
);

Propagating Success and Error

Chaining promises is a very powerful technique that allows us to accomplish a lot of functionality, like having a service make a server call, do some postprocessing of the data, and then return the processed data to the controller. But when we work with promise chains, there are a few things we need to keep in mind.

Consider the following hypothetical promise chain with three promises, P1, P2, and P3. Each promise has a success handler and an error handler, so S1 and E1 for P1, S2 and E2 for P2, and S3 and E3 for P3:

xhrCall()
  .then(S1, E1) //P1
  .then(S2, E2) //P2
  .then(S3, E3) //P3

In the normal flow of things, where there are no errors, the application would flow through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might encounter an error, or P2 might encounter an error, triggering E1 or E2.

Consider the following cases:

• We receive a successful response from the server in P1, but the data returned is not correct, or there is no data available on the server (think empty array). In such a case, for the next promise P2, it should trigger the error handler E2.

• We receive an error for promise P2, triggering E2. But inside the handler, we have data from the cache, ensuring that the application can load as normal. In that case, we might want to ensure that after E2, S3 is called.

So each time we write a success or an error handler, we need to make a call—given our current function, is this promise a success or a failure for the next handler in the promise chain?

If we want to trigger the success handler for the next promise in the chain, we can just return a value from the success or the error handler

If, on the other hand, we want to trigger the error handler for the next promise in the chain, we can do that using a deferred object and calling its reject() method

Now What is deferred object?

Deferred objects in jQuery represents a unit of work that will be completed later, typically asynchronously. Once the unit of work completes, the deferred object can be set to resolved or failed.

A deferred object contains a promise object. Via the promise object you can specify what is to happen when the unit of work completes. You do so by setting callback functions on the promise object.

Deferred objects in Jquery : https://api.jquery.com/jquery.deferred/

Deferred objects in AngularJs : https://docs.angularjs.org/api/ng/service/$q

Getting the class name of an instance?

class A:
  pass

a = A()
str(a.__class__)

The sample code above (when input in the interactive interpreter) will produce '__main__.A' as opposed to 'A' which is produced if the __name__ attribute is invoked. By simply passing the result of A.__class__ to the str constructor the parsing is handled for you. However, you could also use the following code if you want something more explicit.

"{0}.{1}".format(a.__class__.__module__,a.__class__.__name__)

This behavior can be preferable if you have classes with the same name defined in separate modules.

The sample code provided above was tested in Python 2.7.5.

SELECT FOR UPDATE with SQL Server

How about trying to do a simple update on this row first (without really changing any data)? After that you can proceed with the row like in was selected for update.

UPDATE dbo.Customer SET FieldForLock = FieldForLock WHERE CustomerID = @CustomerID
/* do whatever you want */

Edit: you should wrap it in a transaction of course

Edit 2: another solution is to use SERIALIZABLE isolation level

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

Put content in HttpResponseMessage object?

The easiest single-line solution is to use

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };

For serialized JSON content:

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };

grid controls for ASP.NET MVC?

If it is read-only a good idea would be to create a table, then apply some really easy-but-powerful JQuery to that.

For simple alternative colour, try this simple JQuery.

If you need sorting, this JQuery plug-in simply rocks.

Take a char input from the Scanner

You could take the first character from Scanner.next:

char c = reader.next().charAt(0);

To consume exactly one character you could use:

char c = reader.findInLine(".").charAt(0);

To consume strictly one character you could use:

char c = reader.next(".").charAt(0);

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

How to draw interactive Polyline on route google maps v2 android

Instead of creating too many short Polylines just create one like here:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

I'm also not sure you should use geodesic when your points are so close to each other.

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

Difference between FetchType LAZY and EAGER in Java Persistence API?

public enum FetchType extends java.lang.Enum Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. Example: @Basic(fetch=LAZY) protected String getName() { return name; }

Source

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

html cellpadding the left side of a cell

Well, as suggested by Hellfire you can use td width or you could place an element in the td and adjust its width. We could not use

CSS property Padding

as in Microsoft Outlook padding does not work. So what I had to do is,

<table>
    <tr>
        <td><span style="display: inline-block; width: 40px;"></span><span>Content<span></td>
        <td>Content</td>
    </tr>
</table>

With this you can adjust right and left spacing. For top and bottom spacing you could use td's height property. Like,

 <table>
        <tr>
            <td style="vertical-align: top; height: 100px;">Content</td>
            <td>Content</td>
        </tr>
    </table>

This will increase bottom space.

Hope it will work for you guys. :)

iPad browser WIDTH & HEIGHT standard

There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.

That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.

More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.

On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.

Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

How to configure encoding in Maven?

This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.

If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)

Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).

This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.

To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8

Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).

How to remove constraints from my MySQL table?

There is no such thing as DROP CONSTRAINT in MySQL. In your case you could use DROP FOREIGN KEY instead.

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

How do I get SUM function in MySQL to return '0' if no values are found?

Use IFNULL or COALESCE:

SELECT IFNULL(SUM(Column1), 0) AS total FROM...

SELECT COALESCE(SUM(Column1), 0) AS total FROM...

The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

To me it feels like you have missing header files for popen, which is a C system library.

Check if you have installed xcode successful with the command line tools and have accepted the license.

See this thread for more information: How to install Xcode Command Line Tools

HTML5 Email Validation

Using HTML 5,Just make the input email like :

_x000D_
_x000D_
<input type="email"/>
_x000D_
_x000D_
_x000D_

When the user hovers over the input box, they will a tooltip instructing them to enter a valid email. However, Bootstrap forms have a much better Tooltip message to tell the user to enter an email address and it pops up the moment the value entered does not match a valid email.

How to execute a shell script from C in Linux?

I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.

Store you command in a char array parameters, and malloc space for the result.

int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
   fprintf(stderr, "FORK failed");
   return 1;
} else if( childpid == 0) {
   close(1);
   dup2(fd[1], 1);
   close(fd[0]);
   execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);

Run PostgreSQL queries from the command line

  1. Open a command prompt and go to the directory where Postgres installed. In my case my Postgres path is "D:\TOOLS\Postgresql-9.4.1-3".After that move to the bin directory of Postgres.So command prompt shows as "D:\TOOLS\Postgresql-9.4.1-3\bin>"
  2. Now my goal is to select "UserName" from the users table using "UserId" value.So the database query is "Select u."UserName" from users u Where u."UserId"=1".

The same query is written as below for psql command prompt of postgres.

D:\TOOLS\Postgresql-9.4.1-3\bin>psql -U postgres -d DatabaseName -h localhost - t -c "Select u.\"UserName\" from users u Where u.\"UserId\"=1;

Simple pthread! C++

When compiling with G++, remember to put the -lpthread flag :)

How to write to Console.Out during execution of an MSTest test

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

Align Div at bottom on main Div

Modify your CSS like this:

_x000D_
_x000D_
.vertical_banner {_x000D_
    border: 1px solid #E9E3DD;_x000D_
    float: left;_x000D_
    height: 210px;_x000D_
    margin: 2px;_x000D_
    padding: 4px 2px 10px 10px;_x000D_
    text-align: left;_x000D_
    width: 117px;_x000D_
    position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
   position:absolute;                  /* added */_x000D_
   bottom:0;                           /* added */_x000D_
   left:0;                           /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
    <div id="bottom_link">_x000D_
         <input type="submit" value="Continue">_x000D_
       </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I capitalize the first letter of each word in a string using JavaScript?

A more compact (and modern) rewrite of @somethingthere's proposed solution:

_x000D_
_x000D_
let titleCase = (str => str.toLowerCase().split(' ').map(
                c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
    
document.write(titleCase("I'm an even smaller tea pot"));
_x000D_
_x000D_
_x000D_

Opening Chrome From Command Line

Answering this for Ubuntu users for reference.

Run command google-chrome --app-url "http://localhost/"

Replace your desired URL in the parameter.

You can get more options like incognito mode etc. Run google-chrome --help to see the options.

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

How to edit .csproj file

The CSPROJ file, saved in XML format, stores all the references for your project including your compilation options. There is also an SLN file, which stores information about projects that make up your solution.

If you are using Visual Studio and you have the need to view or edit your CSPROJ file, while in Visual Studio, you can do so by following these simple steps:

  1. Right-click on your project in solution explorer and select Unload Project
  2. Right-click on the project (tagged as unavailable in solution explorer) and click "Edit yourproj.csproj". This will open up your CSPROJ file for editing.
  3. After making the changes you want, save, and close the file. Right-click again on the node and choose Reload Project when done.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

Python 'list indices must be integers, not tuple"

The problem is that [...] in python has two distinct meanings

  1. expr [ index ] means accessing an element of a list
  2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

In your code you forgot the comma between the expressions for the items in the outer list:

[ [a, b, c] [d, e, f] [g, h, i] ]

therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

The correct syntax for what you're looking for is

[ [a, b, c], [d, e, f], [g, h, i] ]

How to check for null/empty/whitespace values with a single test?

While checking null or Empty value for a column, I noticed that there are some support concerns in various Databases.

Every Database doesn't support TRIM method.

Below is the matrix just to understand the supported methods by different databases.

The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL: TRIM(), RTRIM(), LTRIM()
  • Oracle: RTRIM(), LTRIM()
  • SQL Server: TRIM(), RTRIM(), LTRIM()

How to Check Empty/Null/Whitespace :-

Below are two different ways according to different Databases-

The syntax for these trim functions are:

  1. Use of Trim to check-

    SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL

  2. Use of LTRIM & RTRIM to check-

    SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL

Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName

Hoping this will help others too :)

SeekBar and media player in android

The below code worked for me.

I've created a method for seekbar

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    mp.start();
     getDurationTimer();
    getSeekBarStatus();


}
//Creating duration time method
public void getDurationTimer(){
    final long minutes=(mSongDuration/1000)/60;
    final int seconds= (int) ((mSongDuration/1000)%60);
    SongMaxLength.setText(minutes+ ":"+seconds);


}



 //creating a method for seekBar progress
public void getSeekBarStatus(){

    new Thread(new Runnable() {

        @Override
        public void run() {
            // mp is your MediaPlayer
            // progress is your ProgressBar

            int currentPosition = 0;
            int total = mp.getDuration();
            seekBar.setMax(total);
            while (mp != null && currentPosition < total) {
                try {
                    Thread.sleep(1000);
                    currentPosition = mp.getCurrentPosition();
                } catch (InterruptedException e) {
                    return;
                }
                seekBar.setProgress(currentPosition);

            }
        }
    }).start();





    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress=0;

        @Override
        public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
            if (fromUser) {
                mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
            }
            final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
            final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
            SongProgress.setText(mMinutes+":"+mSeconds);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

SongProgress and SongMaxLength are the TextView to show song duration and song length.

Visual Studio Code includePath

For Mac users who only have Command Line Tools instead of Xcode, check the /Library/Developer/CommandLineTools directory, for example::

"configurations": [{
    "name": "Mac",
    "includePath": [
            "/usr/local/include",
            // others, e.g.: "/usr/local/opt/ncurses/include",
            "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
            "${workspaceFolder}/**"
    ]
}]

You probably need to adjust the path if you have different version of Command Line Tools installed.

Note: You can also open/generate the c_cpp_properties.json file via the C/Cpp: Edit Configurations command from the Command Palette (??P).

how to add value to a tuple?

OUTPUTS = []
for number in range(len(list_of_tuples))):
    tup_ = list_of_tuples[number]
    list_ = list(tup_)  
    item_ = list_[0] + list_[1] + list_[2] + list_[3]
    list_.append(item_)
    OUTPUTS.append(tuple(list_))

OUTPUTS is what you desire

Tomcat 8 is not able to handle get request with '|' in query parameters?

The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow is deprecated since Tomcat 8.5: tomcat official doc.

You can use relaxedQueryChars / relaxedPathChars in the connectors definition to allow these chars: tomcat official doc.

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

What is the best way to test for an empty string in Go?

As per official guidelines and from performance point of view they appear equivalent (ANisus answer), the s != "" would be better due to a syntactical advantage. s != "" will fail at compile time if the variable is not a string, while len(s) == 0 will pass for several other data types.

Get file size before uploading

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

Is it possible to run selenium (Firefox) web driver without a GUI?

Install & run containerized Firefox:

docker pull selenium/standalone-firefox
docker run --rm -d -p 4444:4444 --shm-size=2g selenium/standalone-firefox

Connect using webdriver.Remote:

driver = webdriver.Remote('http://localhost:4444/wd/hub', DesiredCapabilities.FIREFOX)
driver.set_window_size(1280, 1024)
driver.get('https://www.google.com')

How to set environment variable or system property in spring tests?

If you want your variables to be valid for all tests, you can have an application.properties file in your test resources directory (by default: src/test/resources) which will look something like this:

MYPROPERTY=foo

This will then be loaded and used unless you have definitions via @TestPropertySource or a similar method - the exact order in which properties are loaded can be found in the Spring documentation chapter 24. Externalized Configuration.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Removing duplicate rows from table in Oracle

You should do a small pl/sql block using a cursor for loop and delete the rows you don't want to keep. For instance:

declare
prev_var my_table.var1%TYPE;

begin

for t in (select var1 from my_table order by var 1) LOOP

-- if previous var equal current var, delete the row, else keep on going.
end loop;

end;

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

Parsing XML with namespace in Python via 'ElementTree'

Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.

To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse function, parsing only namespace start events (start-ns):

>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
...     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...     xmlns:owl="http://www.w3.org/2002/07/owl#"
...     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
...     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
...     xmlns="http://dbpedia.org/ontology/">
... 
...     <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
...         <rdfs:label xml:lang="en">basketball league</rdfs:label>
...         <rdfs:comment xml:lang="en">
...           a group of sports teams that compete against each other
...           in Basketball
...         </rdfs:comment>
...     </owl:Class>
... 
... </rdf:RDF>'''
>>> my_namespaces = dict([
...     node for _, node in ElementTree.iterparse(
...         StringIO(my_schema), events=['start-ns']
...     )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
 'owl': 'http://www.w3.org/2002/07/owl#',
 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
 'xsd': 'http://www.w3.org/2001/XMLSchema#'}

Then the dictionary can be passed as argument to the search functions:

root.findall('owl:Class', my_namespaces)

Performing a Stress Test on Web Application?

For simple usage, I perfer ab(apache benchmark) and siege, later one is needed as ab don't support cookie and would create endless sessions from dynamic site.

both are simple to start:

ab -c n -t 30 url

siege -b -c n -t 30s url

siege can run with more urls.

last siege version turn verbose on in siegerc, which is annoy. you can only disable it by edit that file(/usr/local/etc/siegerc).

css absolute position won't work with margin-left:auto margin-right: auto

if the absolute element has a width,you can use the code below

.divtagABS{
    width:300px;
    positon:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

How to register ASP.NET 2.0 to web server(IIS7)?

ASP .NET 2.0:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir

ASP .NET 4.0:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

Run Command Prompt as Administrator to avoid the ...requested operation requires elevation error


aspnet_regiis.exe should no longer be used with IIS7 to install ASP.NET

  1. Open Control Panel
  2. Programs\Turn Windows Features on or off
  3. Internet Information Services
  4. World Wide Web Services
  5. Application development Features
  6. ASP.Net <== check mark here

Jquery, checking if a value exists in array or not

If you want to do it using .map() or just want to know how it works you can do it like this:

var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.

Pointer vs. Reference

A reference is an implicit pointer. Basically you can change the value the reference points to but you can't change the reference to point to something else. So my 2 cents is that if you only want to change the value of a parameter pass it as a reference but if you need to change the parameter to point to a different object pass it using a pointer.

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

How are parameters sent in an HTTP POST request?

Short answer: in POST requests, values are sent in the "body" of the request. With web-forms they are most likely sent with a media type of application/x-www-form-urlencoded or multipart/form-data. Programming languages or frameworks which have been designed to handle web-requests usually do "The Right Thing™" with such requests and provide you with easy access to the readily decoded values (like $_REQUEST or $_POST in PHP, or cgi.FieldStorage(), flask.request.form in Python).


Now let's digress a bit, which may help understand the difference ;)

The difference between GET and POST requests are largely semantic. They are also "used" differently, which explains the difference in how values are passed.

GET (relevant RFC section)

When executing a GET request, you ask the server for one, or a set of entities. To allow the client to filter the result, it can use the so called "query string" of the URL. The query string is the part after the ?. This is part of the URI syntax.

So, from the point of view of your application code (the part which receives the request), you will need to inspect the URI query part to gain access to these values.

Note that the keys and values are part of the URI. Browsers may impose a limit on URI length. The HTTP standard states that there is no limit. But at the time of this writing, most browsers do limit the URIs (I don't have specific values). GET requests should never be used to submit new information to the server. Especially not larger documents. That's where you should use POST or PUT.

POST (relevant RFC section)

When executing a POST request, the client is actually submitting a new document to the remote host. So, a query string does not (semantically) make sense. Which is why you don't have access to them in your application code.

POST is a little bit more complex (and way more flexible):

When receiving a POST request, you should always expect a "payload", or, in HTTP terms: a message body. The message body in itself is pretty useless, as there is no standard (as far as I can tell. Maybe application/octet-stream?) format. The body format is defined by the Content-Type header. When using a HTML FORM element with method="POST", this is usually application/x-www-form-urlencoded. Another very common type is multipart/form-data if you use file uploads. But it could be anything, ranging from text/plain, over application/json or even a custom application/octet-stream.

In any case, if a POST request is made with a Content-Type which cannot be handled by the application, it should return a 415 status-code.

Most programming languages (and/or web-frameworks) offer a way to de/encode the message body from/to the most common types (like application/x-www-form-urlencoded, multipart/form-data or application/json). So that's easy. Custom types require potentially a bit more work.

Using a standard HTML form encoded document as example, the application should perform the following steps:

  1. Read the Content-Type field
  2. If the value is not one of the supported media-types, then return a response with a 415 status code
  3. otherwise, decode the values from the message body.

Again, languages like PHP, or web-frameworks for other popular languages will probably handle this for you. The exception to this is the 415 error. No framework can predict which content-types your application chooses to support and/or not support. This is up to you.

PUT (relevant RFC section)

A PUT request is pretty much handled in the exact same way as a POST request. The big difference is that a POST request is supposed to let the server decide how to (and if at all) create a new resource. Historically (from the now obsolete RFC2616 it was to create a new resource as a "subordinate" (child) of the URI where the request was sent to).

A PUT request in contrast is supposed to "deposit" a resource exactly at that URI, and with exactly that content. No more, no less. The idea is that the client is responsible to craft the complete resource before "PUTting" it. The server should accept it as-is on the given URL.

As a consequence, a POST request is usually not used to replace an existing resource. A PUT request can do both create and replace.

Side-Note

There are also "path parameters" which can be used to send additional data to the remote, but they are so uncommon, that I won't go into too much detail here. But, for reference, here is an excerpt from the RFC:

Aside from dot-segments in hierarchical paths, a path segment is considered opaque by the generic syntax. URI producing applications often use the reserved characters allowed in a segment to delimit scheme-specific or dereference-handler-specific subcomponents. For example, the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes. For example, one URI producer might use a segment such as "name;v=1.1" to indicate a reference to version 1.1 of "name", whereas another might use a segment such as "name,1.1" to indicate the same. Parameter types may be defined by scheme-specific semantics, but in most cases the syntax of a parameter is specific to the implementation of the URIs dereferencing algorithm.

How can I add JAR files to the web-inf/lib folder in Eclipse?

Check under project properties -> deployment assembly if jar file are under deployed path- WEB-INF/lib if not use add button and add jar under WEB-INF/lib

sometime eclipse (in my case Juno Service Release 2 ) was not doing it for me so i did manually. this worked for me.

Parse a URI String into Name-Value Collection

PLAIN Java 11

Given the URL to analyse:

URL url = new URL("https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback");

This solution collects a list of pairs:

List<Map.Entry<String, String>> list = Pattern.compile("&")
   .splitAsStream(url.getQuery())
   .map(s -> Arrays.copyOf(s.split("=", 2), 2))
   .map(o -> Map.entry(decode(o[0]), decode(o[1])))
   .collect(Collectors.toList());

This solution on the other hand collects a map (given that in a url there can be more parameters with same name but different values).

Map<String, List<String>> list = Pattern.compile("&")
   .splitAsStream(url.getQuery())
   .map(s -> Arrays.copyOf(s.split("=", 2), 2))
   .collect(groupingBy(s -> decode(s[0]), mapping(s -> decode(s[1]), toList())));

Both the solutions must use an utility function to properly decode the parameters.

private static String decode(final String encoded) {
    return Optional.ofNullable(encoded)
                   .map(e -> URLDecoder.decode(e, StandardCharsets.UTF_8))
                   .orElse(null);
}

How do I create a new user in a SQL Azure database?

I use the Azure Management console tool of CodePlex, with a very useful GUI, try it. You can save type some code.

How to make join queries using Sequelize on Node.js

In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster

UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

How to pattern match using regular expression in Scala?

Since version 2.10, one can use Scala's string interpolation feature:

implicit class RegexOps(sc: StringContext) {
  def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}

scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true

Even better one can bind regular expression groups:

scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123

scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25

It is also possible to set more detailed binding mechanisms:

scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler

scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20

scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive

scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10

An impressive example on what's possible with Dynamic is shown in the blog post Introduction to Type Dynamic:

object T {

  class RegexpExtractor(params: List[String]) {
    def unapplySeq(str: String) =
      params.headOption flatMap (_.r unapplySeq str)
  }

  class StartsWithExtractor(params: List[String]) {
    def unapply(str: String) =
      params.headOption filter (str startsWith _) map (_ => str)
  }

  class MapExtractor(keys: List[String]) {
    def unapplySeq[T](map: Map[String, T]) =
      Some(keys.map(map get _))
  }

  import scala.language.dynamics

  class ExtractorParams(params: List[String]) extends Dynamic {
    val Map = new MapExtractor(params)
    val StartsWith = new StartsWithExtractor(params)
    val Regexp = new RegexpExtractor(params)

    def selectDynamic(name: String) =
      new ExtractorParams(params :+ name)
  }

  object p extends ExtractorParams(Nil)

  Map("firstName" -> "John", "lastName" -> "Doe") match {
    case p.firstName.lastName.Map(
          Some(p.Jo.StartsWith(fn)),
          Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
      println(s"Match! $fn ...$lastChar")
    case _ => println("nope")
  }
}

How to extract the hostname portion of a URL in JavaScript

Try

document.location.host

or

document.location.hostname

Listening for variable changes in JavaScript

Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var myVar = 123;_x000D_
_x000D_
Object.defineProperty(this, 'varWatch', {_x000D_
  get: function () { return myVar; },_x000D_
  set: function (v) {_x000D_
    myVar = v;_x000D_
    print('Value changed! New value: ' + v);_x000D_
  }_x000D_
});_x000D_
_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Other example

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var varw = (function (context) {_x000D_
  return function (varName, varValue) {_x000D_
    var value = varValue;_x000D_
  _x000D_
    Object.defineProperty(context, varName, {_x000D_
      get: function () { return value; },_x000D_
      set: function (v) {_x000D_
        value = v;_x000D_
        print('Value changed! New value: ' + value);_x000D_
      }_x000D_
    });_x000D_
  };_x000D_
})(window);_x000D_
_x000D_
varw('varWatch'); // Declare_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);_x000D_
_x000D_
print('---');_x000D_
_x000D_
varw('otherVarWatch', 123); // Declare with initial value_x000D_
print(otherVarWatch);_x000D_
otherVarWatch = 789;_x000D_
print(otherVarWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Filter Java Stream to 1 and only 1 element

Use Guava's MoreCollectors.onlyElement() (JavaDoc).

It does what you want and throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

User match =
    users.stream().filter((user) -> user.getId() < 0).collect(onlyElement());

Where to put Gradle configuration (i.e. credentials) that should not be committed?

If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.

  1. Put defaults in gradle.properties
  2. Each developer overrides with gradle-local.properties ( this should be git ignored ).

This is better than overriding using $USER_HOME/.gradle/gradle.properties because different projects might have same property names.

How to validate a date?

I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

Se post HERE

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Mac SQLite editor

I am using simple tool for basic sqlite operation called Lita

This tool is based on Adobe Air so that must be installed prior to use of Lita. Adobe air can be downloaded for free from Adobe site.

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

How can I display an image from a file in Jupyter Notebook?

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

__FILE__ macro shows full path

Here is a portable function that works for both Linux (path '/') and Windows (mix of '\' and '/').
Compiles with gcc, clang and vs.

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

const char* GetFileName(const char *path)
{
    const char *name = NULL, *tmp = NULL;
    if (path && *path) {
        name = strrchr(path, '/');
        tmp = strrchr(path, '\\');
        if (tmp) {
             return name && name > tmp ? name + 1 : tmp + 1;
        }
    }
    return name ? name + 1 : path;
}

int main() {
    const char *name = NULL, *path = NULL;

    path = __FILE__;
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path ="/tmp/device.log";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:\\Downloads\\crisis.avi";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:\\Downloads/nda.pdf";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:/Downloads\\word.doc";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = NULL;
    name = GetFileName(NULL);
    printf("path: %s, filename: %s\n", path, name);

    path = "";
    name = GetFileName("");
    printf("path: %s, filename: %s\n", path, name);

    return 0;
}

Standard output:

path: test.c, filename: test.c
path: /tmp/device.log, filename: device.log
path: C:\Downloads\crisis.avi, filename: crisis.avi
path: C:\Downloads/nda.pdf, filename: nda.pdf
path: C:/Downloads\word.doc, filename: word.doc
path: (null), filename: (null)
path: , filename: 

How can I find the latitude and longitude from address?

An answer to Kandha problem above :

It throws the "java.io.IOException service not available" i already gave those permission and include the library...i can get map view...it throws that IOException at geocoder...

I just added a catch IOException after the try and it solved the problem

    catch(IOException ioEx){
        return null;
    }

DataTable, How to conditionally delete rows

Extension method based on Linq

public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
    foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
        row.Delete();
}

Then use:

DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");

Interesting 'takes exactly 1 argument (2 given)' Python error

Summary (Some examples of how to define methods in classes in python)

#!/usr/bin/env python   # (if running from bash)

class Class1(object):

    def A(self, arg1):
        print arg1
        # this method requires an instance of Class1   
        # can access self.variable_name, and other methods in Class1

    @classmethod
    def B(cls, arg1):
        cls.C(arg1)
        # can access methods B and C in Class1 

    @staticmethod
    def C(arg1):
        print arg1
        # can access methods B and C in Class1 
        # (i.e. via Class1.B(...) and Class1.C(...))

Example

my_obj=Class1()

my_obj.A("1")
# Class1.A("2") # TypeError: method A() must be called with Class1 instance

my_obj.B("3")
Class1.B("4")
my_obj.C("5")
Class1.C("6")`

How do I capture all of my compiler's output to a file?

The compiler warnings happen on stderr, not stdout, which is why you don't see them when you just redirect make somewhere else. Instead, try this if you're using Bash:

$ make &> results.txt

The & means "redirect stdout and stderr to this location". Other shells often have similar constructs.

How to capitalize the first letter of text in a TextView in an Android Application

StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));  
return sb.toString();