Programs & Examples On #Kinect

Microsoft's Kinect is a motion sensing input device for the Xbox 360, Xbox One and PCs. Combining video and depth cameras, the Kinect allows developers to create a touchless and immersive user experience through voice, movement and gesture control.

Cannot open Windows.h in Microsoft Visual Studio

If you already haven't done it, try adding "SDK Path\Include" to:

Project ? Preferences ? C/C++ ? General ? Additional Include Directories

And add "SDK Path\Lib" to:

Project ? Preferences ? Linker ? General ? Additional Library Directories

Also, try to change "Windows.h" to <windows.h>

If won't help, check the physical existence of the file, it should be in "\VC\PlatformSDK\Include" folder in your Visual Studio install directory.

How to set a hidden value in Razor

While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.

@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)

How can I compare two time strings in the format HH:MM:SS?

I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.

function compareDateTimes() {
    //date format ex "04/20/2017 01:30PM"
    //the problem is that this format results in Invalid Date
    //var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date

    var start_date = $(".letter #depo_arrival_time").val();
    var end_date = $(".letter #depo_dateandtime").val();

    if (start_date=="" || end_date=="") {
        return;
    }
    //break it up for processing
    var d1 = stringToDate(start_date);
    var d2 = stringToDate(end_date);

    var diff = d2.getTime() - d1.getTime();
    if (diff < 0) {
        end_date = moment(d2).format("MM/DD/YYYY hh:mA");
        $(".letter #depo_arrival_time").val(end_date);
    }
}

function stringToDate(the_date) {
    var arrDate = the_date.split(" ");
    var the_date = arrDate[0];
    var the_time = arrDate[1];
    var arrTime = the_time.split(":");
    var blnPM = (arrTime[1].indexOf("PM") > -1);
    //first fix the hour
    if (blnPM) {
        if (arrTime[0].indexOf("0")==0) {
            var clean_hour = arrTime[0].substr(1,1);
            arrTime[0] = Number(clean_hour) + 12;
        }
        arrTime[1] = arrTime[1].replace("PM", ":00");
    } else {
        arrTime[1] = arrTime[1].replace("AM", ":00");
    }
    var date_object =  new Date(the_date);
    //now replace the time
    date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
    date_object =  new Date(date_object);

    return date_object;
}

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.

Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.

You can set some value which is present in the parent table and then adding foreign key worked for me.

How to draw checkbox or tick mark in GitHub Markdown table?

I used &#9744; (☐) for [ ] and &#9745; (☑) for [x] and it works for marked.js which says it is compatible with Github markdown. I based my solution on answers for this question. See also this informative answer.

Update: I should have mentioned that when you do it this way, you do not need the <ul>, e.g:

| Unchecked | Checked |
| --------- | ------- |
| &#9744;   | &#9745; |

How to deploy a war file in Tomcat 7

I followed the instruction in the following link, it works for me. http://www.coderanch.com/t/487178/Tomcat/war-file-show-load

  1. Stop Tomcat

  2. Delete all the logs in tomcat/logs and all files in tomcat/conf/Catalina/localhost

  3. Remove the war file and the directory it created (if it did) from tomact/webapps

  4. Start Tomcat

  5. While watching the logs, copy the war file to the webapps directory again

After this, keep an eye on the catalina.xxxx-xx-xx.log to find out the issue.

open() in Python does not create a file if it doesn't exist

I think it's r+, not rw. I'm just a starter, and that's what I've seen in the documentation.

Add onclick event to newly added element in JavaScript

JQuery:

elemm.attr("onclick", "yourFunction(this)");

or:

elemm.attr("onclick", "alert('Hi!')");

Tools: replace not replacing in Android manifest

The following hack works:

  1. add the xmlns:tools="http://schemas.android.com/tools" line in the manifest tag
  2. add tools:replace="android:icon,android:theme,android:allowBackup,label" in the application tag

How can one see the structure of a table in SQLite?

You can query sqlite_master

SELECT sql FROM sqlite_master WHERE name='foo';

which will return a create table SQL statement, for example:

$ sqlite3 mydb.sqlite
sqlite> create table foo (id int primary key, name varchar(10));
sqlite> select sql from sqlite_master where name='foo';
CREATE TABLE foo (id int primary key, name varchar(10))

sqlite> .schema foo
CREATE TABLE foo (id int primary key, name varchar(10));

sqlite> pragma table_info(foo)
0|id|int|0||1
1|name|varchar(10)|0||0

Numpy Resize/Rescale Image

import cv2
import numpy as np

image_read = cv2.imread('filename.jpg',0) 
original_image = np.asarray(image_read)
width , height = 452,452
resize_image = np.zeros(shape=(width,height))

for W in range(width):
    for H in range(height):
        new_width = int( W * original_image.shape[0] / width )
        new_height = int( H * original_image.shape[1] / height )
        resize_image[W][H] = original_image[new_width][new_height]

print("Resized image size : " , resize_image.shape)

cv2.imshow(resize_image)
cv2.waitKey(0)

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

let me as a thank you to the StackOverflow community, share something nice with you, where I have used the above example in Android code for HTTP calls, which now turns MODAL instead of the usual extra thread and the complexities of merging the threads by use of the a bit peculiar threading. (This is working in our app right now - 15 Oct 2020)

public JSONArray genericHttpModal(Context context, final String url, final JSONObject request) {

    this.url = url;    
    genericHttpRequestQueue = Volley.newRequestQueue(context);      
    class MyJsonReturn {
        JSONArray returnJsonArray;

        public void set(JSONArray i) {
            returnJsonArray = i;
        }

        public void set(String i) {
            try {
                returnJsonArray.put(0, i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public JSONArray get() {
            return returnJsonArray;
        }
    }

    final MyJsonReturn mymy = new MyJsonReturn();

    // Positive Response / HTTP OK.
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            throw new RuntimeException();
        }
    };

    final Response.Listener responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                mymy.set(new JSONArray(response));
            } catch (JSONException e) {
                mymy.set("[{\"JSONException:\"" + e.getMessage() + "\"}]");
            }
            handler.sendMessage(handler.obtainMessage());
        }
    };

    // Negative Response / HTTP NOT OK
    final Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            result = "fail";

            try {
                mymy.set(new JSONArray("[{\"JSONException:\"" + result + "\"}]"));
            } catch (JSONException e) {
                mymy.set("[{\"JSONException:\"" + e.getMessage() + "\"}]");
            }
            handler.sendMessage(handler.obtainMessage());
        }
    };


    final StringRequest httpRequest = new StringRequest(Request.Method.POST, URL_POINTER + url,
            responseListener,
            errorListener) {

        // Here the mRequestQueue handler will get the parameters for this request here.
        // Ref: https://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body#33578202
        // Ref: Multi Threaded solution 14 Oct 2020 (David Svarrer) : https://stackoverflow.com/questions/2028697/dialogs-alertdialogs-how-to-block-execution-while-dialog-is-up-net-style (This stackoverflow here)
        @Override
        protected java.util.Map<String, String> getParams() throws AuthFailureError {
            return jsonObjectToMap(request);
        }
    };
    httpRequest.setShouldCache(false); // Elijah: Could work on dropping the cache !!!
    genericHttpRequestQueue.add(httpRequest);    

    try {
        Looper.loop();
    } catch (RuntimeException re) {
    }
    return mymy.get();
}

How to use the unsigned Integer in Java 8 and Java 9?

There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:

static long values = Long.parseUnsignedLong("123456789012345678");

but this is not declaration of the variable.

How to change the size of the radio button using CSS?

Resizing the default widget doesn’t work in all browsers, but you can make custom radio buttons with JavaScript. One of the ways is to create hidden radio buttons and then place your own images on your page. Clicking on these images changes the images (replaces the clicked image with an image with a radio button in a selected state and replaces the other images with radio buttons in an unselected state) and selects the new radio button.

Anyway, there is documentation on this subject. For example, read this: Styling Checkboxes and Radio Buttons with CSS and JavaScript.

How to check if a file contains a specific string using Bash

grep -q [PATTERN] [FILE] && echo $?

The exit status is 0 (true) if the pattern was found; otherwise blankstring.

What is the difference between SAX and DOM?

I will provide general Q&A-oriented answer for this question:

Answer to Questions

Why do we need XML parser?

We need XML parser because we do not want to do everything in our application from scratch, and we need some "helper" programs or libraries to do something very low-level but very necessary to us. These low-level but necessary things include checking the well-formedness, validating the document against its DTD or schema (just for validating parsers), resolving character reference, understanding CDATA sections, and so on. XML parsers are just such "helper" programs and they will do all these jobs. With XML parser, we are shielded from a lot of these complexities and we could concentrate ourselves on just programming at high-level through the API's implemented by the parsers, and thus gain programming efficiency.

Which one is better, SAX or DOM ?

Both SAX and DOM parser have their advantages and disadvantages. Which one is better should depend on the characteristics of your application (please refer to some questions below).

Which parser can get better speed, DOM or SAX parsers?

SAX parser can get better speed.

What's the difference between tree-based API and event-based API?

A tree-based API is centered around a tree structure and therefore provides interfaces on components of a tree (which is a DOM document) such as Document interface,Node interface, NodeList interface, Element interface, Attr interface and so on. By contrast, however, an event-based API provides interfaces on handlers. There are four handler interfaces, ContentHandler interface, DTDHandler interface, EntityResolver interface and ErrorHandler interface.

What is the difference between a DOM Parser and a SAX Parser?

DOM parsers and SAX parsers work in different ways:

  • A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document. A

  • DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time.

  • With DOM parser, method calls in client application have to be explicit and forms a kind of chain. But with SAX, some certain methods (usually overriden by the cient) will be invoked automatically (implicitly) in a way which is called "callback" when some certain events occur. These methods do not have to be called explicitly by the client, though we could call them explicitly.

How do we decide on which parser is good?

Ideally a good parser should be fast (time efficient),space efficient, rich in functionality and easy to use. But in reality, none of the main parsers have all these features at the same time. For example, a DOM Parser is rich in functionality (because it creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree), but it is space inefficient when the document is huge, and it takes a little bit long to learn how to work with it. A SAX Parser, however, is much more space efficient in case of big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM Parser because its API is really simple. But from the functionality point of view, it provides less functions which mean that the users themselves have to take care of more, such as creating their own data structures. By the way, what is a good parser? I think the answer really depends on the characteristics of your application.

What are some real world applications where using SAX parser is advantageous than using DOM parser and vice versa? What are the usual application for a DOM parser and for a SAX parser?

In the following cases, using SAX parser is advantageous than using DOM parser.

  • The input document is too big for available memory (actually in this case SAX is your only choice)
  • You can process the document in small contiguous chunks of input. You do not need the entire document before you can do useful work
  • You just want to use the parser to extract the information of interest, and all your computation will be completely based on the data structures created by yourself. Actually in most of our applications, we create data structures of our own which are usually not as complicated as the DOM tree. From this sense, I think, the chance of using a DOM parser is less than that of using a SAX parser.

In the following cases, using DOM parser is advantageous than using SAX parser.

  • Your application needs to access widely separately parts of the document at the same time.
  • Your application may probably use a internal data structure which is almost as complicated as the document itself.
  • Your application has to modify the document repeatedly.
  • Your application has to store the document for a significant amount of time through many method calls.

Example (Use a DOM parser or a SAX parser?):

Assume that an instructor has an XML document containing all the personal information of the students as well as the points his students made in his class, and he is now assigning final grades for the students using an application. What he wants to produce, is a list with the SSN and the grades. Also we assume that in his application, the instructor use no data structure such as arrays to store the student personal information and the points. If the instructor decides to give A's to those who earned the class average or above, and give B's to the others, then he'd better to use a DOM parser in his application. The reason is that he has no way to know how much is the class average before the entire document gets processed. What he probably need to do in his application, is first to look through all the students' points and compute the average, and then look through the document again and assign the final grade to each student by comparing the points he earned to the class average. If, however, the instructor adopts such a grading policy that the students who got 90 points or more, are assigned A's and the others are assigned B's, then probably he'd better use a SAX parser. The reason is, to assign each student a final grade, he do not need to wait for the entire document to be processed. He could immediately assign a grade to a student once the SAX parser reads the grade of this student. In the above analysis, we assumed that the instructor created no data structure of his own. What if he creates his own data structure, such as an array of strings to store the SSN and an array of integers to sto re the points ? In this case, I think SAX is a better choice, before this could save both memory and time as well, yet get the job done. Well, one more consideration on this example. What if what the instructor wants to do is not to print a list, but to save the original document back with the grade of each student updated ? In this case, a DOM parser should be a better choice no matter what grading policy he is adopting. He does not need to create any data structure of his own. What he needs to do is to first modify the DOM tree (i.e., set value to the 'grade' node) and then save the whole modified tree. If he choose to use a SAX parser instead of a DOM parser, then in this case he has to create a data structure which is almost as complicated as a DOM tree before he could get the job done.

An Example

Problem statement: Write a Java program to extract all the information about circles which are elements in a given XML document. We assume that each circle element has three child elements(i.e., x, y and radius) as well as a color attribute. A sample document is given below:

<?xml version="1.0"?> 
<!DOCTYPE shapes [
<!ELEMENT shapes (circle)*>
<!ELEMENT circle (x,y,radius)>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
<!ELEMENT radius (#PCDATA)>
<!ATTLIST circle color CDATA #IMPLIED>
]>

<shapes> 
          <circle color="BLUE"> 
                <x>20</x>
                <y>20</y>
                <radius>20</radius> 
          </circle>
          <circle color="RED" >
                <x>40</x>
                <y>40</y>
                <radius>20</radius> 
          </circle>
</shapes> 

Program with DOMparser

import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;


public class shapes_DOM {
   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers  
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles 

   public static void main(String[] args) {   

      try{
         // create a DOMParser
         DOMParser parser=new DOMParser();
         parser.parse(args[0]);

         // get the DOM Document object
         Document doc=parser.getDocument();

         // get all the circle nodes
         NodeList nodelist = doc.getElementsByTagName("circle");
         numberOfCircles =  nodelist.getLength();

         // retrieve all info about the circles
         for(int i=0; i<nodelist.getLength(); i++) {

            // get one circle node
            Node node = nodelist.item(i);

            // get the color attribute 
            NamedNodeMap attrs = node.getAttributes();
            if(attrs.getLength() > 0)
               color[i]=(String)attrs.getNamedItem("color").getNodeValue();

            // get the child nodes of a circle node 
            NodeList childnodelist = node.getChildNodes();

            // get the x and y value 
            for(int j=0; j<childnodelist.getLength(); j++) {
               Node childnode = childnodelist.item(j);
               Node textnode = childnode.getFirstChild();//the only text node
               String childnodename=childnode.getNodeName(); 
               if(childnodename.equals("x")) 
                  x[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("y")) 
                  y[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("radius")) 
                  r[i]= Integer.parseInt(textnode.getNodeValue().trim());
            }

         }

         // print the result
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }

      }  catch (Exception e) {e.printStackTrace(System.err);}

    }

}

Program with SAXparser

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;


public class shapes_SAX extends DefaultHandler {

   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles

   static int flagX=0;    //to remember what element has occurred
   static int flagY=0;    //to remember what element has occurred
   static int flagR=0;    //to remember what element has occurred

   // main method 
   public static void main(String[] args) {   
      try{
         shapes_SAX SAXHandler = new shapes_SAX (); // an instance of this class
         SAXParser parser=new SAXParser();          // create a SAXParser object 
         parser.setContentHandler(SAXHandler);      // register with the ContentHandler 
         parser.parse(args[0]);
      }  catch (Exception e) {e.printStackTrace(System.err);}  // catch exeptions
   }

   // override the startElement() method
   public void startElement(String uri, String localName, 
                       String rawName, Attributes attributes) {
         if(rawName.equals("circle"))                      // if a circle element is seen
            color[numberOfCircles]=attributes.getValue("color");  // get the color attribute 

         else if(rawName.equals("x"))      // if a x element is seen set the flag as 1 
            flagX=1;
         else if(rawName.equals("y"))      // if a y element is seen set the flag as 2
            flagY=1;
         else if(rawName.equals("radius")) // if a radius element is seen set the flag as 3 
            flagR=1;
   }

   // override the endElement() method
   public void endElement(String uri, String localName, String rawName) {
         // in this example we do not need to do anything else here
         if(rawName.equals("circle"))                       // if a circle element is ended 
            numberOfCircles +=  1;                          // increment the counter 
   }

   // override the characters() method
   public void characters(char characters[], int start, int length) {
         String characterData = 
             (new String(characters,start,length)).trim(); // get the text

         if(flagX==1) {        // indicate this text is for <x> element 
             x[numberOfCircles] = Integer.parseInt(characterData);
             flagX=0;
         }
         else if(flagY==1) {  // indicate this text is for <y> element 
             y[numberOfCircles] = Integer.parseInt(characterData);
             flagY=0;
         }
         else if(flagR==1) {  // indicate this text is for <radius> element 
             r[numberOfCircles] = Integer.parseInt(characterData);
             flagR=0;
         }
   }

   // override the endDocument() method
   public void endDocument() {
         // when the end of document is seen, just print the circle info 
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }
   }


}

document.getElementById vs jQuery $()

jQuery is built over JavaScript. This means that it's just javascript anyway.

document.getElementById()

The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.

Jquery $()

Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.

convert datetime to date format dd/mm/yyyy

If you want the string use -

DateTime.ToString("dd/MM/yyyy")

Http Get using Android HttpURLConnection

Try getting the input stream from this you can then get the text data as so:-

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://www.mysite.se/index.asp?data=99");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }    
    }

You can probably use other inputstream readers such as buffered reader also.

The problem is that when you open the connection - it does not 'pull' any data.

Change Active Menu Item on Page Scroll?

If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

The Concat method will return an object which implements IEnumerable<T> by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList() on Cat and use the resulting List<T> (which will represent a snapshot of the contents of A and B).

Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.

How can I reconcile detached HEAD with master/origin?

If you did some commits on top of master and just want to "backwards merge" master there (i.e. you want master to point to HEAD), the one-liner would be:

git checkout -B master HEAD
  1. That creates a new branch named master, even if it exists already (which is like moving master and that's what we want).
  2. The newly created branch is set to point to HEAD, which is where you are.
  3. The new branch is checked out, so you are on master afterwards.

I found this especially useful in the case of sub-repositories, which also happen to be in a detached state rather often.

How can I get current location from user in iOS

You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first:

/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/

You also need to escape the other regular expression metacharacters.

Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this:

/[$-/:-?{-~!"^_`\[\]]/

There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[].

Use an ACSII table to find ranges for character classes.

How do I restart my C# WinForm Application?

How about create a bat file, run the batch file before closing, and then close the current instance.

The batch file does this:

  1. wait in a loop to check whether the process has exited.
  2. start the process.

Numeric for loop in Django templates

You should use "slice" in template, a example like this:

in views.py

contexts = {
    'ALL_STORES': Store.objects.all(),
}

return render_to_response('store_list.html', contexts, RequestContext(request, processors=[custom_processor]))

in store_list.html:

<ul>
{% for store in ALL_STORES|slice:":10" %}
    <li class="store_item">{{ store.name }}</li>
{% endfor %}
</ul>

Laravel 4: how to run a raw SQL?

Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to find the kafka version in linux

To check kafka version :

cd /usr/hdp/current/kafka-broker/libs
ls kafka_*.jar

cannot load such file -- bundler/setup (LoadError)

You can try to run:

bundle exec rake rails:update:bin

As @Dinesh mentioned in Rails 5:

rails app:update:bin

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

For those of you experiencing this error on Windows using Task Manager end the instance of "mongod.exe" that is running. Once that is done permanently delete the mongo.lock file and run mongod.exe. It should work perfectly after that.

Python POST binary data

you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):

request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Filter array to have unique values

Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:

Array.from(new Set(arrayOfNonUniqueValues));

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Return value A new Set object.

Array.from()

The Array.from() method creates a new Array instance from an array-like or iterable object.

Return value A new Array instance.

Example Code:

_x000D_
_x000D_
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
_x000D_
_x000D_

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

convert string array to string

    string ConvertStringArrayToString(string[] array)
    {
        //
        // Concatenate all the elements into a StringBuilder.
        //
        StringBuilder strinbuilder = new StringBuilder();
        foreach (string value in array)
        {
            strinbuilder.Append(value);
            strinbuilder.Append(' ');
        }
        return strinbuilder.ToString();
    }

How should I copy Strings in Java?

String str1="this is a string";
String str2=str1.clone();

How about copy like this? I think to get a new copy is better, so that the data of str1 won't be affected when str2 is reference and modified in futher action.

Which are more performant, CTE or temporary tables?

So the query I was assigned to optimize was written with two CTEs in SQL server. It was taking 28sec.

I spent two minutes converting them to temp tables and the query took 3 seconds

I added an index to the temp table on the field it was being joined on and got it down to 2 seconds

Three minutes of work and now its running 12x faster all by removing CTE. I personally will not use CTEs ever they are tougher to debug as well.

The crazy thing is the CTEs were both only used once and still putting an index on them proved to be 50% faster.

How can I play sound in Java?

For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().

What worked for me was the following:

void playSound(String soundFile) {
    File f = new File("./" + soundFile);
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
    Clip clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();
}

And I would play the sound with:

 playSound("sounds/effects/sheep1.wav");

sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).

How do I mock an autowired @Value field in Spring with Mockito?

I used the below code and it worked for me:

@InjectMocks
private ClassABC classABC;

@Before
public void setUp() {
    ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}

Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/

Change the borderColor of the TextBox

This is an ultimate solution to set the border color of a TextBox:

public class BorderedTextBox : UserControl
{
    TextBox textBox;

    public BorderedTextBox()
    {
        textBox = new TextBox()
        {
            BorderStyle = BorderStyle.FixedSingle,
            Location = new Point(-1, -1),
            Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                     AnchorStyles.Left | AnchorStyles.Right
        };
        Control container = new ContainerControl()
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(-1)
        };
        container.Controls.Add(textBox);
        this.Controls.Add(container);

        DefaultBorderColor = SystemColors.ControlDark;
        FocusedBorderColor = Color.Red;
        BackColor = DefaultBorderColor;
        Padding = new Padding(1);
        Size = textBox.Size;
    }

    public Color DefaultBorderColor { get; set; }
    public Color FocusedBorderColor { get; set; }

    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }

    protected override void OnEnter(EventArgs e)
    {
        BackColor = FocusedBorderColor;
        base.OnEnter(e);
    }

    protected override void OnLeave(EventArgs e)
    {
        BackColor = DefaultBorderColor;
        base.OnLeave(e);
    }

    protected override void SetBoundsCore(int x, int y,
        int width, int height, BoundsSpecified specified)
    {
        base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
    }
}

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

Is there a method to generate a UUID with go language

The gorand package has a UUID method that returns a Version 4 (randomly generated) UUID in its canonical string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") and it's RFC 4122 compliant.

It also uses the crypto/rand package to ensure the most cryptographically secure generation of UUIDs across all platforms supported by Go.

import "github.com/leonelquinteros/gorand"

func main() {
    uuid, err := gorand.UUID()
    if err != nil {
        panic(err.Error())
    }

    println(uuid)
} 

Install php-mcrypt on CentOS 6

If you want to recompile PHP with mcrypt enable.

1. Insatll mcrypt. libmcrypt-devel is from Third Party Repositories EPEL, so you should:

yum --enablerepo=extras install epel-release
yum install libmcrypt-devel

2. Append --with-mcrypt to your ./configure arguments:

./configure --with-mcrypt

3. Build and install:

make & make install

How to fire an event on class change using jQuery?

Use trigger to fire your own event. When ever you change class add trigger with name

JS Fiddle DEMO

$("#main").on('click', function () {
    $("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});

$('#chld').on('cssFontSet', function () {

    alert("Red bg set ");
});

Learn jQuery: Simple and easy jQuery tutorials blog

How get value from URL

You can get that value by using the $_GET array. So the id value would be stored in $_GET['id'].

So in your case you could store that value in the $id variable as follows:

$id = $_GET['id'];

Getting the last revision number in SVN?

<?php
    $url = 'your repository here';
    $output = `svn info $url`;
    echo "<pre>$output</pre>";
?>

You can get the output in XML like so:

$output = `svn info $url --xml`;

If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly:

$output = `svn info $url 2>&1`;

static const vs #define

Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:

  1. enums:

    • only possible for integer values
    • properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
    • strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
    • can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
    • stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
    • each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
    • even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
    • the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
    • you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)

  1. consts:

    • properly scoped / identifier clash issues handled nicely
    • strong, single, user-specified type
      • you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
    • One Definition Rule complications
    • can take address, create const references to them etc.
    • most similar to a non-const value, which minimises work and impact if switching between the two
    • value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change

  1. #defines:

    • "global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
      • long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
      • while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
    • more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
      • downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
    • can't use sizeof directly on a defined numeric literal
    • untyped (GCC doesn't warn if compared to unsigned)
    • some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
    • can't take the address
    • the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
    • some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
    • you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
    • substituted text has to be exposed:
      • in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
      • or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)

My personal opinion:

As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

How to get the url parameters using AngularJS

I found solution how to use $location.search() to get parameter from URL

first in URL u need put syntax " # " before parameter like this example

"http://www.example.com/page#?key=value"

and then in your controller u put $location in function and use $location.search() to get URL parameter for

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);

Pentaho Data Integration SQL connection

You need to download mysql-connector-java-5.1.46.tar.gz, not the latest version. The Driver class that Pentaho uses is not included in mysql-connector-java-8.xx.yy versions.

How to dynamic filter options of <select > with jQuery?

Update Lessan's answer to also keep the attributes of the options.

This is my first time answering on Stack Overflow so not sure if I should edit his answer or create my own.

jQuery.fn.allAttr = function() {
  var a, aLength, attributes, map;
  if (!this[0]) return null;
  if (arguments.length === 0) {
    map = {};
    attributes = this[0].attributes;
    aLength = attributes.length;
    for (a = 0; a < aLength; a++) {
      map[attributes[a].name.toLowerCase()] = attributes[a].value;
    }
    return map;
  } else {
    for (var propin arguments[0]) {
      $(this[0]).attr(prop, arguments[0][prop]);
    }
    return this[0];
  }
};


jQuery.fn.filterByText = function(textbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push({ value: $(this).val(), 
        text: $(this).text(), 
        allAttr: $(this).allAttr() });
    });
    $(select).data('options', options);

    $(textbox).bind('change keyup', function() {
      var search = $.trim($(this).val());
      var regex = new RegExp(search, "gi");

      $.each($(select).empty().data('options'), function(i, option) {
        if (option.text.match(regex) !== null) {
          $(select).append(
            $('<option>').text(option.text)
            .val(option.value)
            .allAttr(option.allAttr)
          );
        }
      });
    });
  });
};

How do you detect Credit card type based on number?

public string GetCreditCardType(string CreditCardNumber)
{
    Regex regVisa = new Regex("^4[0-9]{12}(?:[0-9]{3})?$");
    Regex regMaster = new Regex("^5[1-5][0-9]{14}$");
    Regex regExpress = new Regex("^3[47][0-9]{13}$");
    Regex regDiners = new Regex("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");
    Regex regDiscover = new Regex("^6(?:011|5[0-9]{2})[0-9]{12}$");
    Regex regJCB = new Regex("^(?:2131|1800|35\\d{3})\\d{11}$");


    if (regVisa.IsMatch(CreditCardNumber))
        return "VISA";
    else if (regMaster.IsMatch(CreditCardNumber))
        return "MASTER";
    else  if (regExpress.IsMatch(CreditCardNumber))
        return "AEXPRESS";
    else if (regDiners.IsMatch(CreditCardNumber))
        return "DINERS";
    else if (regDiscover.IsMatch(CreditCardNumber))
        return "DISCOVERS";
    else if (regJCB.IsMatch(CreditCardNumber))
        return "JCB";
    else
        return "invalid";
}

Here is the function to check Credit card type using Regex , c#

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Here is an effective solution from didi to solve this problem, Since this bug is very common and difficult to find the cause, It looks more like a system problem, Why can't we ignore it directly?Of course we can ignore it, Here is the sample code:

final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = 
        Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (t.getName().equals("FinalizerWatchdogDaemon") && e instanceof TimeoutException) {
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        }
    }
});

By setting a special default uncaught exception handler, application can change the way in which uncaught exceptions are handled for those threads that would already accept whatever default behavior the system provided. When an uncaught TimeoutException is thrown from a thread named FinalizerWatchdogDaemon, this special handler will block the handler chain, the system handler will not be called, so crash will be avoided.

Through practice, no other bad effects were found. The GC system is still working, timeouts are alleviated as CPU usage decreases.

For more details see: https://mp.weixin.qq.com/s/uFcFYO2GtWWiblotem2bGg

WAMP won't turn green. And the VCRUNTIME140.dll error

VCRUNTIME140.dll error

This error means you don't have required Visual C++ packages installed in your computer. If you have installed wampserver then firstly uninstall wampserver.

Download the VC packages

Download all these VC packages and install all of them. You should install both 64 bit and 32 bit version.

-- VC9 Packages (Visual C++ 2008 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=5582
http://www.microsoft.com/en-us/download/details.aspx?id=2092

-- VC10 Packages (Visual C++ 2010 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=8328
http://www.microsoft.com/en-us/download/details.aspx?id=13523

-- VC11 Packages (Visual C++ 2012 Update 4)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=30679

-- VC13 Packages] (Visual C++ 2013)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
https://www.microsoft.com/en-us/download/details.aspx?id=40784

-- VC14 Packages (Visual C++ 2015)--
The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=48145

install packages with admin priviliges
Right click->Run as Administrator

install wampserver again
After you installed both 64bits and 32 bits version of VC packages then install wampserver again.

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

How to refresh materialized view in oracle

Best option is to use the '?' argument for the method. This way DBMS_MVIEW will choose the best way to refresh, so it'll do the fastest refresh it can for you. , and won't fail if you try something like method=>'f' when you actually need a complete refresh. :-)

from the SQL*Plus prompt:

EXEC DBMS_MVIEW.REFRESH('my_schema.my_mview', method => '?');

How do I scroll to an element within an overflowed Div?

The above answers will position the inner element at the top of the overflow element even if it's in view inside the overflow element. I didn't want that so I modified it to not change the scroll position if the element is in view.

jQuery.fn.scrollTo = function(elem, speed) {
    var $this = jQuery(this);
    var $this_top = $this.offset().top;
    var $this_bottom = $this_top + $this.height();
    var $elem = jQuery(elem);
    var $elem_top = $elem.offset().top;
    var $elem_bottom = $elem_top + $elem.height();

    if ($elem_top > $this_top && $elem_bottom < $this_bottom) {
        // in view so don't do anything
        return;
    }
    var new_scroll_top;
    if ($elem_top < $this_top) {
        new_scroll_top = {scrollTop: $this.scrollTop() - $this_top + $elem_top};
    } else {
        new_scroll_top = {scrollTop: $elem_bottom - $this_bottom + $this.scrollTop()};
    }
    $this.animate(new_scroll_top, speed === undefined ? 100 : speed);
    return this;
};

iOS how to set app icon and launch images

This is a very frustrating part of XCode. Like many, I wasted hours on this when I switched to a newer version of xcode (version 8). The solution for me was to open the properties for my project and under the "App Icons and Launch Images" choose the "migrate" option for the icons. This made absolutely no sense to me as I already had all my icons there, but it worked! Unfortunately I now seem to have two copies of my launcher icons in the project though.

Exception : AAPT2 error: check logs for details

some symbols should be transferred like '%'

<string name="test" formatted="false">95%</string>

What are best practices for multi-language database design?

I find this type of approach works for me:

Product     ProductDetail        Country
=========   ==================   =========
ProductId   ProductDetailId      CountryId
- etc -     ProductId            CountryName
            CountryId            Language
            ProductName          - etc -
            ProductDescription
            - etc -

The ProductDetail table holds all the translations (for product name, description etc..) in the languages you want to support. Depending on your app's requirements, you may wish to break the Country table down to use regional languages too.

List all employee's names and their managers by manager name using an inner join

select a.empno,a.ename,a.job,a.mgr,B.empno,B.ename as MGR_name, B.job as MGR_JOB from 
    emp a, emp B where a.mgr=B.empno ;

PostgreSQL Crosstab Query

Install the additional module tablefunc once per database, which provides the function crosstab(). Since Postgres 9.1 you can use CREATE EXTENSION for that:

CREATE EXTENSION IF NOT EXISTS tablefunc;

Improved test case

CREATE TABLE tbl (
   section   text
 , status    text
 , ct        integer  -- "count" is a reserved word in standard SQL
);

INSERT INTO tbl VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                    , ('C', 'Inactive', 7);  -- ('C', 'Active') is missing

Simple form - not fit for missing attributes

crosstab(text) with 1 input parameter:

SELECT *
FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- needs to be "ORDER BY 1,2" here
   ) AS ct ("Section" text, "Active" int, "Inactive" int);

Returns:

 Section | Active | Inactive
---------+--------+----------
 A       |      1 |        2
 B       |      4 |        5
 C       |      7 |           -- !!
  • No need for casting and renaming.
  • Note the incorrect result for C: the value 7 is filled in for the first column. Sometimes, this behavior is desirable, but not for this use case.
  • The simple form is also limited to exactly three columns in the provided input query: row_name, category, value. There is no room for extra columns like in the 2-parameter alternative below.

Safe form

crosstab(text, text) with 2 input parameters:

SELECT *
FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- could also just be "ORDER BY 1" here

  , $$VALUES ('Active'::text), ('Inactive')$$
   ) AS ct ("Section" text, "Active" int, "Inactive" int);

Returns:

 Section | Active | Inactive
---------+--------+----------
 A       |      1 |        2
 B       |      4 |        5
 C       |        |        7  -- !!
  • Note the correct result for C.

  • The second parameter can be any query that returns one row per attribute matching the order of the column definition at the end. Often you will want to query distinct attributes from the underlying table like this:

    'SELECT DISTINCT attribute FROM tbl ORDER BY 1'
    

    That's in the manual.

    Since you have to spell out all columns in a column definition list anyway (except for pre-defined crosstabN() variants), it is typically more efficient to provide a short list in a VALUES expression like demonstrated:

    $$VALUES ('Active'::text), ('Inactive')$$)
    

    Or (not in the manual):

    $$SELECT unnest('{Active,Inactive}'::text[])$$  -- short syntax for long lists
    
  • I used dollar quoting to make quoting easier.

  • You can even output columns with different data types with crosstab(text, text) - as long as the text representation of the value column is valid input for the target type. This way you might have attributes of different kind and output text, date, numeric etc. for respective attributes. There is a code example at the end of the chapter crosstab(text, text) in the manual.

db<>fiddle here

Advanced examples


\crosstabview in psql

Postgres 9.6 added this meta-command to its default interactive terminal psql. You can run the query you would use as first crosstab() parameter and feed it to \crosstabview (immediately or in the next step). Like:

db=> SELECT section, status, ct FROM tbl \crosstabview

Similar result as above, but it's a representation feature on the client side exclusively. Input rows are treated slightly differently, hence ORDER BY is not required. Details for \crosstabview in the manual. There are more code examples at the bottom of that page.

Related answer on dba.SE by Daniel Vérité (the author of the psql feature):



The previously accepted answer is outdated.

  • The variant of the function crosstab(text, integer) is outdated. The second integer parameter is ignored. I quote the current manual:

    crosstab(text sql, int N) ...

    Obsolete version of crosstab(text). The parameter N is now ignored, since the number of value columns is always determined by the calling query

  • Needless casting and renaming.

  • It fails if a row does not have all attributes. See safe variant with two input parameters above to handle missing attributes properly.

  • ORDER BY is required in the one-parameter form of crosstab(). The manual:

    In practice the SQL query should always specify ORDER BY 1,2 to ensure that the input rows are properly ordered

What to gitignore from the .idea folder?

  • Remove .idea folder

    $rm -R .idea/
    
  • Add rule

    $echo ".idea/*" >> .gitignore
    
  • Commit .gitignore file

    $git commit -am "remove .idea"
    
  • Next commit will be ok

enabling cross-origin resource sharing on IIS7

The 405 response is a "Method not allowed" response. It sounds like your server isn't properly configured to handle CORS preflight requests. You need to do two things:

1) Enable IIS7 to respond to HTTP OPTIONS requests. You are getting the 405 because IIS7 is rejecting the OPTIONS request. I don't know how to do this as I'm not familiar with IIS7, but there are probably others on Stack Overflow who do.

2) Configure your application to respond to CORS preflight requests. You can do this by adding the following two lines underneath the Access-Control-Allow-Origin line in the <customHeaders> section:

<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

You may have to add other values to the Access-Control-Allow-Headers section based on what headers your request is asking for. Do you have the sample code for making a request?

You can learn more about CORS and CORS preflight here: http://www.html5rocks.com/en/tutorials/cors/

Cannot set some HTTP headers when using System.Net.WebRequest

Basically, no. That is an http header, so it is reasonable to cast to HttpWebRequest and set the .Referer (as you indicate in the question):

HttpWebRequest req = ...
req.Referer = "your url";

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

For anyone who may stumble across this thread while trying to fix this same error that results by running Enable-Migrations, chances are none of the solutions above will help you (I tried them all).

I encountered this same issue in Web API 2 after running this in PM console:

Enable-Migrations -EnableAutomaticMigrations -ConnectionString IdentityConnection -ConnectionProviderName System.Data.SqlClient -Force

I fixed it by changing it to actually use the ApplicationDbContext created in IdentityModels.

Enable-Migrations -ContextTypeName ApplicationDbContext -EnableAutomaticMigrations -Force

The interesting thing is not only does this reference the same exact connection string, but the constructor includes code that 4castle said was a potential fix (i.e., the throwIfV1Schema: false suggestion.

Note that the -Force parameter is only being used because the Configuration.cs file already exists.

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

I think you can use display: inline-block on the element you want to center and set text-align: center; on its parent. This definitely center the div on all screen sizes.

Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.

HTML

<div id="container">
    <div id="main">
        <div id="somebackground">
            Hi
        </div>
    </div>
</div>

CSS

#container
{
    text-align: center;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align: left;
    background-color: red;
}

For vertical centering, I "dropped" support for some older browsers in favour of display: table;, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/

Here is the code (again) for completeness:

HTML

<body>
    <div id="table-container">
        <div id="container">
            <div id="main">
                <div id="somebackground">
                    Hi
                </div>
            </div>
        </div>
    </div>
</body>

CSS

body, html
{
    height: 100%;
}
#table-container
{
    display:    table;
    text-align: center;
    width:      100%;
    height:     100%;
}
#container
{
    display:        table-cell;
    vertical-align: middle;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align:       left;
    background-color: red;
}

The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the <video> tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).

The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

How do I remove all non alphanumeric characters from a string except dash?

Here is a non-regex heap allocation friendly fast solution which was what I was looking for.

Unsafe edition.

public static unsafe void ToAlphaNumeric(ref string input)
{
    fixed (char* p = input)
    {
        int offset = 0;
        for (int i = 0; i < input.Length; i++)
        {
            if (char.IsLetterOrDigit(p[i]))
            {
                p[offset] = input[i];
                offset++;
            }
        }
        ((int*)p)[-1] = offset; // Changes the length of the string
        p[offset] = '\0';
    }
}

And for those who don't want to use unsafe or don't trust the string length hack.

public static string ToAlphaNumeric(string input)
{
    int j = 0;
    char[] newCharArr = new char[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsLetterOrDigit(input[i]))
        {
            newCharArr[j] = input[i];
            j++;
        }
    }

    Array.Resize(ref newCharArr, j);

    return new string(newCharArr);
}

No module named _sqlite3

You need to install pysqlite in your python environment:

    $ pip install pysqlite

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

"Untrusted App Developer" message when installing enterprise iOS Application

For iOS 13.6

Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

HTML5 Video not working in IE 11

I know this is old, but here is a additional thing if you still encounter problems with the solution above.

Just put in your <head> :

<meta http-equiv="X-UA-Compatible" content="IE=edge"> 

It will prevent IE to jump back to IE9 compatibility, thus breaking the video function. Worked for me, so if you still have problems, consider checking this out.

Alternatively you can add this in PHP :

header('x-ua-compatible: ie=edge');

Or in a .htaccess file:

header set X-UA-Compatible "IE=Edge"

Ignoring new fields on JSON objects using Jackson

Up to date and complete answer with Jackson 2


Using Annotation

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyMappingClass {

}

See JsonIgnoreProperties on Jackson online documentation.

Using Configuration

Less intrusive than annotation.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ObjectReader objectReader = objectMapper.reader(MyMappingClass.class);
MyMappingClass myMappingClass = objectReader.readValue(json);

See FAIL_ON_UNKNOWN_PROPERTIES on Jackson online documentation.

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

How to search text using php if ($text contains "World")

This might be what you are looking for:

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

Is it?

Or maybe this:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Or even this

<?php
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

You can read all about them in the documentation here:

http://php.net/manual/en/book.strings.php

DataGridView - Focus a specific cell

you can set Focus to a specific Cell by setting Selected property to true

dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;

to avoid Multiple Selection just set

dataGridView1.MultiSelect = false;

asp.net Button OnClick event not firing

Because your button is in control it could be that there is a validation from another control that don't allow the button to submit. The result in my case was to add CausesValidation property to the button:

<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" CausesValidation="False"/> 

Is either GET or POST more secure than the other?

It is harder to alter a POST request (it requires more effort than editing the query string). Edit: In other words, it's only security by obscurity, and barely that.

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to determine if object is in array

This function is to check for a unique field. Arg 1: the array with selected data Arg 2: key to check Arg 3: value that must be "validated"

function objectUnique( array, field, value )
{
    var unique = true;
    array.forEach(function ( entry )
    {
        if ( entry[field] == value )
        {
            unique = false;
        }
    });

    return unique;
}

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

CSS /JS to prevent dragging of ghost image?

For Firefox you need to go a little deeper with this:

var imgs = document.getElementsByTagName('img');

    // loop through fetched images
    for (i = 0; i < imgs.length; i++) {
        // and define onmousedown event handler
        imgs[i].onmousedown = disableDragging;
    }

function disableDragging(e) {
        e.preventDefault();
    }

Enjoy.

Java: Date from unix timestamp

tl;dr

Instant.ofEpochSecond( 1_280_512_800L )

2010-07-30T18:00:00Z

java.time

The new java.time framework built into Java 8 and later is the successor to Joda-Time.

These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.

Instant instant = Instant.ofEpochSecond( 1_280_512_800L );

instant.toString(): 2010-07-30T18:00:00Z

See that code run live at IdeOne.com.

Table of date-time types in Java, both modern and legacy

Asia/Kabul or Asia/Tehran time zones ?

You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).

If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z );  // Same moment, same point on timeline, but seen as different wall-clock time.

2010-07-30T22:30+04:30[Asia/Tehran]

Converting from java.time to legacy classes

You should stick with the new java.time classes. But you can convert to old if required.

java.util.Date date = java.util.Date.from( instant );

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).

DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );

Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.

java.util.Date date = dateTime.toDate();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

Rename master branch for both local and remote Git repositories

What about:

git checkout old-branch-name
git push remote-name new-branch-name
git push remote-name :old-branch-name
git branch -m new-branch-name

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

How to set initial value and auto increment in MySQL?

With CREATE TABLE statement

CREATE TABLE my_table (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
) AUTO_INCREMENT = 100;

or with ALTER TABLE statement

ALTER TABLE my_table AUTO_INCREMENT = 200;

How to import/include a CSS file using PHP code and not HTML code?

You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?

<link rel="stylesheet" href="CSS/main.css" type="text/css">

How to center horizontally div inside parent div

I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.

div#child {
    margin: 0 auto;
}

Debugging iframes with Chrome developer tools

In the Developer Tools in Chrome, there is a bar along the top, called the Execution Context Selector (h/t felipe-sabino), just under the Elements, Network, Sources... tabs, that changes depending on the context of the current tab. When in the Console tab there is a dropdown in that bar that allows you to select the frame context in which the Console will operate. Select your frame in this drop down and you will find yourself in the appropriate frame context. :D

Chrome v59 Chrome version 59

Chrome v33 Chrome version 33

Chrome v32 & lower Chrome pre-version 32

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home

Because:

 $ find /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home -name java*
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javac
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javadoc
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javafxpackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javah
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javap
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javapackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/javafx-src.zip
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/java

How do I PHP-unserialize a jQuery-serialized form?

Modified Murtaza Hussain answer:

function unserializeForm($str) {
    $strArray = explode("&", $str);
    foreach($strArray as $item) {
        $array = explode("=", $item);
        $returndata[] = $array;
    }
    return $returndata;
}

Passing a method parameter using Task.Factory.StartNew

Construct the first parameter as an instance of Action, e.g.

var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
    () => CheckFiles(inputID, col),
    cancelCheckFile.Token,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);

Loop in react-native

renderItem(item)
  {
    const width = '80%';
    var items = [];

    for(let i = 0; i < item.count; i++){

        items.push( <View style={{ padding: 10, borderBottomColor: "#f2f2f2", borderBottomWidth: 10, flexDirection: 'row' }}>
    <View style={{ width }}>
      <Text style={styles.name}>{item.title}</Text>
      <Text style={{ color: '#818181', paddingVertical: 10 }}>{item.taskDataElements[0].description + " "}</Text>
      <Text style={styles.begin}>BEGIN</Text>
    </View>

    <Text style={{ backgroundColor: '#fcefec', padding: 10, color: 'red', height: 40 }}>{this.msToTime(item.minTatTimestamp) <= 0 ? "NOW" : this.msToTime(item.minTatTimestamp) + "hrs"}</Text>
  </View> )
  }

  return items;
}

render() {
return (this.renderItem(this.props.item)) 
}

Execute jar file with multiple classpath libraries from command prompt

I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

I just decided to create the file in D: instead of C: and everything worked well. windows 7...10 have many issues regarding the sharing and authorization of files and folder..

Watching variables contents in Eclipse IDE

You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents

Wireshark vs Firebug vs Fiddler - pros and cons?

If you're developing an application that transfers data using AMF (fairly common in a particular set of GIS web APIs I use regularly), Fiddler does not currently provide an AMF decoder that will allow you to easily view the binary data in an easily-readable format. Charles provides this functionality.

Iterate Multi-Dimensional Array with Nested Foreach Statement

I know this is an old post, but I found it through Google, and after playing with it think I have an easier solution. If I'm wrong please point it out, 'cuz I'd like to know, but this worked for my purposes at least (It's based off of ICR's response):

for (int x = 0; x < array.GetLength(0); x++)
{
    Console.Write(array[x, 0], array[x,1], array[x,2]);
}

Since the both dimensions are limited, either one can be simple numbers, and thus avoid a nested for loop. I admit I'm new to C#, so please, if there's a reason not to do it, please tell me...

Connection pooling options with JDBC: DBCP vs C3P0

We came across a situation where we needed to introduce connection pool and we had 4 options in front of us.

  • DBCP2
  • C3P0
  • Tomcat JDBC
  • HikariCP

We carried out some tests and comparison based on our criteria and decided to go for HikariCP. Read this article which explains why we chose HikariCP.

Detecting Back Button/Hash Change in URL

I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...

// Add code below ...
function locationHashChanged(qs)
{
  var q = parseQs(qs);
  // ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
  // YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
  //  THAT IS PASSED TO changeHashValue(hashQuery)
}

// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
  stopHashListener();
  hashValue     = hashQuery;
  location.hash = hashQuery;
  startHashListener();
}

// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
  var hashQuery = getHashQuery();
  if (hashQuery == hashValue)
    return;
  hashValue = hashQuery;
  locationHashChanged(hashQuery);
}

function parseQs(qs)
{
  var q = {};
  var pairs = qs.split('&');
  for (var idx in pairs) {
    var arg = pairs[idx].split('=');
    q[arg[0]] = arg[1];
  }
  return q;
}

function startHashListener()
{
  hashListener = setInterval(checkIfHashChanged, 1000);
}

function stopHashListener()
{
  if (hashListener != null)
    clearInterval(hashListener);
  hashListener = null;
}

function getHashQuery()
{
  return location.hash.replace(/^#/, '');
}

var hashListener = null;
var hashValue    = '';//getHashQuery();
startHashListener();

Abstract methods in Python

You have to implement an abstract base class (ABC).

Check python docs

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...

But what's the best prefix length for a given column? Here's a method to find out:

SELECT
 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
|         21.78 |         80.20 |        100.00 |         100.00 |
+---------------+---------------+---------------+----------------+

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

What is Java String interning?

Update for Java 8 or plus. In Java 8, PermGen (Permanent Generation) space is removed and replaced by Meta Space. The String pool memory is moved to the heap of JVM.

Compared with Java 7, the String pool size is increased in the heap. Therefore, you have more space for internalized Strings, but you have less memory for the whole application.

One more thing, you have already known that when comparing 2 (referrences of) objects in Java, '==' is used for comparing the reference of object, 'equals' is used for comparing the contents of object.

Let's check this code:

String value1 = "70";
String value2 = "70";
String value3 = new Integer(70).toString();

Result:

value1 == value2 ---> true

value1 == value3 ---> false

value1.equals(value3) ---> true

value1 == value3.intern() ---> true

That's why you should use 'equals' to compare 2 String objects. And that's is how intern() is useful.

Is it possible to deserialize XML into List<T>?

Not sure about List<T> but Arrays are certainly do-able. And a little bit of magic makes it really easy to get to a List again.

public class UserHolder {
   [XmlElement("list")]
   public User[] Users { get; set; }

   [XmlIgnore]
   public List<User> UserList { get { return new List<User>(Users); } }
}

Best way to require all files from a directory in ruby?

Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file| 
  require File.basename(file, File.extname(file))
end

If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").

Why is Java's SimpleDateFormat not thread-safe?

Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.

Linking static libraries to other static libraries

Note before you read the rest: The shell script shown here is certainly not safe to use and well tested. Use at your own risk!

I wrote a bash script to accomplish that task. Suppose your library is lib1 and the one you need to include some symbols from is lib2. The script now runs in a loop, where it first checks which undefined symbols from lib1 can be found in lib2. It then extracts the corresponding object files from lib2 with ar, renames them a bit, and puts them into lib1. Now there may be more missing symbols, because the stuff you included from lib2 needs other stuff from lib2, which we haven't included yet, so the loop needs to run again. If after some passes of the loop there are no changes anymore, i.e. no object files from lib2 added to lib1, the loop can stop.

Note, that the included symbols are still reported as undefined by nm, so I'm keeping track of the object files, that were added to lib1, themselves, in order to determine whether the loop can be stopped.

#! /bin/bash

lib1="$1"
lib2="$2"

if [ ! -e $lib1.backup ]; then
    echo backing up
    cp $lib1 $lib1.backup
fi

remove_later=""

new_tmp_file() {
    file=$(mktemp)
    remove_later="$remove_later $file"
    eval $1=$file
}
remove_tmp_files() {
    rm $remove_later
}
trap remove_tmp_files EXIT

find_symbols() {
    nm $1 $2 | cut -c20- | sort | uniq 
}

new_tmp_file lib2symbols
new_tmp_file currsymbols

nm $lib2 -s --defined-only > $lib2symbols

prefix="xyz_import_"
pass=0
while true; do
    ((pass++))
    echo "Starting pass #$pass"
    curr=$lib1
    find_symbols $curr "--undefined-only" > $currsymbols
    changed=0
    for sym in $(cat $currsymbols); do
        for obj in $(egrep "^$sym in .*\.o" $lib2symbols | cut -d" " -f3); do
            echo "  Found $sym in $obj."
            if [ -e "$prefix$obj" ]; then continue; fi
            echo "    -> Adding $obj to $lib1"
            ar x $lib2 $obj
            mv $obj "$prefix$obj"
            ar -r -s $lib1 "$prefix$obj"
            remove_later="$remove_later $prefix$obj"
            ((changed=changed+1))
        done
    done
    echo "Found $changed changes in pass #$pass"

    if [[ $changed == 0 ]]; then break; fi
done

I named that script libcomp, so you can call it then e.g. with

./libcomp libmylib.a libwhatever.a

where libwhatever is where you want to include symbols from. However, I think it's safest to copy everything into a separate directory first. I wouldn't trust my script so much (however, it worked for me; I could include libgsl.a into my numerics library with that and leave out that -lgsl compiler switch).

How to generate and validate a software license key?

I've implemented internet-based one-time activation on my company's software (C# .net) that requires a license key that refers to a license stored in the server's database. The software hits the server with the key and is given license information that is then encrypted locally using an RSA key generated from some variables (a combination of CPUID and other stuff that won't change often) on the client computer and then stores it in the registry.

It requires some server-side coding, but it has worked really well for us and I was able to use the same system when we expanded to browser-based software. It also gives your sales people great info about who, where and when the software is being used. Any licensing system that is only handled locally is fully vulnerable to exploitation, especially with reflection in .NET. But, like everyone else has said, no system is wholly secure.

In my opinion, if you aren't using web-based licensing, there's no real point to protecting the software at all. With the headache that DRM can cause, it's not fair to the users who have actually paid for it to suffer.

COALESCE Function in TSQL

declare @store table (store_id varchar(300))
insert into @store 
values ('aa'),('bb'),('cc')
declare @str varchar (4000)
select @str = concat(@str+',',store_id) from @store
select @str

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

I think this is what the OP really wants:

array = -1:0.1:10

for i=1:numel(array)
    disp(array(i))
end

What is the recommended project structure for spring boot rest projects?

Though this question has an accepted answer, still I would like to share my project structure for RESTful services.

src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java

DAO = Data Access Object.
DTO = Data Transfer Object.

Add image to left of text via css

For adding background icon always before text when length of text is not known in advance.

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}

setting global sql_mode in mysql

Access the database as the administrator user (root maybe).

Check current SQL_mode

mysql> SELECT @@sql_mode;

To set a new sql_mode, exit the database, create a file

nano /etc/mysql/conf.d/<filename>.cnf 

with your sql_mode content

[mysqld]
sql_mode=NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Restart Mysql

mysql> sudo service mysql stop
mysql> sudo service mysql start

We create a file in the folder /etc/mysql/conf.d/ because in the main config file /etc/mysql/my.cnf the command is written to include all the settings files from the folder /etc/mysql/conf.d/

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

How to add a new schema to sql server 2008?

Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.

IF NOT EXISTS (SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name = 'newSchemaName' )
BEGIN
    EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

Decimal separator comma (',') with numberDecimal inputType in EditText

You could do the following:

DecimalFormatSymbols d = DecimalFormatSymbols.getInstance(Locale.getDefault());
input.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(5, 2) });
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + d.getDecimalSeparator()));

And then you could use an input filter:

    public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    DecimalFormatSymbols d = new DecimalFormatSymbols(Locale.getDefault());
    String s = "\\" + d.getDecimalSeparator();
    mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((" + s + "[0-9]{0," + (digitsAfterZero - 1) + "})?)||(" + s + ")?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Matcher matcher = mPattern.matcher(dest);
    if (!matcher.matches())
        return "";
    return null;
}

}

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I did exactly the same issue using the dependency below:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.44</version>
</dependency>

I just change to version 46 and everything works.

How do I perform a Perl substitution on a string while keeping the original?

I hate foo and bar .. who dreamed up these non descriptive terms in programming anyway?

my $oldstring = "replace donotreplace replace donotreplace replace donotreplace";

my $newstring = $oldstring;
$newstring =~ s/replace/newword/g; # inplace replacement

print $newstring;
%: newword donotreplace newword donotreplace newword donotreplace

Connecting to SQL Server using windows authentication

This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

Validating URL in Java

Thanks. Opening the URL connection by passing the Proxy as suggested by NickDK works fine.

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

System properties however doesn't work as I had mentioned earlier.

Thanks again.

Regards, Keya

Having issues with a MySQL Join that needs to meet multiple conditions

If you join the facilities table twice you will get what you are after:

select u.* 
from room u 
  JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
  JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3' 
where 1 and vizibility='1' 
group by id_uc 
order by u_premium desc, id_uc desc

Bootstrap col-md-offset-* not working

<div class="jumbotron">
        <div class="container">
            <div class="row">
                <div>
                    <h2 class="col-md-4 offset-md-4">Browse.</h2>
                    <h2 class="col-md-4 offset-md-4">create.</h2>
                    <h2 class="col-md-4 offset-md-4">share.</h2>
                </div>
            </div>
        </div>
    </div>

You can try this.

Excel date to Unix timestamp

To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:

=IF(
  AND(
    A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
    A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
  );
  (A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
  (A2-DATE(1970;1;1))*24*60*60*1000
)

Quick explanation:

If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Using Excel 2010 ? Try

Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

vi/vim editor, copy a block (not usual action)

I found the below command much more convenient. If you want to copy lines from 6 to 12 and paste from the current cursor position.

:6,12 co .

If you want to copy lines from 6 to 12 and paste from 100th line.

:6,12t100

Source: https://www.reddit.com/r/vim/comments/8i6vbd/efficient_ways_of_copying_few_lines/

Redirect after Login on WordPress

To globally redirect after successful login, find this code in wp-login.php, under section.

   <form name="loginform" id="loginform" action="<?php echo esc_url( site_url( 'wp-login.php', 'login_post' ) ); ?>" method="post">

<input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />

and replace <?php echo esc_attr($redirect_to); ?> with your URL where you want to redirect. The URL must start with http:// and ends on /other wise page redirect to default location.

Do same thing form redirect after registration with in same file but under <form name="registerform"> section.

Pretty printing XML in Python

Here's my (hacky?) solution to get around the ugly text node problem.

uglyXml = doc.toprettyxml(indent='  ')

text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)    
prettyXml = text_re.sub('>\g<1></', uglyXml)

print prettyXml

The above code will produce:

<?xml version="1.0" ?>
<issues>
  <issue>
    <id>1</id>
    <title>Add Visual Studio 2005 and 2008 solution files</title>
    <details>We need Visual Studio 2005/2008 project files for Windows.</details>
  </issue>
</issues>

Instead of this:

<?xml version="1.0" ?>
<issues>
  <issue>
    <id>
      1
    </id>
    <title>
      Add Visual Studio 2005 and 2008 solution files
    </title>
    <details>
      We need Visual Studio 2005/2008 project files for Windows.
    </details>
  </issue>
</issues>

Disclaimer: There are probably some limitations.

How can I remove the extension of a filename in a shell script?

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'

Reset all the items in a form

Quick answer, maybe it'll help:

private void button1_Click(object sender, EventArgs e)
{            
    Form2 f2 = new Form2();
    f2.ShowDialog();
    while (f2.DialogResult == DialogResult.Retry)
    {
        f2 = new Form2();
        f2.ShowDialog();
    }
}

and in Form2 (The 'settings' Form):

private void button1_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.OK;
    Close();
}

private void button2_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Retry;
    Close();
}

Find the least number of coins required that can make any change from 1 to 99 cents

Solution with greedy approach in java is as below :

public class CoinChange {
    public static void main(String args[]) {
        int denominations[] = {1, 5, 10, 25};
        System.out.println("Total required coins are " + greeadApproach(53, denominations));
    }

    public static int greeadApproach(int amount, int denominations[]) {
        int cnt[] = new int[denominations.length];
        for (int i = denominations.length-1; amount > 0 && i >= 0; i--) {
            cnt[i] = (amount/denominations[i]);
            amount -= cnt[i] * denominations[i];            
        }
        int noOfCoins = 0;
        for (int cntVal : cnt) {
            noOfCoins+= cntVal;
        }
        return noOfCoins;
    }
}

But this works for single amount. If you want to run it for range, than we have to call it for each amount of range.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

THE PROBLEM is here: onClick={this.handleButtonChange(false)}

When you pass this.handleButtonChange(false) to onClick, you are actually calling the function with value = false and setting onClick to the function's return value, which is undefined. Also, calling this.handleButtonChange(false) then calls this.setState() which triggers a re-render, resulting in an infinite render loop.

THE SOLUTION is to pass the function in a lambda: onClick={() => this.handleButtonChange(false)}. Here you are setting onClick to equal a function that will call handleButtonChange(false) when the button is clicked.

The below example may help:

function handleButtonChange(value){
  console.log("State updated!")
}

console.log(handleButtonChange(false))
//output: State updated!
//output: undefined

console.log(() => handleButtonChange(false))
//output: ()=>{handleButtonChange(false);}

MySQL order by before group by

First, don't use * in select, affects their performance and hinder the use of the group by and order by. Try this query:

SELECT wp_posts.post_author, wp_posts.post_date as pdate FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author           
ORDER BY pdate DESC

When you don't specifies the table in ORDER BY, just the alias, they will order the result of the select.

grep output to show only matching file

You can use the Unix-style -l switch – typically terse and cryptic – or the equivalent --files-with-matches – longer and more readable.

The output of grep --help is not easy to read, but it's there:

-l, --files-with-matches  print only names of FILEs containing matches

Cmake doesn't find Boost

One more bit of advice for anyone trying to build CGAL in particular, with statically linked Boost. It is not enough to define Boost_USE_STATIC_LIBS; it gets overridden by the time Boost_DEBUG outputs its value. The thing to do here is to check the "Advanced" checkbox and to enable CGAL_Boost_USE_STATIC_LIBS.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The problem:

java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.

For Jersey 1.x you have to do it like this:

<servlet>
  <servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
  com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>sample.hello.resources</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

For more information check the Jersey 1.x documentation.

If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.xx</version>
</dependency>

For Jersey 2.x you don't need to setup anything in your web.xml, it is sufficient to supply a class similar to this:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest")
public class ApplicationConfig extends Application {

}

For more information, check the Jersey documentation.

See also:

Soft keyboard open and close listener in an activity in Android

Use this class,

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class SoftKeyboard implements View.OnFocusChangeListener
{
private static final int CLEAR_FOCUS = 0;

private ViewGroup layout;
private int layoutBottom;
private InputMethodManager im;
private int[] coords;
private boolean isKeyboardShow;
private SoftKeyboardChangesThread softKeyboardThread;
private List<EditText> editTextList;

private View tempView; // reference to a focused EditText

public SoftKeyboard(ViewGroup layout, InputMethodManager im)
{
    this.layout = layout;
    keyboardHideByDefault();
    initEditTexts(layout);
    this.im = im;
    this.coords = new int[2];
    this.isKeyboardShow = false;
    this.softKeyboardThread = new SoftKeyboardChangesThread();
    this.softKeyboardThread.start();
}

public void openSoftKeyboard()
{
    if(!isKeyboardShow)
    {
        layoutBottom = getLayoutCoordinates();
        im.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
        softKeyboardThread.keyboardOpened();
        isKeyboardShow = true;
    }
}

public void closeSoftKeyboard()
{
    if(isKeyboardShow)
    {
        im.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
        isKeyboardShow = false;
    }
}

public void setSoftKeyboardCallback(SoftKeyboardChanged mCallback)
{
    softKeyboardThread.setCallback(mCallback);
}

public void unRegisterSoftKeyboardCallback()
{
    softKeyboardThread.stopThread();
}

public interface SoftKeyboardChanged 
{
    public void onSoftKeyboardHide();
    public void onSoftKeyboardShow();   
}

private int getLayoutCoordinates()
{
    layout.getLocationOnScreen(coords);
    return coords[1] + layout.getHeight();
}

private void keyboardHideByDefault()
{
    layout.setFocusable(true);
    layout.setFocusableInTouchMode(true);
}

/*
 * InitEditTexts now handles EditTexts in nested views
 * Thanks to Francesco Verheye ([email protected])
 */
private void initEditTexts(ViewGroup viewgroup) 
{
    if(editTextList == null)
        editTextList = new ArrayList<EditText>();

    int childCount = viewgroup.getChildCount();
    for(int i=0; i<= childCount-1;i++) 
    {
        View v = viewgroup.getChildAt(i);

        if(v instanceof ViewGroup) 
        {
            initEditTexts((ViewGroup) v);
        }

        if(v instanceof EditText) 
        {
            EditText editText = (EditText) v;
            editText.setOnFocusChangeListener(this);
            editText.setCursorVisible(true);
            editTextList.add(editText);
        }
    }
}

/*
 * OnFocusChange does update tempView correctly now when keyboard is still shown
 * Thanks to Israel Dominguez ([email protected])
 */
@Override
public void onFocusChange(View v, boolean hasFocus) 
{
    if(hasFocus) 
    {
        tempView = v;
        if(!isKeyboardShow) 
        {
            layoutBottom = getLayoutCoordinates();
            softKeyboardThread.keyboardOpened();
            isKeyboardShow = true;
        }
    }
}

// This handler will clear focus of selected EditText
private final Handler mHandler = new Handler()
{
    @Override
    public void handleMessage(Message m)
    {
        switch(m.what)
        {
        case CLEAR_FOCUS:
            if(tempView != null)
            {
                tempView.clearFocus();
                tempView = null;
            }
            break;
        }
    }
};

private class SoftKeyboardChangesThread extends Thread
{
    private AtomicBoolean started;
    private SoftKeyboardChanged mCallback;

    public SoftKeyboardChangesThread()
    {
        started = new AtomicBoolean(true);
    }

    public void setCallback(SoftKeyboardChanged mCallback)
    {
        this.mCallback = mCallback;
    }

    @Override
    public void run()
    {
        while(started.get())
        {
            // Wait until keyboard is requested to open
            synchronized(this)
            {
                try 
                {
                    wait();
                } catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }

            int currentBottomLocation = getLayoutCoordinates();

            // There is some lag between open soft-keyboard function and when it really appears.
            while(currentBottomLocation == layoutBottom && started.get())
            {
                currentBottomLocation = getLayoutCoordinates();
            }

            if(started.get())
                mCallback.onSoftKeyboardShow();

            // When keyboard is opened from EditText, initial bottom location is greater than layoutBottom
            // and at some moment equals layoutBottom.
            // That broke the previous logic, so I added this new loop to handle this.
            while(currentBottomLocation >= layoutBottom && started.get())
            {
                currentBottomLocation = getLayoutCoordinates();
            }

            // Now Keyboard is shown, keep checking layout dimensions until keyboard is gone
            while(currentBottomLocation != layoutBottom && started.get())
            {
                                    synchronized(this)
                {
                    try 
                    {
                        wait(500);
                    } catch (InterruptedException e) 
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                currentBottomLocation = getLayoutCoordinates();
            }

            if(started.get())
                mCallback.onSoftKeyboardHide();

            // if keyboard has been opened clicking and EditText.
            if(isKeyboardShow && started.get())
                isKeyboardShow = false;

            // if an EditText is focused, remove its focus (on UI thread)
            if(started.get())
                mHandler.obtainMessage(CLEAR_FOCUS).sendToTarget();
        }   
    }

    public void keyboardOpened()
    {
        synchronized(this)
        {
            notify();
        }
    }

    public void stopThread()
    {
        synchronized(this)
        {
            started.set(false);
            notify();
        }
    }

}
}

In Android Manifest, android:windowSoftInputMode="adjustResize" is necessary.

/*
Somewhere else in your code
*/
RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use the layout root
InputMethodManager im = (InputMethodManager)getSystemService(Service.INPUT_METHOD_SERVICE);

/*
Instantiate and pass a callback
*/
SoftKeyboard softKeyboard;
softKeyboard = new SoftKeyboard(mainLayout, im);
softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged() {

@Override
public void onSoftKeyboardHide()  {
    // Code here
}

@Override
public void onSoftKeyboardShow() {
    // Code here
}   
});

/*
Open or close the soft keyboard easily
*/
softKeyboard.openSoftKeyboard();
softKeyboard.closeSoftKeyboard();

/* Prevent memory leaks:*/
@Override
public void onDestroy() {
    super.onDestroy();
    softKeyboard.unRegisterSoftKeyboardCallback();
}

P.S - Completely taken from here.

pros and cons between os.path.exists vs os.path.isdir

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

Remove all html tags from php string

use strip_tags

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);   //output Test paragraph. Other text

<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

SQL Server dynamic PIVOT query?

You can achieve this using dynamic TSQL (remember to use QUOTENAME to avoid SQL injection attacks):

Pivots with Dynamic Columns in SQL Server 2005

SQL Server - Dynamic PIVOT Table - SQL Injection

Obligatory reference to The Curse and Blessings of Dynamic SQL

How to read an entire file to a string using C#?

well the quickest way meaning with the least possible C# code is probably this one:

string readText = System.IO.File.ReadAllText(path);

Selenium C# WebDriver: Wait until element is present

You can use the following

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));
wait.Until(ExpectedConditions.ElementToBeClickable((By.Id("login")));

Which exception should I raise on bad/illegal argument combinations in Python?

I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:

$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

Our junior dev just found this page in a google search for "python exception wrong arguments" and I'm surprised that the obvious (to me) answer wasn't ever suggested in the decade since this question was asked.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

ESLint Parsing error: Unexpected token

Originally, the solution was to provide the following config as object destructuring used to be an experimental feature and not supported by default:

{
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true
    }
  }
}

Since version 5, this option has been deprecated.

Now it is enough just to declare a version of ES, which is new enough:

{
  "parserOptions": {
    "ecmaVersion": 2018
  }
}

Parse an HTML string with JS

var doc = new DOMParser().parseFromString(html, "text/html");
var links = doc.querySelectorAll("a");

Git - Ignore files during merge

.gitattributes - is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.

You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml for our branch. We need to set the merge=foo to config.xml in .gitattributes file.

merge=foo tell git to use our(current branch) file, if a merge conflict occurs.

  1. Add a .gitattributes file at the root level of the repository

  2. You can set up an attribute for confix.xml in the .gitattributes file

     <pattern> merge=foo
    

    Let's take an example for config.xml

     config.xml merge=foo
    
  3. And then define a dummy foo merge strategy with:

     $ git config --global merge.foo.driver true
    

If you merge the stag form dev branch, instead of having the merge conflicts with the config.xml file, the stag branch's config.xml preserves at whatever version you originally had.

for more reference: merge_strategies

Adding values to a C# array

You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.

HighCharts Hide Series Name from the Legend

Replace return 'Legend' by return ''

automating telnet session using bash scripts

Following is working for me... put all of your IPs you want to telnet in IP_sheet.txt

while true
read a
do
{
    sleep 3
    echo df -kh
    sleep 3
    echo exit
} | telnet $a
done<IP_sheet.txt

Floating Point Exception C++ Why and what is it?

Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.

for (i>0; i--;){
c= input%i;

Thats division by zero at some point since you are decrementing i.

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

How to increase the max connections in postgres?

Adding to Winnie's great answer,

If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.

SHOW config_file;

For me changing the max_connections alone made the trick.

how to refresh Select2 dropdown menu after ajax loading different content?

Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:

var drop = $('#product_1');   // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2');  pick krajee attrs of our elem;
var drop_id = drop.attr('id');  // take id 
settings = window[settings];  // take previous settings from window;
drop.select2(settings);  // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;

It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

What are .NumberFormat Options In Excel VBA?

Note this was done on Excel for Mac 2011 but should be same for Windows

Macro:

Sub numberformats()
  Dim rng As Range
  Set rng = Range("A24:A35")
  For Each c In rng
    Debug.Print c.NumberFormat
  Next c
End Sub

Result:

General     General
Number      0
Currency    $#,##0.00;[Red]$#,##0.00
Accounting  _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
Date        m/d/yy
Time        [$-F400]h:mm:ss am/pm
Percentage  0.00%
Fraction    # ?/?
Scientific  0.00E+00
Text        @
Special     ;;
Custom      #,##0_);[Red](#,##0)

(I just picked a random entry for custom)

Sorting HTML table with JavaScript

Here is a complete example using pure JavaScript. The algorithm used for sorting is basically BubbleSort. Here is a Fiddle.

   <!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">

<script type="text/javascript">
    function sort(ascending, columnClassName, tableId) {
        var tbody = document.getElementById(tableId).getElementsByTagName(
                "tbody")[0];
        var rows = tbody.getElementsByTagName("tr");

        var unsorted = true;

        while (unsorted) {
            unsorted = false

            for (var r = 0; r < rows.length - 1; r++) {
                var row = rows[r];
                var nextRow = rows[r + 1];

                var value = row.getElementsByClassName(columnClassName)[0].innerHTML;
                var nextValue = nextRow.getElementsByClassName(columnClassName)[0].innerHTML;

                value = value.replace(',', '.'); // in case a comma is used in float number
                nextValue = nextValue.replace(',', '.');

                if (!isNaN(value)) {
                    value = parseFloat(value);
                    nextValue = parseFloat(nextValue);
                }

                if (ascending ? value > nextValue : value < nextValue) {
                    tbody.insertBefore(nextRow, row);
                    unsorted = true;
                }
            }
        }
    };
</script>
</head>
<body>
    <table id="content-table">
        <thead>
            <tr>
                <th class="id">ID <a
                    href="javascript:sort(true, 'id', 'content-table');">asc</a> <a
                    href="javascript:sort(false, 'id', 'content-table');">des</a>
                </th>
                <th class="country">Country <a
                    href="javascript:sort(true, 'country', 'content-table');">asc</a> <a
                    href="javascript:sort(false, 'country', 'content-table');">des</a>
                </th>
                <th class="some-fact">Some fact <a
                    href="javascript:sort(true, 'some-fact', 'content-table');">asc</a>
                    <a href="javascript:sort(false, 'some-fact', 'content-table');">des</a>
                <th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="id">001</td>
                <td class="country">Germany</td>
                <td class="some-fact">16.405</td>
            </tr>
            <tr>
                <td class="id">002</td>
                <td class="country">France</td>
                <td class="some-fact">10.625</td>
            </tr>
            <tr>
                <td class="id">003</td>
                <td class="country">UK</td>
                <td class="some-fact">15.04</td>
            </tr>
            <tr>
                <td class="id">004</td>
                <td class="country">China</td>
                <td class="some-fact">13.536</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

You can also check out the source from here: https://github.com/wmentzel/table-sort

AngularJS does not send hidden field value

Below Code will work for this IFF it in the same order as its mentionened make sure you order is type then name, ng-model ng-init, value. thats It.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

How do I set up NSZombieEnabled in Xcode 4?

Cocoa offers a cool feature which greatly enhances your capabilities to debug such situations. It is an environment variable which is called NSZombieEnabled, watch this video that explains setting up NSZombieEnabled in objective-C

OSError - Errno 13 Permission denied

This may also happen if you have a slash before the folder name:

path = '/folder1/folder2'

OSError: [Errno 13] Permission denied: '/folder1'

comes up with an error but this one works fine:

path = 'folder1/folder2'

CSS Cell Margin

If padding isn't working for you, another work around is to add extra columns and set a margin via width using <colgroup>. None of the padding solutions above were working for me as I was trying to give the cell border itself a margin, and this is what solved the problem in the end:

<table>
  <colgroup>
    <col>
    <col width="20px">
    <col>
  </colgroup>
  <tr>
     <td>data</td>
     <td></td>
     <td>more data</td>
   </tr>
</table>

Style the borders of the table cells using :nth-child so that the 2nd and third columns appear to be a single column.

table tr td:nth-child(2) { border: 1px solid black; border-right:0; }
table tr td:nth-child(3) { border: 1px solid black; border-left:0; }

How do I test if a string is empty in Objective-C?

So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply. Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.

Let's say empty string means "a string which does not contain any characters significant in the current context".

This could mean visually, as in color and background color are same in an attributed string. Effectively empty.

This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty. Further, empty of meaningful significant characters could mean a string that has no characters the reader understands. They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.

We could say empty is a function of the percentage of negative space in the glyphs rendered.

Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.

Conclusion. Length alone is not the only measure here. Contextual set membership is also pretty important.

Character Set membership is a very important common additional measure. Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas ) Additional more abstract context sets also exist.

So think carefully before assuming a string is only empty based on length or whitespace.

How to check the differences between local and github before the pull

git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

git fetch origin

... and then do:

git diff master origin/master

... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

Personally, I think that doing git fetch and git merge separately is generally a good idea.

How to use store and use session variables across pages?

Try this:

<!-- first page -->
<?php
  session_start(); 
  session_register('myvar');
  $_SESSION['myvar'] == 'myvalue';
?>

<!-- second page -->
<?php
    session_start();
    echo("1");
    if(session_is_registered('myvar'))
    {
        echo("2");
       if($_SESSION['myvar'] == 'myvalue')
       {
           echo("3");
           exit;
       }
    }
    ?>

How can I get the day of a specific date with PHP

You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime, for instance.

For instance, with the 'D' modifier, for the textual representation in three letters :

$timestamp = strtotime('2009-10-22');

$day = date('D', $timestamp);
var_dump($day);

You will get :

string 'Thu' (length=3)

And with the 'l' modifier, for the full textual representation :

$day = date('l', $timestamp);
var_dump($day);

You get :

string 'Thursday' (length=8)

Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :

$day = date('w', $timestamp);
var_dump($day);

You'll obtain :

string '4' (length=1)

How to view the current heap size that an application is using?

Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop

PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

PHP - Copy image to my server direct from URL

This SO thread will solve your problem. Solution in short:

$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));

Nth max salary in Oracle

There are three methods are there...

SELECT salary,first_name,rnk 
FROM (SELECT salary,first_name,rank() over (order by salary desc nulls last) as                                                                  rnk from emp) where rnk=3;


SELECT salary,first_name,rnk 
FROM (SELECT salary,first_name,dense_rank() over (order by salary desc nulls last) as                                                                  rnk from emp) where rnk=3;


select rnk,first_name,salary 
from (select rownum as rnk ,first_name,salary 
      from (select first_name,salary 
            from emp order by salary desc nulls last)) where rnk=3

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

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

[DefaultValue(None)]
public enum Orientation
{
    None = -1,
    North = 0,
    East = 1,
    South = 2,
    West = 3
}

Then in the code you can use

public Orientation GetDefaultOrientation()
{
   return default(Orientation);
} 

Javascript to convert UTC to local time

The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

What is the best way to programmatically detect porn images?

This one looks promising. Basically they detect skin (with calibration by recognizing faces) and determine "skin paths" (i.e. measuring the proportion of skin pixels vs. face skin pixels / skin pixels). This has decent performance. http://www.prip.tuwien.ac.at/people/julian/skin-detection

If statement for strings in python?

If should be if. Your program should look like this:

answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
    print("this will do the calculation")
else:
    exit()

Note also that the indentation is important, because it marks a block in Python.

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Can I access a form in the controller?

Though alluded to in other comments I thought I'd spell it out a bit for those using the "Controller As" syntax:

<div ng-controller="MyController as ctrl">

<form name="ctrl.myForm">
    ...inputs
    Dirty? {{ctrl.myForm.$dirty}}

    <button ng-click="ctrl.saveChanges()">Save</button>
</form>

</div>

Then you can access the FormController in your code like:

function MyController () {
    var vm = this;
    vm.saveChanges = saveChanges;

    function saveChanges() {

       if(vm.myForm.$valid) { 
            // Save to db or whatever.
            vm.myForm.$setPristine();
       }
}

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

Python and SQLite: insert into table

Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:

def sqlite_insert(conn, table, row):
    cols = ', '.join('"{}"'.format(col) for col in row.keys())
    vals = ', '.join(':{}'.format(col) for col in row.keys())
    sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
    conn.cursor().execute(sql, row)
    conn.commit()

Example of use:

sqlite_insert(conn, 'stocks', {
        'created_at': '2016-04-17',
        'type': 'BUY',
        'amount': 500,
        'price': 45.00})

Note, that table name and column names should be validated beforehand.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/