Programs & Examples On #Depth first search

Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

Nice Explanation from http://www.programmerinterview.com/index.php/data-structures/dfs-vs-bfs/

An example of BFS

Here’s an example of what a BFS would look like. This is something like Level Order Tree Traversal where we will use QUEUE with ITERATIVE approach (Mostly RECURSION will end up with DFS). The numbers represent the order in which the nodes are accessed in a BFS:

enter image description here

In a depth first search, you start at the root, and follow one of the branches of the tree as far as possible until either the node you are looking for is found or you hit a leaf node ( a node with no children). If you hit a leaf node, then you continue the search at the nearest ancestor with unexplored children.

An example of DFS

Here’s an example of what a DFS would look like. I think post order traversal in binary tree will start work from the Leaf level first. The numbers represent the order in which the nodes are accessed in a DFS:

enter image description here

Differences between DFS and BFS

Comparing BFS and DFS, the big advantage of DFS is that it has much lower memory requirements than BFS, because it’s not necessary to store all of the child pointers at each level. Depending on the data and what you are looking for, either DFS or BFS could be advantageous.

For example, given a family tree if one were looking for someone on the tree who’s still alive, then it would be safe to assume that person would be on the bottom of the tree. This means that a BFS would take a very long time to reach that last level. A DFS, however, would find the goal faster. But, if one were looking for a family member who died a very long time ago, then that person would be closer to the top of the tree. Then, a BFS would usually be faster than a DFS. So, the advantages of either vary depending on the data and what you’re looking for.

One more example is Facebook; Suggestion on Friends of Friends. We need immediate friends for suggestion where we can use BFS. May be finding the shortest path or detecting the cycle (using recursion) we can use DFS.

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth


Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        displayVertex(0);
        stack.push(0);
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
                stack.pop();
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
                stack.push(adjacentVertex);
            }
        }
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.


Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        displayVertex(0);
        queue.insert(0);
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
                queue.insert(v2);
            }
        }
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

How to do 3 table JOIN in UPDATE query?

An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}

Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

dyld: Library not loaded: @rpath/libswiftCore.dylib

The most easy and easy to ignored way : clean and rebuild.

This solved the issue after tried the answers above and did not worked.

:touch CSS pseudo-class or something similar?

I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

How to get docker-compose to always re-create containers from fresh images?

The only solution that worked for me was this command :

docker-compose build --no-cache

This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.

How do I generate a random int number?

Just as a note for future reference.

If you're using .NET Core, multiple Random instances isn't as dangerous as before. I'm aware that this question is from 2010, but since this question is old but has some attraction, I think it's a good thing to document the change.

You may refer to this question I made a while back:

Did Microsoft change Random default seed?

Basically, they have changed the default seed from Environment.TickCount to Guid.NewGuid().GetHashCode(), so if you create 2 instances of Random it won't display the same numbers.

You can see the file diffs from .NET Framework/.NET Core (2.0.0+) here: https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d

It isn't as safe as RNGCryptoServiceProvider, but at least it won't give you weird results.

Installed Java 7 on Mac OS X but Terminal is still using version 6

May I suggest you to have a look at the tool Jenv

This will allow you to switch at any time between your installed JVMs.

Simply as:

jenv global oracle-1.7

then later for test purpose:

jenv global oracle-1.6

And you have much more commands available.

Android: How to enable/disable option menu item on button click?

simplify @Vikas version

@Override
public boolean onPrepareOptionsMenu (Menu menu) {

    menu.findItem(R.id.example_foobar).setEnabled(isFinalized);
    return true;
}

How to read fetch(PDO::FETCH_ASSOC);

/* Design Pattern "table-data gateway" */

class Gateway
{
    protected $connection = null;

    public function __construct()
    {
        $this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
    }

    public function loadAll()
    {
        $sql = 'SELECT * FROM users';
        $rows = $this->connection->query($sql);

        return $rows;
    }

    public function loadById($id)
    {
        $sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
        $result = $this->connection->query($sql);

        return $result->fetch(PDO::FETCH_ASSOC);
        // http://php.net/manual/en/pdostatement.fetch.php //                   
    }
}

/* Print all row with column 'user_id' only */

$gateway  = new Gateway();
$users    = $gateway->loadAll();

$no = 1;
foreach ($users as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
    $no++;
}

/* Print user_id = 1 with all column */

$user = $gateway->loadById(1);

$no = 1;
foreach ($user as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value . '<br />';
    $no++;
}

/* Print user_id = 1 with column 'email and password' */

$user = $gateway->loadById(1);

echo $user['email'];
echo $user['password'];

How to add element to C++ array?

You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:

int arr[] = new int[15];
unsigned int arr_length = 0;

Now, if you want to add an element to the end of the array, you can do this:

if (arr_length < 15) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;

if (arr_length < ARRAY_MAX) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.

If you will be using elements off the end of the array, you can do this:

if (arr_length > 0) {
  int value = arr[arr_length--];
} else {
  // Handle empty array.
}

If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
unsigned int arr_start = 0;
unsigned int arr_end = 0;

// Insert number at end.
if (arr_length < ARRAY_MAX) {
  arr[arr_end] = <number>;
  arr_end = (arr_end + 1) % ARRAY_MAX;
  arr_length ++;
} else {
  // Handle a full array.
}

// Read number from beginning.
if (arr_length > 0) {
  int value = arr[arr_start];
  arr_start = (arr_start + 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

// Read number from end.
if (arr_length > 0) {
  int value = arr[arr_end];
  arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.

You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.

This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.

How to use find command to find all files with extensions from list?

find /path/to/ -type f -print0 | xargs -0 file | grep -i image

This uses the file command to try to recognize the type of file, regardless of filename (or extension).

If /path/to or a filename contains the string image, then the above may return bogus hits. In that case, I'd suggest

cd /path/to
find . -type f -print0 | xargs -0 file --mime-type | grep -i image/

keypress, ctrl+c (or some combo like that)

As of 2019, this works (in Chrome at least)

$(document).keypress(function(e) {
    var key = (event.which || event.keyCode) ;
  if(e.ctrlKey) {
        if (key == 26) { console.log('Ctrl+Z was pressed') ; }
        else if (key == 25) { console.log('Ctrl+Y was pressed') ; }
        else if (key == 19) { console.log('Ctrl+S was pressed') ; }
    else { console.log('Ctrl', key, 'was pressed') ; }
    }
});

Disable same origin policy in Chrome

For OSX, run the following command from the terminal:

open -na Google\ Chrome --args --disable-web-security --user-data-dir=$HOME/profile-folder-name

This will start a new instance of Google Chrome with a warning on top.

How to remove title bar from the android activity?

You just add following lines of code in style.xml file

<style name="AppTheme.NoTitleBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>

change apptheme in AndroidManifest.xml file

android:theme="@style/AppTheme.NoTitleBar"

What is the difference between Collection and List in Java?

List and Set are two subclasses of Collection.

In List, data is in particular order.

In Set, it can not contain the same data twice.

In Collection, it just stores data with no particular order and can contain duplicate data.

What is a Y-combinator?

Most of the answers above describe what the Y-combinator is but not what it is for.

Fixed point combinators are used to show that lambda calculus is turing complete. This is a very important result in the theory of computation and provides a theoretical foundation for functional programming.

Studying fixed point combinators has also helped me really understand functional programming. I have never found any use for them in actual programming though.

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

Change text (html) with .animate

If all you're looking to do is change the text you could do exactly as Kevin has said. But if you're trying to run an animation as well as change the text you could accomplish this by first changing the text then running your animation.

For Example:

$("#test").html('The text has now changed!');
$("#test").animate({left: '100px', top: '100px'},500);

Check out this fiddle for full example:

http://jsfiddle.net/Twig/3krLh/1/

SQL Server: SELECT only the rows with MAX(DATE)

And u can also use that select statement as left join query... Example :

... left join (select OrderNO,
   PartCode,
   Quantity from (select OrderNO,
         PartCode,
         Quantity,
         row_number() over(partition by OrderNO order by DateEntered desc) as rn
  from YourTable) as T where rn = 1 ) RESULT on ....

Hope this help someone that search for this :)

Can't import org.apache.http.HttpResponse in Android Studio

in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

test if event handler is bound to an element in jQuery

I wrote a very tiny plugin called "once" which do that:

$.fn.once = function(a, b) {
    return this.each(function() {
        $(this).off(a).on(a,b);
    });
};

And simply:

$(element).once('click', function(){
});

Can't specify the 'async' modifier on the 'Main' method of a console app

On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from main:

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        ShowThreadInfo("Application");

        var t = Task.Run(() => ShowThreadInfo("Task") );
        t.Wait();
    }

    static void ShowThreadInfo(String s)
    {
        Console.WriteLine("{0} Thread ID: {1}",
                          s, Thread.CurrentThread.ManagedThreadId);
    }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

Note this statement that follows the example:

The examples show that the asynchronous task executes on a different thread than the main application thread.

So, if instead you want the task to run on the main application thread, see the answer by @StephenCleary.

And regarding the thread on which the task runs, also note Stephen's comment on his answer:

You can use a simple Wait or Result, and there's nothing wrong with that. But be aware that there are two important differences: 1) all async continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in an AggregateException.

(See Exception Handling (Task Parallel Library) for how to incorporate exception handling to deal with an AggregateException.)


Finally, on MSDN from the documentation for Task.Delay Method (TimeSpan), this example shows how to run an asynchronous task that returns a value:

using System;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        var t = Task.Run(async delegate
                {
                    await Task.Delay(TimeSpan.FromSeconds(1.5));
                    return 42;
                });
        t.Wait();
        Console.WriteLine("Task t Status: {0}, Result: {1}",
                          t.Status, t.Result);
    }
}
// The example displays the following output:
//        Task t Status: RanToCompletion, Result: 42

Note that instead of passing a delegate to Task.Run, you can instead pass a lambda function like this:

var t = Task.Run(async () =>
        {
            await Task.Delay(TimeSpan.FromSeconds(1.5));
            return 42;
        });

Access 2013 - Cannot open a database created with a previous version of your application

I've just used Excel 2016 to open Access 2003 tables.

  1. Open a new worksheet
  2. Go to Data tab
  3. Click on "From Access" menu item
  4. Select the database's .mdb file
  5. In the "Data Link Properties" box that opens, switch to the "Provider" tab
  6. Select the "Microsoft Jet 4.0 OLE DB Provider"
  7. Click on Next
  8. Reselect the database's .mdb file (it forgets it when you change Provider)
  9. Click OK
  10. From the Select Table dialogue that appears, choose the table you want to import.

Export and Import all MySQL databases at one time

Be careful when exporting from and importing to different MySQL versions as the mysql tables may have different columns. Grant privileges may fail to work if you're out of luck. I created this script (mysql_export_grants.sql ) to dump the grants for importing into the new database, just in case:

#!/bin/sh
stty -echo
printf 'Password: ' >&2
read PASSWORD
stty echo
printf "\n"
if [ -z "$PASSWORD" ]; then
        echo 'No password given!'
        exit 1
fi
MYSQL_CONN="-uroot -p$PASSWORD"
mysql ${MYSQL_CONN} --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM mysql.user WHERE user<>''" | mysql ${MYSQL_CONN} --skip-column-names -A | sed 's/$/;/g'

How to change value of a request parameter in laravel

If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel

$request->replace(['property to update' => $newValue]);

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

How can I call PHP functions by JavaScript?

I created this library, may be of help to you. MyPHP client and server side library

Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

    <!-- include MyPHP.js -->
    <script src="MyPHP.js"></script>

    <!-- use MyPHP class -->
    <script>
        const php = new MyPHP;
        php.auth = 'hashed-key';

        // call a php class
        const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);

        // call a method in that class
        phpClass.method('login', <arguments>);

        // you can keep chaining here...

        // finally let's call this class
        php.call(phpClass).then((response)=>{
            // returns a promise.
        });

        // calling a function is quite simple also
        php.call('say_hello', <arguments>).then((response)=>{
            // returns a promise
        });

        // if your response has a script tag and you need to update your dom call just call
        php.html(response);

    </script>
</body>
</html>

MySQL select with CONCAT condition

Use CONCAT_WS().

SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users 
WHERE firstlast = "Bob Michael Jones";

The first argument is the separator for the rest of the arguments.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

If you want to add a xx.tar.gz to a /usr/local in container, unzip it, and then remove the useless compressed package.

For COPY:

COPY resources/jdk-7u79-linux-x64.tar.gz /tmp/
RUN tar -zxvf /tmp/jdk-7u79-linux-x64.tar.gz -C /usr/local
RUN rm /tmp/jdk-7u79-linux-x64.tar.gz

For ADD:

ADD resources/jdk-7u79-linux-x64.tar.gz /usr/local/

ADD supports local-only tar extraction. Besides it, COPY will use three layers, but ADD only uses one layer.

PHP include relative path

While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.

Use absolute paths with an constant you can set based on environment.

if (is_production()) {
    define('ROOT_PATH', '/some/production/path');
}
else {
    define('ROOT_PATH', '/root');
}

include ROOT_PATH . '/connect.php';

As commented, ROOT_PATH could also be derived from the current path, $_SERVER['DOCUMENT_ROOT'], etc.

How to get all count of mongoose model?

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

Here's an example of usage:

userModel.count({}, function( err, count){
    console.log( "Number of users:", count );
})

How to change Java version used by TOMCAT?

On Linux, Tomcat7 has a configuration file located at:

/etc/sysconfig/tomcat7

... which is where server specific configurations should be made. You can set the JAVA_HOME env variable here w/o needing to create a profile.d/ script.

This worked for me.

Today's Date in Perl in MM/DD/YYYY format

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

If you are connecting from Windows machine A to Windows machine B (server with SQL Server installed), and are getting this error, you need to do the following:

On machine B:

1.) turn on the Windows service called "SQL Server Browser" and start the service

2.) in the Windows firewall, enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)

3.) in the Windows firewall, enable incoming port TCP 1433 (in case there is a telnet connection)

4.) in SQL Server Configuration Manager, enable TCP/IP protocol for port 1433

enter image description here

What's "tools:context" in Android layout files?

That attribute is basically the persistence for the "Associated Activity" selection above the layout. At runtime, a layout is always associated with an activity. It can of course be associated with more than one, but at least one. In the tool, we need to know about this mapping (which at runtime happens in the other direction; an activity can call setContentView(layout) to display a layout) in order to drive certain features.

Right now, we're using it for one thing only: Picking the right theme to show for a layout (since the manifest file can register themes to use for an activity, and once we know the activity associated with the layout, we can pick the right theme to show for the layout). In the future, we'll use this to drive additional features - such as rendering the action bar (which is associated with the activity), a place to add onClick handlers, etc.

The reason this is a tools: namespace attribute is that this is only a designtime mapping for use by the tool. The layout itself can be used by multiple activities/fragments etc. We just want to give you a way to pick a designtime binding such that we can for example show the right theme; you can change it at any time, just like you can change our listview and fragment bindings, etc.

(Here's the full changeset which has more details on this)

And yeah, the link Nikolay listed above shows how the new configuration chooser looks and works

One more thing: The "tools" namespace is special. The android packaging tool knows to ignore it, so none of those attributes will be packaged into the APK. We're using it for extra metadata in the layout. It's also where for example the attributes to suppress lint warnings are stored -- as tools:ignore.

Ng-model does not update controller value

"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.

Controller

$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works
}

Template

<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats. The child-scope creates it's own value and a name conflict is born as illustrated here:

See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

Android intent for playing video?

from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();

startVideo(b.getString(uri));

Cannot receive the uri from here:

public void playsquirrelmp4(View v) {
    Intent VideoIntent = (new Intent(this, VideoActivity.class));
    VideoIntent.putExtra("android.resource://" + getPackageName()
        + "/"+   R.raw.squirrel, uri);
    startActivity(VideoIntent);
}

Migration: Cannot add foreign key constraint

For me, the issue was an old table was using MyISAM and not InnoDB. This fixed it

    $tables = [
        'table_1',
        'table_2'
    ];

    foreach ($tables as $table) {
        \DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
    }

Angularjs autocomplete from $http

Use angular-ui-bootstrap's typehead.

It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.

(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)

Convert String to int array in java

    final String[] strings = {"1", "2"};
    final int[] ints = new int[strings.length];
    for (int i=0; i < strings.length; i++) {
        ints[i] = Integer.parseInt(strings[i]);
    }

php resize image on upload

// This was my example that I used to automatically resize every inserted photo to 100 by 50 pixel and image format to jpeg hope this helps too

if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
    $target_filename = $_FILES['photo']['tmp_name'];
    $fn = $_FILES['photo']['tmp_name'];
    $size = getimagesize( $fn );
    $ratio = $size[0]/$size[1]; // width/height
    if( $ratio > 1) {
        $width = $maxDimW;
        $height = $maxDimH/$ratio;
    } else {
        $width = $maxDimW*$ratio;
        $height = $maxDimH;
    }
    $src = imagecreatefromstring(file_get_contents($fn));
    $dst = imagecreatetruecolor( $width, $height );
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );

    imagejpeg($dst, $target_filename); // adjust format as needed


}

move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);

How do I create a new class in IntelliJ without using the mouse?

In my (linux mint) system I can not get working combination alt+insert so I do the next steps:

alt+1 (navigate to "tree") --> "context button - analog right mouse click" (between right alt and ctrl) -- then with arrows (up or down) desired choice (create new class or package or ...)

Hope it helps some "mint" owners )).

How to extract .war files in java? ZIP vs JAR

For mac users: in terminal command :

unzip yourWARfileName.war

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Save Javascript objects in sessionStorage

You could also use the store library which performs it for you with crossbrowser ability.

example :

// Store current user
store.set('user', { name:'Marcus' })

// Get current user
store.get('user')

// Remove current user
store.remove('user')

// Clear all keys
store.clearAll()

// Loop over all stored values
store.each(function(value, key) {
    console.log(key, '==', value)
})

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:

=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1 

This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:

=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1

For weeks beginning on Tuesday, use:

=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1

etc.

I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

Int or Number DataType for DataAnnotation validation attribute

almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.

I managed it by adding data-val-number to the input field the use localization on the message:

<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I enabled zlib.output_compression in php.ini and it seemed to fix the issue for me.

Uninstall old versions of Ruby gems

bundler clean

Stopped the message showing for me, as a last step after I tried all of the above.

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

JavaScript string and number conversion

You can do it like this:

// step 1 
var one = "1" + "2" + "3"; // string value "123"

// step 2
var two = parseInt(one); // integer value 123

// step 3
var three = 123 + 100; // integer value 223

// step 4
var four = three.toString(); // string value "223"

jQuery: Currency Format Number

Here is the cool regex style for digit grouping:

thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

Going to a specific line number using Less in Unix

You can use sed for this too -

sed -n '320123'p filename 

This will print line number 320123.

If you want a range then you can do -

sed -n '320123,320150'p filename 

If you want from a particular line to the very end then -

sed -n '320123,$'p filename 

JSON parsing using Gson for Java

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();

Hope this helps.

.htaccess rewrite subdomain to directory

This redirects to the same folder to a subdomain:

.httaccess

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain\.com/subdomains/%1

wget: unable to resolve host address `http'

remove the http or https from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip . this worked fine for me.

Firebug-like debugger for Google Chrome

This doesn't answer your question but, in case you missed it, Chris Pederick's Web Developer is now available for Chrome: https://chrome.google.com/extensions/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm.

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Make sure that the controller has a parameterless public constructor error

I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.

For example:

Defining UnityContainer:

var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);

SiteController (the wrong way - notice repo type):

private readonly DashboardRepository _repo;

public SiteController(DashboardRepository repo)
{
    _repo = repo;
}

SiteController (the right way):

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

How to start/stop/restart a thread in Java?

There's a difference between pausing a thread and stopping/killing it. If stopping for you mean killing the thread, then a restart simply means creating a new thread and launching.

There are methods for killing threads from a different thread (e.g., your spawner), but they are unsafe in general. It might be safer if your thread constantly checks some flag to see if it should continue (I assume there is some loop in your thread), and have the external "controller" change the state of that flag.

You can see a little more in: http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

May I ask why you want to kill the thread and restart it? Why not just have it wait until its services are needed again? Java has synchronization mechanisms exactly for that purpose. The thread will be sleeping until the controller notifies it to continue executing.

application/x-www-form-urlencoded or multipart/form-data?

If you need to use Content-Type=x-www-urlencoded-form then DO NOT use FormDataCollection as parameter: In asp.net Core 2+ FormDataCollection has no default constructors which is required by Formatters. Use IFormCollection instead:

 public IActionResult Search([FromForm]IFormCollection type)
    {
        return Ok();
    }

Using quotation marks inside quotation marks

You need to escape it. (Using Python 3 print function):

>>> print("The boy said \"Hello!\" to the girl")
The boy said "Hello!" to the girl
>>> print('Her name\'s Jenny.')
Her name's Jenny.

See the python page for string literals.

Resize to fit image in div, and center horizontally and vertically

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

Why the value had to be given in yyyy-MM-dd?

According to the input type = date spec of HTML 5, the value has to be in the format yyyy-MM-dd since it takes the format of a valid full-date which is specified in RFC3339 as

full-date = date-fullyear "-" date-month "-" date-mday

There is nothing to do with Angularjs since the directive input doesn't support date type.

How do I get Firefox to accept my formatted value in the date input?

FF doesn't support date type of input for at least up to the version 24.0. You can get this info from here. So for right now, if you use input with type being date in FF, the text box takes whatever value you pass in.

My suggestion is you can use Angular-ui's Timepicker and don't use the HTML5 support for the date input.

node.js: cannot find module 'request'

if some module you cant find, try with Static URI, for example:

var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");

This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel

How do I download a binary file over HTTP?

Following solutions will first read the whole content to memory before writing it to disc (for more i/o efficient solutions look at the other answers).

You can use open-uri, which is a one liner

require 'open-uri'
content = open('http://example.com').read

Or by using net/http

require 'net/http'
File.write("file_name", Net::HTTP.get(URI.parse("http://url.com")))

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

How to use Typescript with native ES6 Promises

I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",

CURL and HTTPS, "Cannot resolve host"

Your getting the error because you're probably doing it on your Local server environment. You need to skip the certificates check when the cURL call is made. For that just add the following options

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST,  0);

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

Create list or arrays in Windows Batch

I like this way:

set list=a;^
b;^
c;^ 
d;


for %%a in (%list%) do ( 
 echo %%a
 echo/
)

Reading json files in C++

Here is another easier possibility to read in a json file:

#include "json/json.h"

std::ifstream file_input("input.json");
Json::Reader reader;
Json::Value root;
reader.parse(file_input, root);
cout << root;

You can then get the values like this:

cout << root["key"]

How to overlay images

You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/

In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.

Hope this helps!

-Dave

Get a random boolean in python?

u could try this it produces randomly generated array of true and false :

a=[bool(i) for i in np.array(np.random.randint(0,2,10))]

out: [True, True, True, True, True, False, True, False, True, False]

Find the 2nd largest element in an array with minimum number of comparisons

Suppose provided array is inPutArray = [1,2,5,8,7,3] expected O/P -> 7 (second largest)

 take temp array 
      temp = [0,0], int dummmy=0;
    for (no in inPutArray) {
    if(temp[1]<no)
     temp[1] = no
     if(temp[0]<temp[1]){
    dummmy = temp[0]
    temp[0] = temp[1]
    temp[1] = temp
      }
    }

    print("Second largest no is %d",temp[1])

Synchronous Requests in Node.js

The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.

There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?

You'd want to have a counter, and only call the callback when the data is there:

var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    ucomp = split2[1];
    if(--waiting == 0) callback();
});

request( {url: base + v_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    vcomp = split2[1];
    if(--waiting == 0) callback();
});

function callback() {
    // do math here.
}

Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

Java LinkedHashMap get first or last entry

I know that I came too late but I would like to offer some alternatives, not something extraordinary but some cases that none mentioned here. In case that someone doesn't care so much for efficiency but he wants something with more simplicity(perhaps find the last entry value with one line of code), all this will get quite simplified with the arrival of Java 8 . I provide some useful scenarios.

For the sake of the completeness, I compare these alternatives with the solution of arrays that already mentioned in this post by others users. I sum up all the cases and i think they would be useful(when performance does matter or no) especially for new developers, always depends on the matter of each problem

Possible Alternatives

Usage of Array Method

I took it from the previous answer to to make the follow comparisons. This solution belongs @feresr.

  public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }

Usage of ArrayList Method

Similar to the first solution with a little bit different performance

public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

Reduce Method

This method will reduce the set of elements until getting the last element of stream. In addition, it will return only deterministic results

public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

SkipFunction Method

This method will get the last element of the stream by simply skipping all the elements before it

public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

Iterable Alternative

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too

public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

Here is the full source code

import com.google.common.collect.Iterables;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PerformanceTest {

    private static long startTime;
    private static long endTime;
    private static LinkedHashMap<Integer, String> linkedmap;

    public static void main(String[] args) {
        linkedmap = new LinkedHashMap<Integer, String>();

        linkedmap.put(12, "Chaitanya");
        linkedmap.put(2, "Rahul");
        linkedmap.put(7, "Singh");
        linkedmap.put(49, "Ajeet");
        linkedmap.put(76, "Anuj");

        //call a useless action  so that the caching occurs before the jobs starts.
        linkedmap.entrySet().forEach(x -> {});



        startTime = System.nanoTime();
        FindLasstEntryWithArrayListMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayListMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");


         startTime = System.nanoTime();
        FindLasstEntryWithArrayMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithReduceMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithReduceMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithSkipFunctionMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithSkipFunctionMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.currentTimeMillis();
        FindLasstEntryWithGuavaIterable();
        endTime = System.currentTimeMillis();
        System.out.println("FindLasstEntryWithGuavaIterable : " + "took " + (endTime - startTime) + " milliseconds");


    }

    public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

    public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

    public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

    public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

    public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }
}

Here is the output with performance of each method

FindLasstEntryWithArrayListMethod : took 0.162 milliseconds
FindLasstEntryWithArrayMethod : took 0.025 milliseconds
FindLasstEntryWithReduceMethod : took 2.776 milliseconds
FindLasstEntryWithSkipFunctionMethod : took 3.396 milliseconds
FindLasstEntryWithGuavaIterable : took 11 milliseconds

UITextField border color

borderColor on any view(or UIView Subclass) could also be set using storyboard with a little bit of coding and this approach could be really handy if you're setting border color on multiple UI Objects.

Below are the steps how to achieve it,

  1. Create a category on CALayer class. Declare a property of type UIColor with a suitable name, I'll name it as borderUIColor .
  2. Write the setter and getter for this property.
  3. In the 'Setter' method just set the "borderColor" property of layer to the new colors CGColor value.
  4. In the 'Getter' method return UIColor with layer's borderColor.

P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.

Please have a look at the below code sample;

Objective C:

Interface File:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer (BorderProperties)

// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;

@end

Implementation File:

#import "CALayer+BorderProperties.h"

@implementation CALayer (BorderProperties)

- (void)setBorderUIColor:(UIColor *)color {
    self.borderColor = color.CGColor;
}

- (UIColor *)borderUIColor {
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Swift 2.0:

extension CALayer {
var borderUIColor: UIColor {
    set {
        self.borderColor = newValue.CGColor
    }

    get {
        return UIColor(CGColor: self.borderColor!)
    }
}
}

And finally go to your storyboard/XIB, follow the remaining steps;

  1. Click on the View object for which you want to set border Color.
  2. Click on "Identity Inspector"(3rd from Left) in "Utility"(Right side of the screen) panel.
  3. Under "User Defined Runtime Attributes", click on the "+" button to add a key path.
  4. Set the type of the key path to "Color".
  5. Enter the value for key path as "layer.borderUIColor". [Remember this should be the variable name you declared in category, not borderColor here it's borderUIColor].
  6. Finally chose whatever color you want.

You've to set layer.borderWidth property value to at least 1 to see the border color.

Build and Run. Happy Coding. :)

How many bytes in a JavaScript string?

I'm working with an embedded version of the V8 Engine. I've tested a single string. Pushing each step 1000 characters. UTF-8.

First test with single byte (8bit, ANSI) Character "A" (hex: 41). Second test with two byte character (16bit) "O" (hex: CE A9) and the third test with three byte character (24bit) "?" (hex: E2 98 BA).

In all three cases the device prints out of memory at 888 000 characters and using ca. 26 348 kb in RAM.

Result: The characters are not dynamically stored. And not with only 16bit. - Ok, perhaps only for my case (Embedded 128 MB RAM Device, V8 Engine C++/QT) - The character encoding has nothing to do with the size in ram of the javascript engine. E.g. encodingURI, etc. is only useful for highlevel data transmission and storage.

Embedded or not, fact is that the characters are not only stored in 16bit. Unfortunally I've no 100% answer, what Javascript do at low level area. Btw. I've tested the same (first test above) with an array of character "A". Pushed 1000 items every step. (Exactly the same test. Just replaced string to array) And the system bringt out of memory (wanted) after 10 416 KB using and array length of 1 337 000. So, the javascript engine is not simple restricted. It's a kind more complex.

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

How to clear Facebook Sharer cache?

I found a solution to my problem. You could go to this site:

https://developers.facebook.com/tools/debug

...then put in the URL of the page you want to share, and click "debug". It will automatically extract all the info on your meta tags and also clear the cache.

Datetime equal or greater than today in MySQL

SELECT * FROM table_name WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) ,  '-', SUBSTRING( json_date, 7, 2 ) ,  '-', SUBSTRING(json_date, 3, 2 ) ) >= NOW();

json_date ["05/11/2011"]

Property '...' has no initializer and is not definitely assigned in the constructor

The error is legitimate and may prevent your app from crashing. You typed makes as an array but it can also be undefined.

You have 2 options (instead of disabling the typescript's reason for existing...):

1. In your case the best is to type makes as possibily undefined.

makes?: any[]
// or
makes: any[] | undefined

In this case the compiler will inform you whenever you try to access to makes that it could be undefined. For exemple if the // <-- Not ok lines below are executed before getMakes finished or if getMakes fails, your app will crash and a runetime error will be thrown.

makes[0] // <-- Not ok
makes.map(...) // <-- Not ok

if (makes) makes[0] // <-- Ok
makes?.[0] // <-- Ok
(makes ?? []).map(...) // <-- Ok

2. You can assume that it will never fail and that you will never try to access it before initialization by writing the code below (risky!). So the compiler won't take care about it.

makes!: any[]

How to make an app's background image repeat

Ok, here's what I've got in my app. It includes a hack to prevent ListViews from going black while scrolling.

drawable/app_background.xml:

<?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/actual_pattern_image"
        android:tileMode="repeat" />

values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="app_theme" parent="android:Theme">
    <item name="android:windowBackground">@drawable/app_background</item>
    <item name="android:listViewStyle">@style/TransparentListView</item>
    <item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
  </style>

  <style name="TransparentListView" parent="@android:style/Widget.ListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

  <style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

</resources>

AndroidManifest.xml:

//
<application android:theme="@style/app_theme">
//

Is there a way to create and run javascript in Chrome?

Try this:
1. Install Node.js from https://nodejs.org/
2. Place your JavaScript code into a .js file (e.g. someCode.js)
3. Open a cmd shell (or Terminal on Mac) and use Node's Read-Eval-Print-Loop (REPL) to execute someCode.js like this:
> node someCode.js

Hope this helps!

Exact time measurement for performance testing

I'm using this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();

timer.Start();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

statusCode = response.StatusCode.ToString();

response.Close();

timer.Stop();

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

+(False) converts to 0 and +(True) converts to 1

How to detect Safari, Chrome, IE, Firefox and Opera browser?

We can use below util methods

utils.isIE = function () {
        var ver = navigator.userAgent;
        return ver.indexOf("MSIE") !== -1 || ver.indexOf("Trident") !== -1; // need to check for Trident for IE11
    };

    utils.isIE32 = function () {
        return (utils.isIE() && navigator.appVersion.indexOf('Win64') === -1);
    };

    utils.isChrome = function () {
        return (window.chrome);
    };

    utils.isFF64 = function () {
        var agent = navigator.userAgent;
        return (agent.indexOf('Win64') >= 0 && agent.indexOf('Firefox') >= 0);
    };

    utils.isFirefox = function () {
        return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
    };

php exec command (or similar) to not wait for result

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');

using jQuery .animate to animate a div from right to left?

If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0

CSS:

.parent{
width:100%;
position:relative;
}

#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}

Javascript:

$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
                }),
    headers:     headers(true)
   };
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));
    };
  }

"Unmappable character for encoding UTF-8" error

I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.

 <javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
     includeantruntime="false" source="${java.level}" target="${java.level}"

     encoding="iso-8859-1">

     <src path="${production.dir}" />
 </javac>

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Take these two scenarios:

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

If opt doesn't contain a value, the two are indeed equivalent. But if opt does contain a value, how many Foo objects will be created?

P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

com.android.build.transform.api.TransformException

I resolved it with the next:

I configured multidex

In build.gradle you need to add the next one.

android {
...
   defaultConfig {
       ...
       // Enabling multidex support.
       multiDexEnabled true
       ...
   }
   dexOptions {
      incremental true
      maxProcessCount 4 // this is the default value
      javaMaxHeapSize "2g"
   }
...
}
dependencies {
...
   compile 'com.android.support:multidex:1.0.1'
...
}

Add the next one in local.properties

org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

After that into Application class you need to add the Multidex too.

 public class MyApplication extends MultiDexApplication {

   @Override
   public void onCreate() {
       super.onCreate();
       //mas codigo
   }

   @Override
   protected void attachBaseContext(Context base) {
       super.attachBaseContext(base);
       MultiDex.install(this);
   }
}

Don't forget add the line code into Manifest.xml

<application
    ...
    android:name=".MyApplication"
    ...
/>

That's it with this was enough for resolve the bug: Execution failed for task ':app:transformClassesWithDexForDebug. Check very well into build.gradle with javaMaxHeapSize "2g" and the local.properties org.gradle.jvmargs=-Xmx2048m are of 2 gigabyte.

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

What are the differences between a pointer variable and a reference variable in C++?

There is a semantic difference that may appear esoteric if you are not familiar with studying computer languages in an abstract or even academic fashion.

At the highest-level, the idea of references is that they are transparent "aliases". Your computer may use an address to make them work, but you're not supposed to worry about that: you're supposed to think of them as "just another name" for an existing object and the syntax reflects that. They are stricter than pointers so your compiler can more reliably warn you when you about to create a dangling reference, than when you are about to create a dangling pointer.

Beyond that, there are of course some practical differences between pointers and references. The syntax to use them is obviously different, and you cannot "re-seat" references, have references to nothingness, or have pointers to references.

Configure apache to listen on port other than 80

For FC22 server

cd /etc/httpd/conf edit httpd.conf [enter]

Change: Listen 80 to: Listen whatevernumber

Save the file

systemctl restart httpd.service [enter] if required, open whatevernumber in your router / firewall

Python element-wise tuple operations like sum

from numpy import array

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

gives array([4,4,4]).

See http://www.scipy.org/Tentative_NumPy_Tutorial

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Or you can: hadoop fs -rm -r PATH

Hint: if you enter: hadoop fs -rmr PATH you would mostly get:Please use 'rm -r' instead.

Remove object from a list of objects in python

In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:

my_list = [1,2,4,6,7]

del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list

In your case the appropriate method to use is pop, because it takes the index to be removed:

x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]

Logical operators for boolean indexing in Pandas

Logical operators for boolean indexing in Pandas

It's important to realize that you cannot use any of the Python logical operators (and, or or not) on pandas.Series or pandas.DataFrames (similarly you cannot use them on numpy.arrays with more than one element). The reason why you cannot use those is because they implicitly call bool on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.

NumPys logical functions

However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array, pandas.Series, pandas.DataFrame, or any other (conforming) numpy.array subclass:

So, essentially, one should use (assuming df1 and df2 are pandas DataFrames):

np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)

Bitwise functions and bitwise operators for booleans

However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):

Typically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:

(df1 < 10) | (df2 > 10)  # instead of the wrong df1 < 10 | df2 > 10

This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10 (where a and b are for example simple integers) and don't need the parenthesis.

Differences between logical and bitwise operations (on non-booleans)

It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:

>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])

>>> np.logical_and(a1, a2)
array([False, False, False,  True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)

And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:

>>> a3 = np.array([1, 2, 3, 4])

>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])

Summary table

Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
       and       |  np.logical_and        | np.bitwise_and         |        &
-------------------------------------------------------------------------------------
       or        |  np.logical_or         | np.bitwise_or          |        |
-------------------------------------------------------------------------------------
                 |  np.logical_xor        | np.bitwise_xor         |        ^
-------------------------------------------------------------------------------------
       not       |  np.logical_not        | np.invert              |        ~

Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise. However be careful with the bitwise invert on plain Python bools because the bool will be interpreted as integers in this context (for example ~False returns -1 and ~True returns -2).

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance :

TL;DR

Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.

Sorted by performance:

  1. isInstance
  2. instanceof (+ 0.5%)
  3. isAssignableFrom (+ 2.7%)

Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.

In theory

Using a soft like bytecode viewer we can translate each operator into bytecode.

In the context of:

package foo;

public class Benchmark
{
  public static final Object a = new A();
  public static final Object b = new B();

  ...

}

JAVA:

b instanceof A;

Bytecode:

getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A

JAVA:

A.class.isInstance(b);

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);

JAVA:

A.class.isAssignableFrom(b.getClass());

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);

Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.

The benchmark

Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):

class A {}
class B extends A {}

public class Benchmark {

    public static final Object a = new A();
    public static final Object b = new B();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testInstanceOf()
    {
        return b instanceof A;
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsInstance()
    {
        return A.class.isInstance(b);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsAssignableFrom()
    {
        return A.class.isAssignableFrom(b.getClass());
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TestPerf2.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(2000)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Gave the following results (score is a number of operations in a time unit, so the higher the score the better):

Benchmark                       Mode   Cnt    Score   Error   Units
Benchmark.testIsInstance        thrpt  2000  373,061 ± 0,115  ops/us
Benchmark.testInstanceOf        thrpt  2000  371,047 ± 0,131  ops/us
Benchmark.testIsAssignableFrom  thrpt  2000  363,648 ± 0,289  ops/us

Warning

  • the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
  • the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
  • it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
  • in relation to the previous point, instanceof in the context of your code might get optimized more easily than an isInstance for example...

To give you an example, take the following loop:

class A{}
class B extends A{}

A b = new B();

boolean execute(){
  return A.class.isAssignableFrom(b.getClass());
  // return A.class.isInstance(b);
  // return b instanceof A;
}

// Warmup the code
for (int i = 0; i < 100; ++i)
  execute();

// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
   execute();
}
final long elapsed = System.nanoTime() - start;

Thanks to the JIT, the code is optimized at some point and we get:

  • instanceof: 6ms
  • isInstance: 12ms
  • isAssignableFrom : 15ms

Note

Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details

Related questions

Best way to unselect a <select> in jQuery?

A quick google found this post that describes how to do what you want for both single and multiple select lists in IE. The solution seems pretty elegant as well:

$('#clickme').click(function() {
        $('#selectmenu option').attr('selected', false);

}); 

Inner Joining three tables

Just do the same thing agin but then for TableC

SELECT *
FROM dbo.tableA A 
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common

How do you detect where two line segments intersect?

A C++ program to check if two given line segments intersect

#include <iostream>
using namespace std;

struct Point
{
    int x;
    int y;
};

// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
    if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
        q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
       return true;

    return false;
}

// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
    // See 10th slides from following link for derivation of the formula
    // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
    int val = (q.y - p.y) * (r.x - q.x) -
              (q.x - p.x) * (r.y - q.y);

    if (val == 0) return 0;  // colinear

    return (val > 0)? 1: 2; // clock or counterclock wise
}

// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);

    // General case
    if (o1 != o2 && o3 != o4)
        return true;

    // Special Cases
    // p1, q1 and p2 are colinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;

    // p1, q1 and p2 are colinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;

    // p2, q2 and p1 are colinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;

     // p2, q2 and q1 are colinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;

    return false; // Doesn't fall in any of the above cases
}

// Driver program to test above functions
int main()
{
    struct Point p1 = {1, 1}, q1 = {10, 1};
    struct Point p2 = {1, 2}, q2 = {10, 2};

    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {10, 0}, q1 = {0, 10};
    p2 = {0, 0}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {-5, -5}, q1 = {0, 0};
    p2 = {1, 1}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    return 0;
}

Show a PDF files in users browser via PHP/Perl

You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)

move_uploaded_file gives "failed to open stream: Permission denied" error

Just change the permission of tmp_file_upload to 755 Following is the command chmod -R 755 tmp_file_upload

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

How to get a context in a recycler view adapter

You can define:

Context ctx; 

And on onCreate initialise ctx to:

ctx=parent.getContext(); 

Note: Parent is a ViewGroup.

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

How do I get the name of the active user via the command line in OS X?

You can also use the logname command from the BSD General Commands Manual under Linux or MacOS to see the username of the user currently logged in, even if the user is performing a sudo operation. This is useful, for instance, when modifying a user's crontab while installing a system-wide package with sudo: crontab -u $(logname)

Per man logname:

LOGNAME(1)

NAME
    logname -- display user's login name

Command to list all files in a folder as well as sub-folders in windows

If you simply need to get the basic snapshot of the files + folders. Follow these baby steps:

  • Press Windows + R
  • Press Enter
  • Type cmd
  • Press Enter
  • Type dir -s
  • Press Enter

Send a SMS via intent

This is another solution using SMSManager:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("PhoneNumber-example:+989147375410", null, "SMS Message Body", null, null);

Filter LogCat to get only the messages from My Application in Android?

For windows, you can use my PowerShell script to show messages for your app only: https://github.com/AlShevelev/power_shell_logcat

javascript: pause setTimeout();

Something like this should do the trick.

function Timer(fn, countdown) {
    var ident, complete = false;

    function _time_diff(date1, date2) {
        return date2 ? date2 - date1 : new Date().getTime() - date1;
    }

    function cancel() {
        clearTimeout(ident);
    }

    function pause() {
        clearTimeout(ident);
        total_time_run = _time_diff(start_time);
        complete = total_time_run >= countdown;
    }

    function resume() {
        ident = complete ? -1 : setTimeout(fn, countdown - total_time_run);
    }

    var start_time = new Date().getTime();
    ident = setTimeout(fn, countdown);

    return { cancel: cancel, pause: pause, resume: resume };
}

Where does Chrome store cookies?

Actually the current browsing path to the Chrome cookies in the address bar is: chrome://settings/content/cookies

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.

This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!

  • The Video shows you the JavaFx Sdk download
  • How to set it as a Global Library
  • Set the module-info.java (i prefer the bottom one)

module thisIsTheNameOfYourProject {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens sample;
}

The entire thing took me only 5mins !!!

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Find all controls in WPF Window by type

I wanted to add a comment but I have less than 50 pts so I can only "Answer". Be aware that if you use the "VisualTreeHelper" method to retrieve XAML "TextBlock" objects then it will also grab XAML "Button" objects. If you re-initialize the "TextBlock" object by writing to the Textblock.Text parameter then you will no longer be able to change the Button text using the Button.Content parameter. The Button will permanently show the text written to it from the Textblock.Text write action (from when it was retrieved --

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
   tb.Text = ""; //this will overwrite Button.Content and render the 
                 //Button.Content{set} permanently disabled.
}

To work around this, you can try using a XAML "TextBox" and add methods (or Events) to mimic a XAMAL Button. XAML "TextBox" is not gathered by a search for "TextBlock".

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

What's the difference between Unicode and UTF-8?

Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!

disable editing default value of text input

I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled attribute.

<input disabled="disabled" id="price_from" value="price from ">

Declare an array in TypeScript

this is how you can create an array of boolean in TS and initialize it with false:

var array: boolean[] = [false, false, false]

or another approach can be:

var array2: Array<boolean> =[false, false, false] 

you can specify the type after the colon which in this case is boolean array

C# string replace

The simplest way is to do

line.Replace(@",", @";");

Output is shown as below:

enter image description here

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

"Default Activity Not Found" on Android Studio upgrade

If you see that error occur after upgrading versions of IntelliJ IDEA or Android Studio, or after Generating a new APK, you may need to refresh the IDE's cache.

File -> Invalidate Caches / Restart...

How to draw border around a UILabel?

Swift 3/4 with @IBDesignable


While almost all the above solutions work fine but I would suggest an @IBDesignable custom class for this.

@IBDesignable
class CustomLabel: UILabel {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }
}

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

HTML.ActionLink method

Use named parameters for readability and to avoid confusions.

@Html.ActionLink(
            linkText: "Click Here",
            actionName: "Action",
            controllerName: "Home",
            routeValues: new { Identity = 2577 },
            htmlAttributes: null)

Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

get all characters to right of last dash

You could use LINQ, and save yourself the explicit parsing:

string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();

Console.WriteLine(lastFragment);

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

There's a couple of different memory settings for good reason.

The eclipse memory setting is because Eclipse is a large java program. if you are going to have a huge amount of files open in a couple of projects, then you're going to want to give Eclipse more ram. This is an issue only on "enterprise" systems normally personal projects wont use that many file handles or interfaces.

The JRE setting is how much ram to allow the java runtime when you run your project. This is probably the one you want when you are running some memory hogging application. I've run mathematical projects that needed a few gigs of ram and had to really tell the JRE it was okay, the JVM kept assuming my program was in some leaky runaway state, but I was doing it on purpose, and had to tell JVM specifically what it was allowed to use.

Then Catalina's memory setting is for the application server Tomcat. That server needs memory for each application and concurrent users. This blends with the JRE number because your project might be a web application and I'm not sure which one needs the memory.

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

Commenting multiple lines in DOS batch file

Another option is to enclose the unwanted lines in an IF block that can never be true

if 1==0 (
...
)

Of course nothing within the if block will be executed, but it will be parsed. So you can't have any invalid syntax within. Also, the comment cannot contain ) unless it is escaped or quoted. For those reasons the accepted GOTO solution is more reliable. (The GOTO solution may also be faster)

Update 2017-09-19

Here is a cosmetic enhancement to pdub's GOTO solution. I define a simple environment variable "macro" that makes the GOTO comment syntax a bit better self documenting. Although it is generally recommended that :labels are unique within a batch script, it really is OK to embed multiple comments like this within the same batch script.

@echo off
setlocal

set "beginComment=goto :endComment"

%beginComment%
Multi-line comment 1
goes here
:endComment

echo This code executes

%beginComment%
Multi-line comment 2
goes here
:endComment

echo Done

Or you could use one of these variants of npocmaka's solution. The use of REM instead of BREAK makes the intent a bit clearer.

rem.||(
   remarks
   go here
)

rem^ ||(
   The space after the caret
   is critical
)

Converting milliseconds to a date (jQuery/JavaScript)

Below is a snippet to enable you format the date to a desirable output:

var time = new Date();
var time = time.getTime();

var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();

document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);

Android, Java: HTTP POST Request

HTTP request POST in java does not dump the answer?

public class HttpClientExample 
{
 private final String USER_AGENT = "Mozilla/5.0";
 public static void main(String[] args) throws Exception 
 {

HttpClientExample http = new HttpClientExample();

System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();

}

 // HTTP POST request
 private void sendPost() throws Exception {
 String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("User-Agent", USER_AGENT);

List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
        urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

 BufferedReader rd = new BufferedReader(new 
 InputStreamReader(response.getEntity().getContent()));

  StringBuilder result = new StringBuilder();
  String line = "";
  while ((line = rd.readLine()) != null) 
        {
      result.append(line);
                System.out.println(line);
    }

   }
 }

This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

jQuery Date Picker - disable past dates

$( "#date" ).datetimepicker({startDate:new Date()}).datetimepicker('update', new Date());

new Date() : function get the todays date previous date are locked. 100% working

CMAKE_MAKE_PROGRAM not found

Well, if it is useful, I have had several problems with cmake, including this one. They all disappeared when I fix the global variable (in my case the MinGW Codeblocks) PATH in the system. When the codeblocks install is not in default, and for some unknow reason, this global variable does not point to the right place. Check if the path of Codeblocks or MinGW are correct:

Right click on "My Computer"> Properties> Advanced Properties or Advanced> Environment Variables> to Change the PATH variable

It worked for me;)

How to create a checkbox with a clickable label?

In Angular material label with checkbox

<mat-checkbox>Check me!</mat-checkbox>

Regex for Comma delimited list

It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.

([1-9][0-9]*,[ ])*[1-9][0-9]*

Here's how I built that mentally:

[0-9]  any digit.
[1-9][0-9]*  leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ]  as above, followed by a space
([1-9][0-9]*[ ])*  as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]*  as above, with a final number that doesn't have a comma.

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Gets byte array from a ByteBuffer in java

final ByteBuffer buffer;
if (buffer.hasArray()) {
    final byte[] array = buffer.array();
    final int arrayOffset = buffer.arrayOffset();
    return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
                              arrayOffset + buffer.limit());
}
// do something else

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

Class name does not name a type in C++

Aren't you missing the #include "B.h" in A.h?

Creating a list of pairs in java

If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.

Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.

How to join multiple lines of file names into one with custom delimiter?

If Python3 is your cup of tea, you can do this (but please explain why you would?):

ls -1 | python -c "import sys; print(','.join(sys.stdin.read().splitlines()))"

JWT (JSON Web Token) automatic prolongation of expiration

In the case where you handle the auth yourself (i.e don't use a provider like Auth0), the following may work:

  1. Issue JWT token with relatively short expiry, say 15min.
  2. Application checks token expiry date before any transaction requiring a token (token contains expiry date). If token has expired, then it first asks API to 'refresh' the token (this is done transparently to the UX).
  3. API gets token refresh request, but first checks user database to see if a 'reauth' flag has been set against that user profile (token can contain user id). If the flag is present, then the token refresh is denied, otherwise a new token is issued.
  4. Repeat.

The 'reauth' flag in the database backend would be set when, for example, the user has reset their password. The flag gets removed when the user logs in next time.

In addition, let's say you have a policy whereby a user must login at least once every 72hrs. In that case, your API token refresh logic would also check the user's last login date from the user database and deny/allow the token refresh on that basis.

Using grep and sed to find and replace a string

Not sure if this will be helpful but you can use this with a remote server like the example below

ssh example.server.com "find /DIR_NAME -type f -name "FILES_LOOKING_FOR" -exec sed -i 's/LOOKINGFOR/withThisString/g' {} ;"

replace the example.server.com with your server replace DIR_NAME with your directory/file locations replace FILES_LOOKING_FOR with files you are looking for replace LOOKINGFOR with what you are looking for replace withThisString with what your want to be replaced in the file

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

How can I share Jupyter notebooks with non-programmers?

The "best" way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it's certainly more complex; there's no built-in way to do this in Jupyter alone, but a couple of options are:

Host your own nbviewer

GitHub and the Jupyter Notebook Veiwer both use the same tool to render .ipynb files into static HTML, this tool is nbviewer.

The installation instructions are more complex than I'm willing to go into here but if your company/team has a shared server that doesn't require password access then you could host the nbviewer on that server and direct it to load from your credentialed server. This will probably require some more advanced configuration than you're going to find in the docs.

Set up a deployment script

If you don't necessarily need live updating HTML then you could set up a script on your credentialed server that will simply use Jupyter's built-in export options to create the static HTML files and then send those to a more publicly accessible server.

What is Android's file system?

Most answers here are pretty old.

In the past when un managed nand was the most popular storage technology, yaffs2 was the most common file system. This days there are few devices using un-managed nand, and those still in use are slowly migrating to ubifs.

Today most common storage is emmc (managed nand), for such devices ext4 is far more popular, but, this file system is slowly clears its way for f2fs (flash friendly fs).

Edit: f2fs will probably won't make it as the common fs for flash devices (including android)

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Thank you, that worked! But I replaced this

AllowOverride AuthConfig Indexes

with that

AllowOverride All

Otherwise, the .htaccess didn't work: I got problems with the RewriteEngine and the error message "RewriteEngine not allowed here".

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

Automatically run %matplotlib inline in IPython Notebook

In your ipython_config.py file, search for the following lines

# c.InteractiveShellApp.matplotlib = None

and

# c.InteractiveShellApp.pylab = None

and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

jQuery click not working for dynamically created items

$("#container").delegate("span", "click", function (){
    alert(11);
});

What is middleware exactly?

Some examples of middleware: CORBA, Remote Method Invocation (RMI),...

The examples mentioned above are all pieces of software allowing you to take care of communication between different processes (either running on the same machine or distributed over e.g. the internet).

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

How do I loop through or enumerate a JavaScript object?

An object becomes an iterator when it implements the .next() method

_x000D_
_x000D_
const james = {
  name: 'James',
  height: `5'10"`,
  weight: 185,

  [Symbol.iterator]() {
    let properties = []
    for (let key of Object.keys(james)) {
      properties.push(key);
    }

    index = 0;
    return {
      next: () => {
        let key = properties[index];
        let value = this[key];
        let done = index >= properties.length - 1;
        index++;
        return {
          key,
          value,
          done
        };
      }
    };
  }

};


const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
_x000D_
_x000D_
_x000D_

Comparing chars in Java

Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.

Alternatively you could put your valid values into an array and check for the existence of symbol in the array.

List of remotes for a Git repository?

The answers so far tell you how to find existing branches:

git branch -r

Or repositories for the same project [see note below]:

git remote -v

There is another case. You might want to know about other project repositories hosted on the same server.

To discover that information, I use SSH or PuTTY to log into to host and ls to find the directories containing the other repositories. For example, if I cloned a repository by typing:

git clone ssh://git.mycompany.com/git/ABCProject

and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:

ls /git

assuming ls says:

 ABCProject DEFProject

I can use the command

 git clone ssh://git.mycompany.com/git/DEFProject

to gain access to the other project.

NOTE: Usually git remote simply tells me about origin -- the repository from which I cloned the project. git remote would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.

Nullable type as a generic parameter possible?

This may be a dead thread, but I tend to use the following:

public static T? GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct 
{
    return reader[columnName] as T?;
}

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

from tensorflow.python.client import device_lib
print device_lib.list_local_devices()

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf

How can I center text (horizontally and vertically) inside a div block?

Apply style:

position: absolute;
top: 50%;
left: 0;
right: 0;

Your text would be centered irrespective of its length.

Programmatically obtain the phone number of the Android phone

Wouldn't be recommending to use TelephonyManager as it requires the app to require READ_PHONE_STATE permission during runtime.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.

implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
    val googleApiClient = GoogleApiClient.Builder(context)
        .addApi(Auth.CREDENTIALS_API).build()

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
        googleApiClient, hintRequest
    )

    startIntentSenderForResult(
        hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
    )
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PHONE_NUMBER -> {
            if (requestCode == Activity.RESULT_OK) {
                val credential = data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
                val selectedPhoneNumber = credential?.id
            }
        }
    }
}

Get button click inside UITableViewCell

Swift 2.2

You need to add target for that button.

myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)

FunctionName: connected // for example

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

func connected(sender: UIButton) {
    let buttonTag = sender.tag
    // Do any additional setup
}

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

Add padding on view programmatically

Write Following Code to set padding, it may help you.

TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();

layoutparams.setPadding(50,50,50,50);

ApplyPaddingTextView.setLayoutParams(layoutparams);

Use LinearLayout.LayoutParams or RelativeLayout.LayoutParams according to parent layout of the child view

App.Config change value

You cannot use AppSettings static object for this. Try this

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         
configFileMap.ExeConfigFilename = configFile;          
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

config.AppSettings.Settings["YourThing"].Value = "New Value"; 
config.Save(); 

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Python import csv to list

You can use the list() function to convert csv reader object to list

import csv

with open('input.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)
    print(rows)

How to find and replace string?

void replace(char *str, char *strFnd, char *strRep)
{
    for (int i = 0; i < strlen(str); i++)
    {
        int npos = -1, j, k;
        if (str[i] == strFnd[0])
        {
            for (j = 1, k = i+1; j < strlen(strFnd); j++)
                if (str[k++] != strFnd[j])
                    break;
            npos = i;
        }
        if (npos != -1)
            for (j = 0, k = npos; j < strlen(strRep); j++)
                str[k++] = strRep[j];
    }

}

int main()
{
    char pst1[] = "There is a wrong message";
    char pfnd[] = "wrong";
    char prep[] = "right";

    cout << "\nintial:" << pst1;

    replace(pst1, pfnd, prep);

    cout << "\nfinal : " << pst1;
    return 0;
}

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

How to add a line break within echo in PHP?

You have to use br when using echo , like this :

echo "Thanks for your email" ."<br>". "Your orders details are below:"

and it will work properly

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

for gitbash in windows10 look out for the config file in

/.gitconfig file

C++ IDE for Macs

Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.

Clion from JetBrains, also is available now, and uses Cmake as project model.

Module not found: Error: Can't resolve 'core-js/es6'

Just change "target": "es2015" to "target": "es5" in your tsconfig.json.

Work for me with Angular 8.2.XX

Tested on IE11 and Edge