Programs & Examples On #Custom pages

How to use a dot "." to access members of dictionary?

I recently came across the 'Box' library which does the same thing.

Installation command : pip install python-box

Example:

from box import Box

mydict = {"key1":{"v1":0.375,
                    "v2":0.625},
          "key2":0.125,
          }
mydict = Box(mydict)

print(mydict.key1.v1)

I found it to be more effective than other existing libraries like dotmap, which generate python recursion error when you have large nested dicts.

link to library and details: https://pypi.org/project/python-box/

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

How to update the current menu in order to enable or disable the items when an AsyncTask is done.

In my use case I needed to disable my menu while my AsyncTask was loading data, then after loading all the data, I needed to enable all the menu again in order to let the user use it.

This prevented the app to let users click on menu items while data was loading.

First, I declare a state variable , if the variable is 0 the menu is shown, if that variable is 1 the menu is hidden.

private mMenuState = 1; //I initialize it on 1 since I need all elements to be hidden when my activity starts loading.

Then in my onCreateOptionsMenu() I check for this variable , if it's 1 I disable all my items, if not, I just show them all

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_galeria_pictos, menu);

        if(mMenuState==1){
            for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(false);
            }
        }else{
             for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(true);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

Now, when my Activity starts, onCreateOptionsMenu() will be called just once, and all my items will be gone because I set up the state for them at the start.

Then I create an AsyncTask Where I set that state variable to 0 in my onPostExecute()

This step is very important!

When you call invalidateOptionsMenu(); it will relaunch onCreateOptionsMenu();

So, after setting up my state to 0, I just redraw all the menu but this time with my variable on 0 , that said, all the menu will be shown after all the asynchronous process is done, and then my user can use the menu.

 public class LoadMyGroups extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mMenuState = 1; //you can set here the state of the menu too if you dont want to initialize it at global declaration. 

        }

        @Override
        protected Void doInBackground(Void... voids) {
           //Background work

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            mMenuState=0; //We change the state and relaunch onCreateOptionsMenu
            invalidateOptionsMenu(); //Relaunch onCreateOptionsMenu

        }
    }

Results

enter image description here

Python truncate a long string

info = data[:75] + ('..' if len(data) > 75 else '')

How do I declare a global variable in VBA?

To use global variables, Insert New Module from VBA Project UI and declare variables using Global

Global iRaw As Integer
Global iColumn As Integer

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

How do I print a list of "Build Settings" in Xcode project?

Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.

As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:

Target's Build Phases section w/ added Log Build Settings script phase

To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash and the command to export.  You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources.  Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.

The result is this incredibly helpful listing of current environment variables used for building:

Build Log output w/ export command's results

jquery data selector

If you also use jQueryUI, you get a (simple) version of the :data selector with it that checks for the presence of a data item, so you can do something like $("div:data(view)"), or $( this ).closest(":data(view)").

See http://api.jqueryui.com/data-selector/ . I don't know for how long they've had it, but it's there now!

Sorting rows in a data table

It turns out there is a special case where this can be achieved. The trick is when building the DataTable, collect all the rows in a list, sort them, then add them. This case just came up here.

How to get certain commit from GitHub project

Try the following command sequence:

$ git fetch origin <copy/past commit sha1 here>
$ git checkout FETCH_HEAD
$ git push origin master

Change background color of R plot

Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.

plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)

How to filter WooCommerce products by custom attribute

Try WooCommerce Product Filter, plugin developed by Mihajlovicnenad.com. You can filter your products by any criteria. Also, it integrates with your Shop and archive pages perfectly. Here is a screenshot. And this is just one of the layouts, you can customize and make your own. Look at demo site. Thanks! enter image description here

How do I restart nginx only after the configuration test was successful on Ubuntu?

As of nginx 1.8.0, the correct solution is

sudo nginx -t && sudo service nginx reload

Note that due to a bug, configtest always returns a zero exit code even if the config file has an error.

Does Python have a string 'contains' substring method?

Here is your answer:

if "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

For checking if it is false:

if not "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

OR:

if "insert_char_or_string_here" not in "insert_string_to_search_here":
    #DOSTUFF

Pass Method as Parameter using C#

Here is an example without a parameter: http://en.csharp-online.net/CSharp_FAQ:_How_call_a_method_using_a_name_string

with params: http://www.daniweb.com/forums/thread98148.html#

you basically pass in an array of objects along with name of method. you then use both with the Invoke method.

params Object[] parameters

How do I concatenate two arrays in C#?

Here's my answer:

int[] z = new List<string>()
    .Concat(a)
    .Concat(b)
    .Concat(c)
    .ToArray();

This method can be used at initialization level, for example to define a static concatenation of static arrays:

public static int[] a = new int [] { 1, 2, 3, 4, 5 };
public static int[] b = new int [] { 6, 7, 8 };
public static int[] c = new int [] { 9, 10 };

public static int[] z = new List<string>()
    .Concat(a)
    .Concat(b)
    .Concat(c)
    .ToArray();

However, it comes with two caveats that you need to consider:

  • The Concat method creates an iterator over both arrays: it does not create a new array, thus being efficient in terms of memory used: however, the subsequent ToArray  will negate such advantage, since it will actually create a new array and take up the memory for the new array.
  • As @Jodrell said, Concat would be rather inefficient for large arrays: it should only be used for medium-sized arrays.

If aiming for performance is a must, the following method can be used instead:

/// <summary>
/// Concatenates two or more arrays into a single one.
/// </summary>
public static T[] Concat<T>(params T[][] arrays)
{
    // return (from array in arrays from arr in array select arr).ToArray();

    var result = new T[arrays.Sum(a => a.Length)];
    int offset = 0;
    for (int x = 0; x < arrays.Length; x++)
    {
        arrays[x].CopyTo(result, offset);
        offset += arrays[x].Length;
    }
    return result;
}

Or (for one-liners fans):

int[] z = (from arrays in new[] { a, b, c } from arr in arrays select arr).ToArray();

Although the latter method is much more elegant, the former one is definitely better for performance.

For additional info, please refer to this post on my blog.

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

All has great answer on the question, and yes this is only applicable when running it on the current directory not unless you include the absolute path. See my samples below.

Also, the (dot-slash) made sense to me when I've the command on the child folder tmp2 (/tmp/tmp2) and it uses (double dot-slash).

SAMPLE:

[fifiip-172-31-17-12 tmp]$ ./StackO.sh

Hello Stack Overflow

[fifi@ip-172-31-17-12 tmp]$ /tmp/StackO.sh

Hello Stack Overflow

[fifi@ip-172-31-17-12 tmp]$ mkdir tmp2

[fifi@ip-172-31-17-12 tmp]$ cd tmp2/

[fifi@ip-172-31-17-12 tmp2]$ ../StackO.sh

Hello Stack Overflow

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

What are the dark corners of Vim your mom never told you about?

Not an obscure feature, but very useful and time saving.

If you want to save a session of your open buffers, tabs, markers and other settings, you can issue the following:

mksession session.vim

You can open your session using:

vim -S session.vim

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

How to prevent downloading images and video files from my website?

If you want only authorised users to get the content, both the client and the server need to use encryption.

For video and audio, a good solution is Azure Media Services, which has content protection and encryption. You embed the Azure media player in your browser and it streams the video from Azure.

For documents and email, you can look at Azure Rights Management, which uses a special client. It doesn't currently work in ordinary web browsers, unfortunately, except for one-off, single-use codes.

I'm not sure exactly how secure all this is, however. As others have pointed out, from a security point of view, once those downloaded bytes are in the "attacker's" RAM, they're as good as gone. No solution is 100% secure in this case (please correct me if I'm wrong). As with most security, the goal is to make it harder, so the 99% don't bother.

how to use Spring Boot profiles

Use "-Dspring-boot.run.profiles=foo,local" in Intellij IDEA. It's working. Its sets 2 profiles "foo and local".

Verified with boot version "2.3.2.RELEASE" & Intellij IDEA CE 2019.3.

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Setting profile with "mvn spring-boot:run" enter image description here

Setting environment variable enter image description here

compareTo with primitives -> Integer / int

May I propose a third

((Integer) a).compareTo(b)  

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

There are more aspects to this.

You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.

To have a green bar for a self-signed certificate, you also need to become the Certificate Authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.

This resource covers the creation of both the CA certificate and a Server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge: https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58

Please note: in Chrome you need to add the CA Certificate to your trusted authorities.

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

Date ticks and rotation in matplotlib

An easy solution which avoids looping over the ticklabes is to just use

fig.autofmt_xdate()

This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call

fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')

The additional bottom argument is equivalent to setting plt.subplots_adjust(bottom=bottom), which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.

So basically here you have all the settings you need to have a nice date axis in a single command.

A good example can be found on the matplotlib page.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Another cause is if the user's default database is unavailable.

I had an account that was used for backing up two databases. When the backup user's default database was taken off-line, the "no process on the other end of the pipe" error started.

Tools to search for strings inside files without indexing

Original Answer

Windows Grep does this really well.

Edit: Windows Grep is no longer being maintained or made available by the developer. An alternate download link is here: Windows Grep - alternate

Current Answer

Visual Studio Code has excellent search and replace capabilities across files. It is extremely fast, supports regex and live preview before replacement.

enter image description here

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

Constantly print Subprocess output while process is running

Ok i managed to solve it without threads (any suggestions why using threads would be better are appreciated) by using a snippet from this question Intercepting stdout of a subprocess while it is running

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise ProcessException(command, exitCode, output)

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

How to sort List of objects by some property

You can call Collections.sort() and pass in a Comparator which you need to write to compare different properties of the object.

How to check if a socket is connected/disconnected in C#?

public static class SocketExtensions
{
    private const int BytesPerLong = 4; // 32 / 8
    private const int BitsPerByte = 8;

    public static bool IsConnected(this Socket socket)
    {
        try
        {
            return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
        }
        catch (SocketException)
        {
            return false;
        }
    }


    /// <summary>
    /// Sets the keep-alive interval for the socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="time">Time between two keep alive "pings".</param>
    /// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
    /// <returns>If the keep alive infos were succefully modified.</returns>
    public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
    {
        try
        {
            // Array to hold input values.
            var input = new[]
            {
                (time == 0 || interval == 0) ? 0UL : 1UL, // on or off
                time,
                interval
            };

            // Pack input into byte struct.
            byte[] inValue = new byte[3 * BytesPerLong];
            for (int i = 0; i < input.Length; i++)
            {
                inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
            }

            // Create bytestruct for result (bytes pending on server socket).
            byte[] outValue = BitConverter.GetBytes(0);

            // Write SIO_VALS to Socket IOControl.
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
        }
        catch (SocketException)
        {
            return false;
        }

        return true;
    }
}
  1. Copy the SocketExtensions class to your project
  2. Call the SetKeepAlive on your socket - socket.SetKeepAlive(1000, 2);
  3. Add a timer to check the IsConnected function

Pyinstaller setting icons don't change

I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile:

pyinstaller.exe --onefile --windowed --icon=app.ico app.py

Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.

The information here was found at this site: https://mborgerson.com/creating-an-executable-from-a-python-script

Cannot open output file, permission denied

Hello I realize this post is old, but here is my opinion anyway. This error arises when you close the console output window using the close icon instead of pressing "any key to continue"

TypeError: $ is not a function when calling jQuery function

(function( $ ) {
  "use strict";

  $(function() {

    //Your code here

  });

}(jQuery));

Bootstrap 3 grid with no gap

Simple you can use bellow class.

_x000D_
_x000D_
.nopadmar {_x000D_
   padding: 0 !important;_x000D_
   margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6 nopadmar">Your Content<div>_x000D_
       <div class="col-md-6 nopadmar">Your Content<div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

How to print exact sql query in zend framework ?

even shorter:

echo $select->__toString()."\n";

and more shorter:

echo  $select .""; die;

Google Maps Api v3 - find nearest markers

The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:

function find_closest_marker( lat1, lon1 ) {    
    var pi = Math.PI;
    var R = 6371; //equatorial radius
    var distances = [];
    var closest = -1;

    for( i=0;i<markers.length; i++ ) {  
        var lat2 = markers[i].position.lat();
        var lon2 = markers[i].position.lng();

        var chLat = lat2-lat1;
        var chLon = lon2-lon1;

        var dLat = chLat*(pi/180);
        var dLon = chLon*(pi/180);

        var rLat1 = lat1*(pi/180);
        var rLat2 = lat2*(pi/180);

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
                    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2); 
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        var d = R * c;

        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    // (debug) The closest marker is:
    console.log(markers[closest]);
}

SQL Server procedure declare a list

You can convert the list of passed values into a table valued parameter and then select against this list

DECLARE @list NVARCHAR(MAX)
SET @list = '1,2,5,7,10';

DECLARE @pos INT
DECLARE @nextpos INT
DECLARE @valuelen INT
DECLARE @tbl TABLE (number int NOT NULL)

SELECT @pos = 0, @nextpos = 1;

WHILE @nextpos > 0
BEGIN
    SELECT @nextpos = charindex(',', @list, @pos + 1)
    SELECT @valuelen = CASE WHEN @nextpos > 0
                            THEN @nextpos
                            ELSE len(@list) + 1
                        END - @pos - 1
    INSERT @tbl (number)
        VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
    SELECT @pos = @nextpos;
END

SELECT * FROM DBTable WHERE id IN (SELECT number FROM @tbl);

In this example the string passed in '1,2,5,7,10' is split by the commas and each value is added as a new row within the @tbl table variable. This can then be selected against using standard SQL.

If you intend to reuse this functionality you could go further and convert this into a function.

Filter Pyspark dataframe column with None value

if column = None

COLUMN_OLD_VALUE
----------------
None
1
None
100
20
------------------

Use create a temptable on data frame:

sqlContext.sql("select * from tempTable where column_old_value='None' ").show()

So use : column_old_value='None'

jQuery validation plugin: accept only alphabetical characters?

Be careful,

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please"); 

[a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.

For spaces + text, just do this:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Letters and spaces only please");

[a-z ] this allows spaces aswell as text only.

............................................................................

also the message "Letters and spaces only please" is not required, if you already have a message in messages:

messages:{
        firstname:{
        required: "Enter your first name",
        minlength: jQuery.format("Enter at least (2) characters"),
        maxlength:jQuery.format("First name too long more than (80) characters"),
        lettersonly:jQuery.format("letters only mate")
        },

Adam

Change UITextField and UITextView Cursor / Caret Color

I think If you want some custom colors you can go to Assets.xcassets folder, right click and select New Color Set, once you created you color you set, give it a name to reuse it.

And you can use it just like this :

import UIKit 

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        UITextField.appearance().tintColor = UIColor(named: "YOUR-COLOR-NAME")  #here
    }
}

Tested on macOS 10.15 / iOS 13 / Swift 5

How can I run multiple npm scripts in parallel?

You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you'll need to manually stop it after all tests are finished.

This is an example for protractor testing through npm:

scripts: {
  "webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
  "protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
  "http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
  "test": "npm-run-all -p -r webdriver-start http-server protractor"
}

-p = Run commands in parallel.

-r = Kill all commands when one of them finishes with an exit code of zero.

Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.

How can I use jQuery in Greasemonkey?

There's absolutely nothing wrong with including the entirety of jQuery within your Greasemonkey script. Just take the source, and place it at the top of your user script. No need to make a script tag, since you're already executing JavaScript!

The user only downloads the script once anyways, so size of script is not a big concern. In addition, if you ever want your Greasemonkey script to work in non-GM environments (such as Opera's GM-esque user scripts, or Greasekit on Safari), it'll help not to use GM-unique constructs such as @require.

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

How to load a model from an HDF5 file in Keras?

I done in this way

from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Bootstrap4 with jQuery, simplified solution

<div class="device-sm d-sm-none"></div>
<div class="device-md d-md-none"></div>
<div class="device-lg d-lg-none"></div>
<div class="device-xl d-xl-none"></div>
<script>
var size = $('.device-xl').is(':hidden') ? 'xl' : ($('.device-lg').is(':hidden') ? 'lg'
    : ($('.device-md').is(':hidden') ? 'md': ($('.device-sm').is(':hidden') ? 'sm' : 'xs')));
alert(size);
</script>

Sorting JSON by values

Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

$scope.sortMyData = function (a, b)
{
  var retVal = 0, key;
  for (var i = 0; i < $scope.sortKeys.length; i++)
  {
    if (retVal !== 0)
    {
      break;
    }
    else
    {
      key = $scope.sortKeys[i];
      if ('asc' === key.direction)
      {
        retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
      }
      else
      {
        retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
      }
    }
  }
  return retVal;
};

How can I check whether a option already exist in select by JQuery

Although most of other answers worked for me I used .find():

if ($("#yourSelect").find('option[value="value"]').length === 0){
    ...
}

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Recently released JDK 1.8.0_40 added support for JavaFX dialogs, alerts, etc. For example, to show a confirmation dialog, one would use the Alert class:

Alert alert = new Alert(AlertType.CONFIRMATION, "Delete " + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}

Here's a list of added classes in this release:

Split string into individual words Java

Yet another method, using StringTokenizer :

String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);

while(tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

unique() for more than one variable

This is an addition to Josh's answer.

You can also keep the values of other variables while filtering out duplicated rows in data.table

Example:

library(data.table)

#create data table
dt <- data.table(
  V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
  V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
  V3=c(1),
  V4=c(2) )

> dt
# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# A  B  1  2
# B  A  1  2
# C  D  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2
# A  B  1  2

# set the key to all columns
setkey(dt)

# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] ) 

# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# B  A  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2

Alert: If there are different combinations of values in the other variables, then your result will be

unique combination of V1 and V2

Make Font Awesome icons in a circle?

I like Dave Everitt's answer with the « line-height » but it only works by specifying the « height » and then we have to add « !important » to line-height ...

.cercle {
    font-size: 2em;
    width: 2em;
    height: 2em;
    text-align: center;
    line-height: 2em!important;
    background: #666;
    color: #fff;
    border-radius: 2em;
}

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Switch tabs using Selenium WebDriver with Java

Work around

Assumption : By Clicking something on your web page leads to open a new tab.

Use below logic to switch to second tab.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();

In the same manner you can switch back to first tab again.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Finding last occurrence of substring in string, replacing that

To replace from the right:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

In use:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Go to Start and search for cmd. Right click on it, properties then set the Target path in quotes. This worked fine for me.

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

How do I vertically align text in a paragraph?

In my case margin auto works fine.

p {
    font: 22px/24px Ubuntu;
    margin:auto 0px;
}

What is the syntax for Typescript arrow functions with generics?

The language specification says on p.64f

A construct of the form < T > ( ... ) => { ... } could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former[..]

example:

// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
           R extends Backbone.Collection<any> >(c:R) => {
               return new Promise(function (fulfill, reject) {
                   c.fetch({reset: true, success: fulfill, error: reject})
               });
           };

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

Calling a Variable from another Class

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Got it to work by transitioning the padding as well as the width.

JSFiddle: http://jsfiddle.net/tuybk748/1/

<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
    <div class="gray contents">These are the contents of this div</div>
</div>
.gray {
    background: #ddd;
}
.contents-wrapper, .label, .contents {
    display: inline-block;
}
.label, .contents {
    overflow: hidden; /* must be on both divs to prevent dropdown behavior */
    height: 20px;
}
.label {
    padding: 10px 10px 15px;
}
.contents {
    padding: 10px 0px 15px; /* no left-right padding at beginning */
    white-space: nowrap; /* keeps text all on same line */
    width: 0%;
    -webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -o-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

Align two divs horizontally side by side center to the page using bootstrap css

I recommend css grid over bootstrap if what you really want, is to have more structured data, e.g. a side by side table with multiple rows, because you don't have to add class name for every child:

// css-grid: https://www.w3schools.com/css/tryit.asp?filename=trycss_grid
// https://css-tricks.com/snippets/css/complete-guide-grid/
.grid-container {
  display: grid;
  grid-template-columns: auto auto; // 20vw 40vw for me because I have dt and dd
  padding: 10px;
  text-align: left;
  justify-content: center;
  align-items: center;
}

.grid-container > div {
  padding: 20px;
}


<div class="grid-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>

css-grid

How to delete row based on cell value

You can loop through each the cells in your range and use the InStr function to check if a cell contains a string, in your case; a hyphen.

Sub DeleteRowsWithHyphen()

    Dim rng As Range

    For Each rng In Range("A2:A10") 'Range of values to loop through

        If InStr(1, rng.Value, "-") > 0 Then 'InStr returns an integer of the position, if above 0 - It contains the string
            rng.Delete
        End If

    Next rng

End Sub

How to detect the character encoding of a text file?

If your file starts with the bytes 60, 118, 56, 46 and 49, then you have an ambiguous case. It could be UTF-8 (without BOM) or any of the single byte encodings like ASCII, ANSI, ISO-8859-1 etc.

How to check status of PostgreSQL server Mac OS X

The pg_ctl status command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.

It is better to use another method like using psql to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1', or use pg_isready to check the connection status.

Storing Data in MySQL as JSON

To illustrate how difficult it is to get JSON data using a query, I will share the query I made to handle this.

It doesn't take into account arrays or other objects, just basic datatypes. You should change the 4 instances of column to the column name storing the JSON, and change the 4 instances of myfield to the JSON field you want to access.

SELECT
    SUBSTRING(
        REPLACE(REPLACE(REPLACE(column, '{', ''), '}', ','), '"', ''),
        LOCATE(
            CONCAT('myfield', ':'),
            REPLACE(REPLACE(REPLACE(column, '{', ''), '}', ','), '"', '')
        ) + CHAR_LENGTH(CONCAT('myfield', ':')),
        LOCATE(
            ',',
            SUBSTRING(
                REPLACE(REPLACE(REPLACE(column, '{', ''), '}', ','), '"', ''),
                LOCATE(
                    CONCAT('myfield', ':'),
                    REPLACE(REPLACE(REPLACE(column, '{', ''), '}', ','), '"', '')
                ) + CHAR_LENGTH(CONCAT('myfield', ':'))
            )
        ) - 1
    )
    AS myfield
FROM mytable WHERE id = '3435'

CSS media query to target iPad and iPad only?

Well quite same question and there is also an answer =)

http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1

@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...

I can not test it currently so please test it =)

Also found some more:

http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/

Or you check the navigator with some javascript and generate / add a css file with javascript

Java collections maintaining insertion order

Theres's a section in the O'Reilly Java Cookbook called "Avoiding the urge to sort" The question you should be asking is actually the opposite of your original question ... "Do we gain something by sorting?" It take a lot of effort to sort and maintain that order. Sure sorting is easy but it usually doesn't scale in most programs. If you're going to be handling thousands or tens of thousands of requests (insrt,del,get,etc) per second whether not you're using a sorted or non sorted data structure is seriously going to matter.

Namespace not recognized (even though it is there)

This happened to me in Visual Studio 2019. For me, I was trying to reference another project in my solution. Here are the steps I took in case it helps anyone else:

  1. Ensured the project I wanted to reference was listed under References
  2. Ensured both projects were using the correct version of .NET Framework
  3. Built the project (clicked green "Start" arrow)

I was confused because I was still getting the error after steps 1 and 2, but building the project seemed to resolve it.

Simple export and import of a SQLite database on Android

This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a

    public class ExportImportDB extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
            File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");

               if(!direct.exists())
                {
                    if(direct.mkdir()) 
                      {
                       //directory is created;
                      }

                }
            exportDB();
            importDB();

        }
    //importing database
        private void importDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data  = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File  backupDB= new File(data, currentDBPath);
                    File currentDB  = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }
    //exporting database 
        private void exportDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

Dont forget to add this permission to proceed it

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

Enjoy

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

EventListener Enter Key

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

Best practice to look up Java Enum

Looks like you have a bad practice here but not where you think.

Catching an IllegalArgumentException to rethrow another RuntimeException with a clearer message might look like a good idea but it is not. Because it means you care about messages in your exceptions.

If you care about messages in your exceptions, then it means that your user is somehow seeing your exceptions. This is bad.

If you want to provide an explicit error message to your user, you should check the validity of the enum value when parsing user input and send the appropriate error message in the response if user input is incorrect.

Something like:

// This code uses pure fantasy, you are warned!
class MyApi
{
    // Return the 24-hour from a 12-hour and AM/PM

    void getHour24(Request request, Response response)
    {
        // validate user input
        int nTime12 = 1;
        try
        {
            nTime12 = Integer.parseInt(request.getParam("hour12"));
            if( nTime12 <= 0 || nTime12 > 12 )
            {
                throw new NumberFormatException();
            }
        }
        catch( NumberFormatException e )
        {
            response.setCode(400); // Bad request
            response.setContent("time12 must be an integer between 1 and 12");
            return;
        }

        AMPM pm = null;
        try
        {
            pm = AMPM.lookup(request.getParam("pm"));
        }
        catch( IllegalArgumentException e )
        {
            response.setCode(400); // Bad request
            response.setContent("pm must be one of " + AMPM.values());
            return;
        }

        response.setCode(200);
        switch( pm )
        {
            case AM:
                response.setContent(nTime12);
                break;
            case PM:
                response.setContent(nTime12 + 12);
                break;
        }
        return;
    }
}

Android failed to load JS bundle

Here are the simple steps to run your app on android(release):

1. Go to your application root.

2. Run this command.

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

All your files are copied.

3. Create signed APK.

Open android studio.

Build > Generate Signed APK > [Fill required details, keystroke has to be generated before this step]

Your APK should be generated without any errors. Install on your device and this should work without any issues.

You can also connect your device and directly hit Run icon on android studio for testing.


Generating Keystroke:

  1. Goto C:\Program Files\Java\jdkx.x.x_x\bin

  2. Run

keytool -genkey -v -keystore d:\my_private_key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

It will probably ask you to fill in some details. Do it and your have your keystroke file(my_private_key.keystore) which can be used to sign your apk.

Permission denied error on Github Push

Based on the information that the original poster has provided so far, it might be the case that the project owners of EasySoftwareLicensing/software-licensing-php will only accept pull requests from forks, so you may need to fork the main repo and push to your fork, then make pull requests from it to the main repo.

See the following GitHub help articles for instructions:

  1. Fork a Repo.
  2. Collaborating.

How can I handle the warning of file_get_contents() function in PHP?

My favourite way to do this is fairly simple:

if (false !== ($data = file_get_contents("http://www.google.com"))) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

I found this after experimenting with the try/catch from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last to get the text of the last error, and file_get_contents returns false on failure, so a simple "if" can catch that.

How to Calculate Execution Time of a Code Snippet in C++

In some programs I wrote I used RDTS for such purpose. RDTSC is not about time but about number of cycles from processor start. You have to calibrate it on your system to get a result in second, but it's really handy when you want to evaluate performance, it's even better to use number of cycles directly without trying to change them back to seconds.

(link above is to a french wikipedia page, but it has C++ code samples, english version is here)

How to save python screen output to a text file

A quick and dirty hack to do this within the script is to direct the screen output to a file:

import sys 

stdoutOrigin=sys.stdout 
sys.stdout = open("log.txt", "w")

and then reverting back to outputting to screen at the end of your code:

sys.stdout.close()
sys.stdout=stdoutOrigin

This should work for a simple code, but for a complex code there are other more formal ways of doing it such as using Python logging.

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

.jar error - could not find or load main class

I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.

Size-limited queue that holds last N elements in Java

The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).

To my knowledge your trivial implementation is the easiest way to get such an behaviour.

Use '=' or LIKE to compare strings in SQL?

To see the performance difference, try this:

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name

Comparing strings with '=' is much faster.

Regex for empty string or white space

Had similar problem, was looking for white spaces in a string, solution:

  • To search for 1 space:

    var regex = /^.+\s.+$/ ;
    

    example: "user last_name"

  • To search for multiple spaces:

    var regex = /^.+\s.+$/g ;
    

    example: "user last name"

$(form).ajaxSubmit is not a function

Try:

$(document).ready(function() {
    $('#contact-form').validate({submitHandler: function(form) {
         var data = $('#contact-form').serialize();   
         $.post(
              'url_request',
               {data: data},
               function(response){
                  console.log(response);
               }
          );
         }
    });
});

How to run Unix shell script from Java code?

Here is an example how to run an Unix bash or Windows bat/cmd script from Java. Arguments can be passed on the script and output received from the script. The method accepts arbitrary number of arguments.

public static void runScript(String path, String... args) {
    try {
        String[] cmd = new String[args.length + 1];
        cmd[0] = path;
        int count = 0;
        for (String s : args) {
            cmd[++count] = args[count - 1];
        }
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        try {
            process.waitFor();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        while (bufferedReader.ready()) {
            System.out.println("Received from script: " + bufferedReader.readLine());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
}

When running on Unix/Linux, the path must be Unix-like (with '/' as separator), when running on Windows - use '\'. Hier is an example of a bash script (test.sh) that receives arbitrary number of arguments and doubles every argument:

#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
  echo argument $((counter +=1)): $1
  echo doubling argument $((counter)): $(($1+$1))
  shift
done

When calling

runScript("path_to_script/test.sh", "1", "2")

on Unix/Linux, the output is:

Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4

Hier is a simple cmd Windows script test.cmd that counts number of input arguments:

@echo off
set a=0
for %%x in (%*) do Set /A a+=1 
echo %a% arguments received

When calling the script on Windows

  runScript("path_to_script\\test.cmd", "1", "2", "3")

The output is

Received from script: 3 arguments received

Meaning of "n:m" and "1:n" in database design

m:n refers to many to many relationship where as 1:n means one to many relationship forexample employee(id,name,skillset) skillset(id,skillname,qualifications)

in this case the one employee can have many skills and ignoring other cases you can say that its a 1:N relationship

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

Wizard

Have you tried setting the height and width of the extra div, I know that on a project I am working on JS won't put anything in the div unless I have the height and width already set.

I used your code and hard coded the height and width and it shows up for me and without it doesn't show.

<body>
    <div style="height:500px; width:500px;"> <!-- ommiting the height and width will not show the map -->
         <div id="map-canvas"></div>
    </div>
</body> 

I would recommend either hard coding it in or assigning the div an ID and then add it to your CSS file.

Determine when a ViewPager changes pages

Kotlin Users,

viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
            }
        })

Update 2020 for ViewPager2

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageScrollStateChanged(state: Int) {
            println(state)
        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            println(position)
        }


        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            println(position)
        }
    })

Java HashMap: How to get a key and value by index?

I came across the same problem, read a couple of answers from different related questions and came up with my own class.

public class IndexableMap<K, V> extends HashMap<K, V> {

    private LinkedList<K> keyList = new LinkedList<>();

    @Override
    public V put(K key, V value) {
        if (!keyList.contains(key))
            keyList.add(key);
        return super.put(key, value);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public void clear() {
        keyList.clear();
        super.clear();
    }

    public List<K> getKeys() {
        return keyList;
    }

    public int getKeyIndex(K key) {
        return keyList.indexOf(key);
    }

    public K getKeyAt(int index) {
        if (keyList.size() > index)
            return keyList.get(index);
        return null;
    }

    public V getValueAt(int index) {
        K key = getKeyAt(index);
        if (key != null)
            return get(key);
        return null;
    }
}

Example (types are differing from OPs question just for clarity):

Map<String, Double> myMap = new IndexableMap<>();

List<String> keys = myMap.getKeys();
int keyIndex = myMap.getKeyIndex("keyString");
String key = myMap.getKeyAt(2);
Double value myMap.getValueAt(2);

Keep in mind that it does not override any of the complex methods, so you will need to do this on your own if you want to reliably access one of these.

Edit: I made a change to the putAll() method, because the old one had a rare chance to cause HashMap and LinkedList being in different states.

How to ALTER multiple columns at once in SQL Server

This is not possible. You will need to do this one by one. You could:

  1. Create a Temporary Table with your modified columns in
  2. Copy the data across
  3. Drop your original table (Double check before!)
  4. Rename your Temporary Table to your original name

React: trigger onChange if input value is changing by state?

You need to trigger the onChange event manually. On text inputs onChange listens for input events.

So in you handleClick function you need to trigger event like

handleClick () {
    this.setState({value: 'another random text'})
    var event = new Event('input', { bubbles: true });
    this.myinput.dispatchEvent(event);
  }

Complete code

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: 'random text'
    }
  }
  handleChange (e) {
    console.log('handle change called')
  }
  handleClick () {
    this.setState({value: 'another random text'})
    var event = new Event('input', { bubbles: true });
    this.myinput.dispatchEvent(event);
  }
  render () {
    return (
      <div>
        <input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
        <button onClick={this.handleClick.bind(this)}>Change Input</button>
      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

Codepen

Edit: As Suggested by @Samuel in the comments, a simpler way would be to call handleChange from handleClick if you don't need to the event object in handleChange like

handleClick () {
    this.setState({value: 'another random text'})
    this.handleChange();
  }

I hope this is what you need and it helps you.

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

Get variable from PHP to JavaScript

Update: I completely rewrote this answer. The old code is still there, at the bottom, but I don't recommend it.


There are two main ways you can get access GET variables:

  1. Via PHP's $_GET array (associative array).
  2. Via JavaScript's location object.

With PHP, you can just make a "template", which goes something like this:

<script type="text/javascript">
var $_GET = JSON.parse("<?php echo json_encode($_GET); ?>");
</script>

However, I think the mixture of languages here is sloppy, and should be avoided where possible. I can't really think of any good reasons to mix data between PHP and JavaScript anyway.

It really boils down to this:

  • If the data can be obtained via JavaScript, use JavaScript.
  • If the data can't be obtained via JavaScript, use AJAX.
  • If you otherwise need to communicate with the server, use AJAX.

Since we're talking about $_GET here (or at least I assumed we were when I wrote the original answer), you should get it via JavaScript.

In the original answer, I had two methods for getting the query string, but it was too messy and error-prone. Those are now at the bottom of this answer.

Anyways, I designed a nice little "class" for getting the query string (actually an object constructor, see the relevant section from MDN's OOP article):

function QuerystringTable(_url){
    // private
    var url   = _url,
        table = {};

    function buildTable(){
        getQuerystring().split('&').filter(validatePair).map(parsePair);
    }

    function parsePair(pair){
        var splitPair = pair.split('='),
            key       = decodeURIComponent(splitPair[0]),
            value     = decodeURIComponent(splitPair[1]);

        table[key] = value;
    }

    function validatePair(pair){
        var splitPair = pair.split('=');

        return !!splitPair[0] && !!splitPair[1];
    }

    function validateUrl(){
        if(typeof url !== "string"){
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
        }

        if(url == ""){
            throw "QuerystringTable() :: Empty string given for argument <string url>";
        }
    }

    // public
    function getKeys(){
        return Object.keys(table);
    }

    function getQuerystring(){
        var string;

        validateUrl();
        string = url.split('?')[1];

        if(!string){
            string = url;
        }

        return string;
    }

    function getValue(key){
        var match = table[key] || null;

        if(!match){
            return "undefined";
        }

        return match;
    }

    buildTable();
    this.getKeys        = getKeys;
    this.getQuerystring = getQuerystring;
    this.getValue       = getValue;
}

JSFiddle demo

_x000D_
_x000D_
function main(){_x000D_
    var imaginaryUrl = "http://example.com/webapp/?search=how%20to%20use%20Google&the_answer=42",_x000D_
        qs = new QuerystringTable(imaginaryUrl);_x000D_
_x000D_
    urlbox.innerHTML = "url: " + imaginaryUrl;_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getKeys()",_x000D_
        qs.getKeys()_x000D_
        .map(arrowify)_x000D_
        .join("\n")_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("search")',_x000D_
        qs.getValue("search")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("the_answer")',_x000D_
        qs.getValue("the_answer")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getQuerystring()",_x000D_
        qs.getQuerystring()_x000D_
        .arrowify()_x000D_
    );_x000D_
}_x000D_
_x000D_
function arrowify(str){_x000D_
    return "  -> " + str;_x000D_
}_x000D_
_x000D_
String.prototype.arrowify = function(){_x000D_
    return arrowify(this);_x000D_
}_x000D_
_x000D_
function log(msg){_x000D_
    txt.value += msg + '\n';_x000D_
    txt.scrollTop = txt.scrollHeight;_x000D_
}_x000D_
_x000D_
function logButton(name, output){_x000D_
    var el = document.createElement("button");_x000D_
    _x000D_
    el.innerHTML = name;_x000D_
    _x000D_
    el.onclick = function(){_x000D_
        log(name);_x000D_
        log(output);_x000D_
        log("- - - -");_x000D_
    }_x000D_
    _x000D_
    buttonContainer.appendChild(el);_x000D_
}_x000D_
_x000D_
function QuerystringTable(_url){_x000D_
    // private_x000D_
    var url = _url,_x000D_
        table = {};_x000D_
_x000D_
    function buildTable(){_x000D_
        getQuerystring().split('&').filter(validatePair).map(parsePair);_x000D_
    }_x000D_
_x000D_
    function parsePair(pair){_x000D_
        var splitPair = pair.split('='),_x000D_
            key       = decodeURIComponent(splitPair[0]),_x000D_
            value     = decodeURIComponent(splitPair[1]);_x000D_
_x000D_
        table[key] = value;_x000D_
    }_x000D_
_x000D_
    function validatePair(pair){_x000D_
        var splitPair = pair.split('=');_x000D_
_x000D_
        return !!splitPair[0] && !!splitPair[1];_x000D_
    }_x000D_
_x000D_
    function validateUrl(){_x000D_
        if(typeof url !== "string"){_x000D_
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;_x000D_
        }_x000D_
_x000D_
        if(url == ""){_x000D_
            throw "QuerystringTable() :: Empty string given for argument <string url>";_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // public_x000D_
    function getKeys(){_x000D_
        return Object.keys(table);_x000D_
    }_x000D_
_x000D_
    function getQuerystring(){_x000D_
        var string;_x000D_
_x000D_
        validateUrl();_x000D_
        string = url.split('?')[1];_x000D_
_x000D_
        if(!string){_x000D_
            string = url;_x000D_
        }_x000D_
_x000D_
        return string;_x000D_
    }_x000D_
_x000D_
    function getValue(key){_x000D_
        var match = table[key] || null;_x000D_
_x000D_
        if(!match){_x000D_
            return "undefined";_x000D_
        }_x000D_
_x000D_
        return match;_x000D_
    }_x000D_
_x000D_
    buildTable();_x000D_
    this.getKeys        = getKeys;_x000D_
    this.getQuerystring = getQuerystring;_x000D_
    this.getValue       = getValue;_x000D_
}_x000D_
_x000D_
main();
_x000D_
#urlbox{_x000D_
    width: 100%;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    font: 12px monospace;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
#txt{_x000D_
    width: 100%;_x000D_
    height: 200px;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    resize: none;_x000D_
    border: none;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
    displaY:block;_x000D_
}_x000D_
_x000D_
button{_x000D_
    padding: 5px;_x000D_
    margin: 10px;_x000D_
    width: 200px;_x000D_
    background: #eee;_x000D_
    color: #000;_x000D_
    border:1px solid #ccc;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
button:hover{_x000D_
    background: #fff;_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<p id="urlbox"></p>_x000D_
<textarea id="txt" disabled="true"></textarea>_x000D_
<div id="buttonContainer"></div>
_x000D_
_x000D_
_x000D_

It's much more robust, doesn't rely on regex, combines the best parts of both the previous approaches, and will validate your input. You can give it query strings other than the one from the url, and it will fail loudly if you give bad input. Moreover, like a good object/module, it doesn't know or care about anything outside of the class definition, so it can be used with anything.

The constructor automatically populates its internal table and decodes each string such that ...?foo%3F=bar%20baz&ampersand=this%20thing%3A%20%26, for example, will internally become:

{
    "foo?"      : "bar baz",
    "ampersand" : "this thing: &"
}

All the work is done for you at instantiation.

Here's how to use it:

var qst = new QuerystringTable(location.href);
qst.getKeys()        // returns an array of keys
qst.getValue("foo")  // returns the value of foo, or "undefined" if none.
qst.getQuerystring() // returns the querystring

That's much better. And leaving the url part up to the programmer both allows this to be used in non-browser environments (tested in both node.js and a browser), and allows for a scenario where you might want to compare two different query strings.

var qs1 = new QuerystringTable(/* url #1 */),
    qs2 = new QuerystringTable(/* url #2 */);

if (qs1.getValue("vid") !== qs2.getValue("vid")){
    // Do something
}

As I said above, there were two messy methods that are referenced by this answer. I'm keeping them here so readers don't have to hunt through revision history to find them. Here they are:

1) Direct parse by function. This just grabs the url and parses it directly with RegEx

$_GET=function(key,def){
    try{
        return RegExp('[?&;]'+key+'=([^?&#;]*)').exec(location.href)[1]
    }catch(e){
        return def||''
    }
}

Easy peasy, if the query string is ?ducksays=quack&bearsays=growl, then $_GET('ducksays') should return quack and $_GET('bearsays') should return growl

Now you probably instantly notice that the syntax is different as a result of being a function. Instead of $_GET[key], it is $_GET(key). Well, I thought of that :)

Here comes the second method:


2) Object Build by Loop

onload=function(){
    $_GET={}//the lack of 'var' makes this global
    str=location.search.split('&')//not '?', this will be dealt with later
    for(i in str){
        REG=RegExp('([^?&#;]*)=([^?&#;]*)').exec(str[i])
        $_GET[REG[1]]=REG[2]
    }
}

Behold! $_GET is now an object containing an index of every object in the url, so now this is possible:

$_GET['ducksays']//returns 'quack'

AND this is possible

for(i in $_GET){
    document.write(i+': '+$_GET[i]+'<hr>')
}

This is definitely not possible with the function.


Again, I don't recommend this old code. It's badly written.

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

What does "hashable" mean in Python?

In python it means that the object can be members of sets in order to return a index. That is, they have unique identity/ id.

for example, in python 3.3:

the data structure Lists are not hashable but the data structure Tuples are hashable.

pthread function from a class

My guess would be this is b/c its getting mangled up a bit by C++ b/c your sending it a C++ pointer, not a C function pointer. There is a difference apparently. Try doing a

(void)(*p)(void) = ((void) *(void)) &c[0].print; //(check my syntax on that cast)

and then sending p.

I've done what your doing with a member function also, but i did it in the class that was using it, and with a static function - which i think made the difference.

using javascript to detect whether the url exists before display in iframe

I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file

// if-url-exist.js v1
function ifUrlExist(url, callback) {
    let request = new XMLHttpRequest;
    request.open('GET', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.setRequestHeader('Accept', '*/*');
    request.onprogress = function(event) {
        let status = event.target.status;
        let statusFirstNumber = (status).toString()[0];
        switch (statusFirstNumber) {
            case '2':
                request.abort();
                return callback(true);
            default:
                request.abort();
                return callback(false);
        };
    };
    request.send('');
};

Example of use:

ifUrlExist(url, function(exists) {
    console.log(exists);
});

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

show all tags in git log

git log --no-walk --tags --pretty="%h %d %s" --decorate=full

This version will print the commit message as well:

 $ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f  (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762  (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998  (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484  (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7  (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b  (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe  (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1  (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.

In C#, why is String a reference type that behaves like a value type?

Not only strings are immutable reference types. Multi-cast delegates too. That is why it is safe to write

protected void OnMyEventHandler()
{
     delegate handler = this.MyEventHandler;
     if (null != handler)
     {
        handler(this, new EventArgs());
     }
}

I suppose that strings are immutable because this is the most safe method to work with them and allocate memory. Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define

string s1 = "my string";
//some code here
string s2 = "my string";

Chances are that both instances of "my string" constant will be allocated in your assembly only once.

If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.

If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.

How to find index of an object by key and value in an javascript array

Do this way:-

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

$.each(peoples, function(i, val) {
    $.each(val, function(key, name) {
        if (name === "john")
            alert(key + " : " + name);
    });
});

OUTPUT:

name : john

Refer LIVE DEMO

?

Easiest way to open a download window without navigating away from the page

Using HTML5 Blob Object-URL File API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file_x000D_
 * @param fileName String_x000D_
 * @param fileContents String JSON String_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
var saveBlobAsFile = function(fileName, fileContents) {_x000D_
  if (typeof(Blob) != 'undefined') { // using Blob_x000D_
    var textFileAsBlob = new Blob([fileContents], {_x000D_
      type: 'text/plain'_x000D_
    });_x000D_
    var downloadLink = document.createElement("a");_x000D_
    downloadLink.download = fileName;_x000D_
    if (window.webkitURL != null) {_x000D_
      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
    } else {_x000D_
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
      downloadLink.onclick = document.body.removeChild(event.target);_x000D_
      downloadLink.style.display = "none";_x000D_
      document.body.appendChild(downloadLink);_x000D_
    }_x000D_
    downloadLink.click();_x000D_
  } else {_x000D_
    var pp = document.createElement('a');_x000D_
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
    pp.setAttribute('download', fileName);_x000D_
    pp.onclick = document.body.removeChild(event.target);_x000D_
    pp.click();_x000D_
  }_x000D_
} //saveBlobAsFile_x000D_
_x000D_
var jsonObject = {_x000D_
  "name": "John",_x000D_
  "age": 31,_x000D_
  "city": "New York"_x000D_
};_x000D_
var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
var fileName = "data.json";_x000D_
_x000D_
saveBlobAsFile(fileName, fileContents)
_x000D_
_x000D_
_x000D_

Space between two rows in a table?

Works for most latest browsers in 2015. Simple solution. It doesn't work for transparent, but unlike Thoronwen's answer, I can't get transparent to render with any size.

    tr {
      border-bottom:5em solid white;
    }

More than one file was found with OS independent path 'META-INF/LICENSE'

app build.gradle

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/INDEX.LIST'
    }
}

How do you comment an MS-access Query?

I know this question is very old, but I would like to add a few points, strangely omitted:

  1. you can right-click the query in the container, and click properties, and fill that with your description. The text you input that way is also accessible in design view, in the Descrption property
  2. Each field can be documented as well. Just make sure the properties window is open, then click the query field you want to document, and fill the Description (just above the too little known Format property)

It's a bit sad that no product (I know of) documents these query fields descriptions and expressions.

How to find the kafka version in linux

If you want to check the version of a specific Kafka broker, run this CLI on the broker*

kafka-broker-api-versions.sh --bootstrap-server localhost:9092 --version

where localhost:9092 is the accessible <hostname|IP Address>:<port> this API will check (localhost can be used if it's the same host you're running this command on). Example of output:

2.4.0 (Commit:77a89fcf8d7fa018)

* Apache Kafka comes with a variety of console tools in the ./bin sub-directory of your Kafka download; e.g. ~/kafka/bin/

How to get child process from parent process

ps -axf | grep parent_pid 

Above command prints respective processes generated from parent_pid, hope it helps. +++++++++++++++++++++++++++++++++++++++++++

root@root:~/chk_prgrm/lp#

 parent...18685

 child... 18686


root@root:~/chk_prgrm/lp# ps axf | grep frk

 18685 pts/45   R      0:11  |       \_ ./frk

 18686 pts/45   R      0:11  |       |   \_ ./frk

 18688 pts/45   S+     0:00  |       \_ grep frk

Why can't I shrink a transaction log file, even after backup?

I've had the same issue in the past. Normally a shrink and a trn backup need to occur multiple times. In extreme cases I set the DB to "Simple" recovery and then run a shrink operation on the log file. That always works for me. However recently I had a situation where that would not work. The issue was caused by a long running query that did not complete, so any attempts to shrink were useless until I could kill that process then run my shrink operations. We are talking a log file that grew to 60 GB and is now shrunk to 500 MB.

Remember, as soon as you change from FULL to Simple recovery mode and do the shrink, dont forget to set it back to FULL. Then immediately afterward you must do a FULL DB backup.

java.io.IOException: Broken pipe

You may have not set the output file.

How to reference a local XML Schema file correctly?

Add one more slash after file:// in the value of xsi:schemaLocation. (You have two; you need three. Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.

xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"

Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:

file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd

If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.

If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.

Re-sign IPA (iPhone)

Checked with Mac OS High Sierra and Xcode 10

You can simply implement the same using the application iResign.

Give path of 1).ipa

2) New provision profile

3) Entitlement file (Optional, add only if you have entitlement)

4) Bundle id

5) Distribution Certificate

You can see output .ipa file saved after re-sign

Simple and powerful tool

How to write a caption under an image?

<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>

Style as desired.

How do I get the old value of a changed cell in Excel VBA?

try this

declare a variable say

Dim oval

and in the SelectionChange Event

Public Sub Worksheet_SelectionChange(ByVal Target As Range)
oval = Target.Value
End Sub

and in your Worksheet_Change event set

old_value = oval

Accessing Google Spreadsheets with C# using Google Data API

http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!

DIV table colspan: how?

you can simply use two table divs, for instance:

_x000D_
_x000D_
<div style="display:table; width:450px; margin:0 auto; margin-top:30px; ">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:50%">element1</div>_x000D_
    <div style="width:50%">element2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div style="display:table; width:450px; margin:0 auto;">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:100%">element1</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

works great!

Java : Sort integer array without using Arrays.sort()

int x[] = { 10, 30, 15, 69, 52, 89, 5 };
    int max, temp = 0, index = 0;
    for (int i = 0; i < x.length; i++) {
        int counter = 0;
        max = x[i];
        for (int j = i + 1; j < x.length; j++) {

            if (x[j] > max) {
                max = x[j];
                index = j;
                counter++;
            }

        }
        if (counter > 0) {
            temp = x[index];
            x[index] = x[i];
            x[i] = temp;
        }
    }
    for (int i = 0; i < x.length; i++) {
        System.out.println(x[i]);
    }

How do I make an attributed string using Swift?

 let attrString = NSAttributedString (
            string: "title-title-title",
            attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])

Arduino Tools > Serial Port greyed out

open $arduinoHome/arduino in text editor and modify last string:

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base "$@"

to

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel -Dgnu.io.rxtx.SerialPorts="/dev/ttyACMN" processing.app.Base "$@"

(set property gnu.io.rxtx.SerialPorts to /dev/ttyACMN,where ttyACMN is name of serial port which you use)

it may temporary fix bug in rxtx library. helped me to upload sketch with arduino1.0.5 IDE.

Maybe would helpful for someone.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

How to remove title bar from the android activity?

Try this:

this.getSupportActionBar().hide();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try
    {
        this.getSupportActionBar().hide();
    }
    catch (NullPointerException e){}

    setContentView(R.layout.activity_main);
}

wp_nav_menu change sub-menu class name?

Like it always is, after having looked for a long time before writing something to the site, just a minute after I posted here I found my solution.

It thought I'd share it here so someone else can find it.

//Add "parent" class to pages with subpages, change submenu class name, add depth class

    class Prio_Walker extends Walker_Nav_Menu {
    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
        $GLOBALS['dd_children'] = ( isset($children_elements[$element->ID]) )? 1:0;
        $GLOBALS['dd_depth'] = (int) $depth;
        parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }

     function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"children level-".$depth."\">\n";
  }
}

add_filter('nav_menu_css_class','add_parent_css',10,2);
function  add_parent_css($classes, $item){
     global  $dd_depth, $dd_children;
     $classes[] = 'depth'.$dd_depth;
     if($dd_children)
         $classes[] = 'parent';
    return $classes;
}

//Add class to parent pages to show they have subpages (only for automatic wp_nav_menu)

function add_parent_class( $css_class, $page, $depth, $args )
{
   if ( ! empty( $args['has_children'] ) )
       $css_class[] = 'parent';
   return $css_class;
}
add_filter( 'page_css_class', 'add_parent_class', 10, 4 );

This is where I found the solution: Solution in WordPress support forum

How to set proper codeigniter base url?

Base URL should be absolute, including the protocol:

$config['base_url'] = "http://somesite.com/somedir/";

If using the URL helper, then base_url() will output the above string.

Passing arguments to base_url() or site_url() will result in the following (assuming $config['index_page'] = "index.php";:

echo base_url('assets/stylesheet.css'); // http://somesite.com/somedir/assets/stylesheet.css
echo site_url('mycontroller/mymethod'); // http://somesite.com/somedir/index.php/mycontroller/mymethod

Full path from file input using jQuery

Well, getting full path is not possible but we can have a temporary path.

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
    <br>
<img src="" width="200" style="display:none;" />
        <br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

SQLite Reset Primary Key Field

As an alternate option, if you have the Sqlite Database Browser and are more inclined to a GUI solution, you can edit the sqlite_sequence table where field name is the name of your table. Double click the cell for the field seq and change the value to 0 in the dialogue box that pops up.

How to add a class with React.js?

It is simple. take a look at this

https://codepen.io/anon/pen/mepogj?editors=001

basically you want to deal with states of your component so you check the currently active one. you will need to include

getInitialState: function(){}
//and 
isActive: function(){}

check out the code on the link

Python convert decimal to hex

It is good to write your own functions for conversions between numeral systems to learn something. For "real" code I would recommend to use build in conversion function from Python like bin(x), hex(x), int(x). Some examples can be found here.

How do I migrate an SVN repository with history to a new Git repository?

There are different methods to achieve this goal. I've tried some of them and found really working one with just git and svn installed on Windows OS.

Prerequisites:

  1. git on windows (I've used this one) https://git-scm.com/
  2. svn with console tools installed (I've used tortoise svn)
  3. Dump file of your SVN repository. svnadmin dump /path/to/repository > repo_name.svn_dump

Steps to achieve final goal (move all repository with history to a git, firstly local git, then remote)

  1. Create empty repository (using console tools or tortoiseSVN) in directory REPO_NAME_FOLDER cd REPO_NAME_PARENT_FOLDER, put dumpfile.dump into REPO_NAME_PARENT_FOLDER

  2. svnadmin load REPO_NAME_FOLDER < dumpfile.dump Wait for this operation, it may be long

  3. This command is silent, so open second cmd window : svnserve -d -R --root REPO_NAME_FOLDER Why not just use file:///...... ? Cause next command will fail with Unable to open ... to URL:, thanks to the answer https://stackoverflow.com/a/6300968/4953065

  4. Create new folder SOURCE_GIT_FOLDER

  5. cd SOURCE_GIT_FOLDER
  6. git svn clone svn://localhost/ Wait for this operation.

Finally, what do we got?

Lets check our Local repository :

git log

See your previous commits? If yes - okay

So now you have fully functional local git repository with your sources and old svn history. Now, if you want to move it to some server, use the following commands :

git remote add origin https://fullurlpathtoyourrepo/reponame.git
git push -u origin --all # pushes up the repo and its refs for the first time
git push -u origin --tags # pushes up any tags

In my case, I've dont need tags command cause my repo dont have tags.

Good luck!

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, use the commercial but inexpensive SSMS Tools Pack addin which has a nifty "Generate Insert statements from resultsets, tables or database" feature

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

Pandas join issue: columns overlap but no suffix specified

Mainly join is used exclusively to join based on the index,not on the attribute names,so change the attributes names in two different dataframes,then try to join,they will be joined,else this error is raised

PHP PDO returning single row

You could try this for a database SELECT query based on user input using PDO:

$param = $_GET['username'];

$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();

$result = $query -> fetch();

print_r($result);

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

How to show soft-keyboard when edittext is focused

I had the same problem. Immediately after editText VISIBILITY change from GONE to VISIBLE, I had to set the focus and display the soft keyboard. I achieved this using the following code:

new Handler().postDelayed(new Runnable() {

    public void run() {
//        ((EditText) findViewById(R.id.et_find)).requestFocus();
//              
        EditText yourEditText= (EditText) findViewById(R.id.et_find);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));                           
    }
}, 200);

It works for me with 100ms delay, but failed without any delay or with only a delay of 1ms.

Commented part of code shows another approach, which works only on some devices. I tested on OS versions 2.2 (emulator), 2.2.1 (real device) and 1.6 (emulator).

This approach saved me a lot of pain.

CSS3 Transparency + Gradient

Here is my code:

background: #e8e3e3; /* Old browsers */
  background: -moz-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */

Multiline string literal in C#

You can use the @ symbol in front of a string to form a verbatim string literal:

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

You also do not have to escape special characters when you use this method, except for double quotes as shown in Jon Skeet's answer.

get and set in TypeScript

It is very similar to creating common methods, simply put the keyword reserved get or set at the beginning.

class Name{
    private _name: string;

    getMethod(): string{
        return this._name;
    }

    setMethod(value: string){
        this._name = value
    }

    get getMethod1(): string{
        return this._name;
    }

    set setMethod1(value: string){
        this._name = value
    }
}

class HelloWorld {

    public static main(){

        let test = new Name();

        test.setMethod('test.getMethod() --- need ()');
            console.log(test.getMethod());

        test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
            console.log(test.getMethod1);
    }
}
HelloWorld.main();

In this case you can skip return type in get getMethod1() {

    get getMethod1() {
        return this._name;
    }

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Add & delete view from Layout

For changing visibility:

predictbtn.setVisibility(View.INVISIBLE);

For removing:

predictbtn.setVisibility(View.GONE);

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

some tests we did in our team show that A.class.isAssignableFrom(B.getClass()) works faster than B instanceof A. this can be very useful if you need to check this on large number of elements.

What does ^M character mean in Vim?

I got a text file originally generated on a Windows Machine by way of a Mac user and needed to import it into a Linux MySQL DB using the load data command.

Although VIM displayed the '^M' character, none of the above worked for my particular problem, the data would import but was always corrupted in some way. The solution was pretty easy in the end (after much frustration).

Solution: Executing dos2unix TWICE on the same file did the trick! Using the file command shows what is happening along the way.

$ file 'file.txt'
file.txt: ASCII text, with CRLF, CR line terminators

$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text, with CRLF line terminators

$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text

And the final version of the file imported perfectly into the database.

How to embed a YouTube channel into a webpage

I quickly did this for anyone else coming onto this page:

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"
  type="application/x-shockwave-flash"
  allowfullscreen="true"
  allowscriptaccess="always"
  width="425" height="344">
</embed>
</object>

See the jsFiddle.

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

Of course, if you create a queue don't forget to dispatch_release if you're targeting an iOS version before 6.0.

Add unique constraint to combination of two columns

This can also be done in the GUI:

  1. Under the table "Person", right click Indexes
  2. Click/hover New Index
  3. Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it.
  2. Check Unique checkbox
  3. Click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

  1. Click OK in each window.

Converting array to list in Java

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

The infamous java.sql.SQLException: No suitable driver found

I was having the same issue with mysql datasource using spring data that would work outside but gave me this error when deployed on tomcat.

The error went away when I added the driver jar mysql-connector-java-8.0.16.jar to the jres lib/ext folder

However I did not want to do this in production for fear of interfering with other applications. Explicity defining the driver class solved this issue for me

    spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver

Server Client send/receive simple text

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

//The following code is for the server application:

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

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

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

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

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

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

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

//this is the code for the client

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

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

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

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

How to find length of digits in an integer?

If you have to ask an user to give input and then you have to count how many numbers are there then you can follow this:

count_number = input('Please enter a number\t')

print(len(count_number))

Note: Never take an int as user input.

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

jQuery - how can I find the element with a certain id?

This is one more option to find the element for above question

$("#tbIntervalos").find('td[id="'+horaInicial+'"]')

Simple PHP calculator

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Calculator</title> 
    </head>
<body>

    <form method="GET">
    <h1>Calculator</h1>
    <p>This is a calculator made by Hau Teen Yee Fabrice and is free to use.</p>
        <ul>
     <ol> Multiplication: * </ol>
     <ol> Substraction: - </ol>
     <ol> Division: / </ol>
     <ol> Addition: + </ol>
        </ul>
     <p>Enter first number:</p>
        <input type="text" name="cal1">
        <p>Enter second number:</p>
        <input type="text" name="cal2">
        <p>Enter the calculator symbol</p>
        <input type="text" name="symbol">
        <button>Calculate</button>
    </form>
    <?php
    $cal1= $_GET['cal1'];
    $cal2= $_GET['cal2'];
    $symbol =$_GET['symbol'];

    if($symbol == '+')
    {
        $add = $cal1 + $cal2;
        echo "Addition is:".$add;
    }
    else if($symbol == '-')
    {
        $subs = $cal1 - $cal2;
        echo "Substraction is:".$subs;
    }
     else if($symbol == '*')
    {
        $mul = $cal1 * $cal2;
        echo "Multiply is:".$mul;
    }
    else if($symbol == '/')
    {
        $div = $cal1 / $cal2;
        echo "Division is:".$div;
    }
      else
    { 
        echo "Oops ,something wrong in your code son";
    }
    ?>
    </body> 
</html>

What is referencedColumnName used for in JPA?

"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).

Table Person
name char(64) primary key
age int

Table Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)

When you implement classes you will have something like

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn([column]name="owner_name", referencedColumnName="name")
    private Person owner;
}

EDIT: as @searchengine27 has commented, columnName does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.

ReactJS - Does render get called any time "setState" is called?

Not All Components.

the state in component looks like the source of the waterfall of state of the whole APP.

So the change happens from where the setState called. The tree of renders then get called from there. If you've used pure component, the render will be skipped.

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

From C# 6:

var dateTimeUtcAsString = $"{DateTime.UtcNow:o}";

The result will be: "2019-01-15T11:46:33.2752667Z"

HTTP Request in Kotlin

I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

val url = "https://example.com/endpoint"

val client = OkHttpClient()

val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
        .addHeader("Authorization", "Bearer $token")
        .url(url)
        .post(body)
        .build()

val  response = client . newCall (request).execute()

println(response.request())
println(response.body()!!.string())

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

UPDATE: January 25th, 2021 Everything is okay with the most updated versions.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.12.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

Get Method

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
            .url(url)
            .get()
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}

POST Method

fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val body = jacksonString.toRequestBody(mediaType)

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}

How do I set a program to launch at startup

Add an app to run automatically at startup in Windows 10

Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.

Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.

Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.

Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.

how to convert a string to date in mysql?

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL

SELECT  STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM    table

say for example use the below query to get output

SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table

For String format use the below link

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Create the perfect JPA entity

Entity interface

public interface Entity<I> extends Serializable {

/**
 * @return entity identity
 */
I getId();

/**
 * @return HashCode of entity identity
 */
int identityHashCode();

/**
 * @param other
 *            Other entity
 * @return true if identities of entities are equal
 */
boolean identityEquals(Entity<?> other);
}

Basic implementation for all Entities, simplifies Equals/Hashcode implementations:

public abstract class AbstractEntity<I> implements Entity<I> {

@Override
public final boolean identityEquals(Entity<?> other) {
    if (getId() == null) {
        return false;
    }
    return getId().equals(other.getId());
}

@Override
public final int identityHashCode() {
    return new HashCodeBuilder().append(this.getId()).toHashCode();
}

@Override
public final int hashCode() {
    return identityHashCode();
}

@Override
public final boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
        return false;
    }

    return identityEquals((Entity<?>) o);
}

@Override
public String toString() {
    return getClass().getSimpleName() + ": " + identity();
    // OR 
    // return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

Room Entity impl:

@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;

@Column(name = "number") 
private String number; //immutable

@Column(name = "capacity")
private Integer capacity;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable

Room() {
    // default constructor
}

public Room(Building building, String number) {
    // constructor with required field
    notNull(building, "Method called with null parameter (application)");
    notNull(number, "Method called with null parameter (name)");

    this.building = building;
    this.number = number;
}

public Integer getId(){
    return id;
}

public Building getBuilding() {
    return building;
}

public String getNumber() {
    return number;
}


public void setCapacity(Integer capacity) {
    this.capacity = capacity;
}

//no setters for number, building nor id
}

I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).

List comprehension on a nested list?

Here is how to convert nested for loop to nested list comprehension:

enter image description here

Here is how nested list comprehension works:

            l a b c d e f
            ? ? ? ? ? ? ?
In [1]: l = [ [ [ [ [ [ 1 ] ] ] ] ] ]
In [2]: for a in l:
   ...:     for b in a:
   ...:         for c in b:
   ...:             for d in c:
   ...:                 for e in d:
   ...:                     for f in e:
   ...:                         print(float(f))
   ...:                         
1.0

In [3]: [float(f)
         for a in l
   ...:     for b in a
   ...:         for c in b
   ...:             for d in c
   ...:                 for e in d
   ...:                     for f in e]
Out[3]: [1.0]

For your case, it will be something like this.

In [4]: new_list = [float(y) for x in l for y in x]

How to get the mouse position without events (without moving the mouse)?

You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.

For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...

How do I debug error ECONNRESET in Node.js?

I had the same issue and it appears that the Node.js version was the problem.

I installed the previous version of Node.js (10.14.2) and everything was ok using nvm (allow you to install several version of Node.js and quickly switch from a version to another).

It is not a "clean" solution, but it can serve you temporarly.

How to kill zombie process

Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/

2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes

kill -9 <pid>

will not kill a process. Run

ps -xal

the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!

Example

4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie

18581, 18582, 18583 are zombies -

kill -9 18581 18582 18583

has no effect.

kill -9 31706

removes the zombies.

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

Remove all whitespaces from NSString

That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

Changing the child element's CSS when the parent is hovered

To change it from css you dont even need to set the child class

.parent > div:nth-child(1) { display:none; }
.parent:hover > div:nth-child(1) { display: block; }

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

Do everything in the inline of UL tag

<ul class="dropdown-menu scrollable-menu" role="menu" style="height: auto;max-height: 200px; overflow-x: hidden;">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Action</a></li>
                ..
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
            </ul>

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

SQLite with encryption/password protection

The .net library System.Data.SQLite also provides for encryption.

How to update a plot in matplotlib?

In case anyone comes across this article looking for what I was looking for, I found examples at

How to visualize scalar 2D data with Matplotlib?

and

http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)

then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.


Starting with a 3D array of images of shape (nBins, nBins, nBins), called frames.

def animate_frames(frames):
    nBins   = frames.shape[0]
    frame   = frames[0]
    tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
    for k in range(nBins):
        frame   = frames[k]
        tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
        del tempCS1
        fig.canvas.draw()
        #time.sleep(1e-2) #unnecessary, but useful
        fig.clf()

fig = plt.figure()
ax  = fig.add_subplot(111)

win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate_frames, frames)

I also found a much simpler way to go about this whole process, albeit less robust:

fig = plt.figure()

for k in range(nBins):
    plt.clf()
    plt.imshow(frames[k],cmap=plt.cm.gray)
    fig.canvas.draw()
    time.sleep(1e-6) #unnecessary, but useful

Note that both of these only seem to work with ipython --pylab=tk, a.k.a.backend = TkAgg

Thank you for the help with everything.

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Intellij idea cannot resolve anything in maven

Using default maven (which comes with IntelliJ) also could create this problem. So configure the maven which you have installed.

This can be done from: File -> Settings -> Build, Execution, Deployment -> Maven

Update following settings according to your maven installation:

  1. Maven home directory =
  2. User settings file =
  3. Local repository =

How to sort a Ruby Hash by number value?

Already answered but still. Change your code to:

metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }

Converted to strings along the way or not, this will do the job.

Open the terminal in visual studio?

You can have a integrated terminal inside Visual Studio using one of these extensions:

Whack Whack Terminal

Terminal: cmd or powershell

Shortcut: Ctrl\, Ctrl\

Supports: Visual Studio 2017

https://marketplace.visualstudio.com/items?itemName=DanielGriffen.WhackWhackTerminal

Whack Whack Terminal


BuiltinCmd

Terminal: cmd or powershell

Shortcut: CtrlShiftT

Supports: Visual Studio 2013, 2015, 2017, 2019

https://marketplace.visualstudio.com/items?itemName=lkytal.BuiltinCmd

BuiltinCmd

Android: Reverse geocoding - getFromLocation

Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.

Geocoder call procedure, can be located in a Helper class

public static void getAddressFromLocation(
        final Location location, final Context context, final Handler handler) {
    Thread thread = new Thread() {
        @Override public void run() {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());   
            String result = null;
            try {
                List<Address> list = geocoder.getFromLocation(
                        location.getLatitude(), location.getLongitude(), 1);
                if (list != null && list.size() > 0) {
                    Address address = list.get(0);
                    // sending back first address line and locality
                    result = address.getAddressLine(0) + ", " + address.getLocality();
                }
            } catch (IOException e) {
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            } finally {
                Message msg = Message.obtain();
                msg.setTarget(handler);
                if (result != null) {
                    msg.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("address", result);
                    msg.setData(bundle);
                } else 
                    msg.what = 0;
                msg.sendToTarget();
            }
        }
    };
    thread.start();
}

Here is the call to this Geocoder procedure in your UI Activity:

getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());

And the handler to show the results in your UI:

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String result;
        switch (message.what) {
        case 1:
            Bundle bundle = message.getData();
            result = bundle.getString("address");
            break;
        default:
            result = null;
        }
        // replace by what you need to do
        myLabel.setText(result);
    }   
}

Don't forget to put the following permission in your Manifest.xml

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

Does VBA contain a comment block syntax?

Although there isn't a syntax, you can still get close by using the built-in block comment buttons:

If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:

enter image description here

Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:

enter image description here

Fast and easy!

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

SQL How to replace values of select return?

I saying that the case statement is wrong but this can be a good solution instead. If you choose to use the CASE statement, you have to make sure that at least one of the CASE condition is matched. Otherwise, you need to define an error handler to catch the error. Recall that you don’t have to do this with the IF statement.

SELECT if(hide = 0,FALSE,TRUE) col FROM tbl; #for BOOLEAN Value return

or

SELECT if(hide = 0,'FALSE','TRUE') col FROM tbl; #for string Value return

How to find reason of failed Build without any error or warning

I had the same problem. The error list window has 2 dropdowns "Show items contained by" and "Show issues generated". These names are visible after hovering over the dropdown. The "Show issues generated" dropdown was set to "Build + IntelliSense" and after changing to "Build Only" the errors appeared on the list.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Creating an R dataframe row-by-row

I've found this way to create dataframe by raw without matrix.

With automatic column name

df<-data.frame(
        t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
        ,row.names = NULL,stringsAsFactors = FALSE
    )

With column name

df<-setNames(
        data.frame(
            t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
            ,row.names = NULL,stringsAsFactors = FALSE
        ), 
        c("col1","col2","col3")
    )

Gradle finds wrong JAVA_HOME even though it's correctly set

Adding below lines in build.gradle solved my issue .

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 8.2, iOS 10

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>