Programs & Examples On #Keyboardfocusmanager

jQuery UI Datepicker - Multiple Date Selections

I have now spent quite some time trying to find a good date picker that support interval ranges, and eventually found this one:

http://keith-wood.name/datepick.html

I believe this may be the best jquery date picker for selecting a range or multiple dates, and it is claimed to have been the base for the jQuery UI datepicker, and I see no reason to doubt that since it seems to be really powerful, and also good documented !

Show how many characters remaining in a HTML text box using JavaScript

How about this approach, which splits the problem into two parts:

  • Using jQuery, it shows a decrementing counter below the textarea, which turns red when it hits zero but still allows the user to type.
  • I use a separate string length validator (server and client-side) to actually prevent submission of the form if the number of chatacters in the textarea is greater than 160.

My textarea has an id of Message, and the span in which I display the number of remaining characters has an id of counter. The css class of error gets applied when the number of remaining characters hits zero.

var charactersAllowed = 160;

$(document).ready(function () {
    $('#Message').keyup(function () {
        var left = charactersAllowed - $(this).val().length;
        if (left < 0) {
            $('#counter').addClass('error');
            left = 0;
        }
        else {
            $('#counter').removeClass('error');
        }
        $('#counter').text('Characters left: ' + left);
    });
});

is it possible to get the MAC address for machine using nmap

In current releases of nmap you can use:

sudo nmap -sn 192.168.0.*

This will print the MAC addresses of all available hosts. Of course provide your own network, subnet and host id's.

Further explanation can be found here.

Git pull till a particular commit

git pull is nothing but git fetch followed by git merge. So what you can do is

git fetch remote example_branch

git merge <commit_hash>

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

How do you get the currently selected <option> in a <select> via JavaScript?

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

How to add an extra column to a NumPy array

Add an extra column to a numpy array:

Numpy's np.append method takes three parameters, the first two are 2D numpy arrays and the 3rd is an axis parameter instructing along which axis to append:

import numpy as np  
x = np.array([[1,2,3], [4,5,6]]) 
print("Original x:") 
print(x) 

y = np.array([[1], [1]]) 
print("Original y:") 
print(y) 

print("x appended to y on axis of 1:") 
print(np.append(x, y, axis=1)) 

Prints:

Original x:
[[1 2 3]
 [4 5 6]]
Original y:
[[1]
 [1]]
x appended to y on axis of 1:
[[1 2 3 1]
 [4 5 6 1]]

How to get class object's name as a string in Javascript?

Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:

function myClass() { 
  this.myName = function () { 
    // search through the global object for a name that resolves to this object
    for (var name in this.global) 
      if (this.global[name] == this) 
        return name 
  } 
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"

Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.

edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:

function myConstructor () {
  this.count = 0
  this.clickme = function () {
    this.count += 1
    alert(this.count)
  }

  var newDiv = document.createElement("div")
  var contents = document.createTextNode("Click me!")

  // This is the crucial part. We don't construct an onclick handler by creating a
  // string, but instead we pass in a function that does what we want. In order to
  // refer to the object, we can't use this directly (since that will refer to the 
  // div when running event handler), but we create an anonymous function with an 
  // argument and pass this in as that argument.
  newDiv.onclick = (function (obj) { 
    return function () {
      obj.clickme()
    }
  })(this)

  newDiv.appendChild(contents)
  document.getElementById("frobnozzle").appendChild(newDiv)

}
window.onload = function () {
  var myVar = new myConstructor()
}

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

I saw that someone was wondering how to do it for another controller.

In my case I had all of my email templates in the Views/Email folder, but you could modify this to pass in the controller in which you have views associated for.

public static string RenderViewToString(Controller controller, string viewName, object model)
    {
        var oldController = controller.RouteData.Values["controller"].ToString();

        if (controller.GetType() != typeof(EmailController))
            controller.RouteData.Values["controller"] = "Email";

        var oldModel = controller.ViewData.Model;
        controller.ViewData.Model = model;
        try
        {
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName,
                                                                           null);

                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                //Cleanup
                controller.ViewData.Model = oldModel;
                controller.RouteData.Values["controller"] = oldController;

                return sw.GetStringBuilder().ToString();
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

            throw ex;
        }
    }

Essentially what this does is take a controller, such as AccountController and modify it to think it's an EmailController so that the code will look in the Views/Email folder. It's necessary to do this because the FindView method doesn't take a straight up path as a parameter, it wants a ControllerContext.

Once done rendering the string, it returns the AccountController back to its initial state to be used by the Response object.

Passive Link in Angular 2 - <a href=""> equivalent

Here is a simple way

  <div (click)="$event.preventDefault()">
            <a href="#"></a>
   </div>

capture the bubbling event and shoot it down

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

There's no need for you to use super-call of the ActionBarDrawerToggle which requires the Toolbar. This means instead of using the following constructor:

ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)

You should use this one:

ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)

So basically the only thing you have to do is to remove your custom drawable:

super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);

More about the "new" ActionBarDrawerToggle in the Docs (click).

Trim a string in C

/* Function to remove white spaces on both sides of a string i.e trim */

void trim (char *s)
{
    int i;

    while (isspace (*s)) s++;   // skip left side white spaces
    for (i = strlen (s) - 1; (isspace (s[i])); i--) ;   // skip right side white spaces
    s[i + 1] = '\0';
    printf ("%s\n", s);
}

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

How to unapply a migration in ASP.NET Core with EF Core

You can do it with:

dotnet ef migrations remove

Warning

Take care not to remove any migrations which are already applied to production databases. Not doing so will prevent you from being able to revert it, and may break the assumptions made by subsequent migrations.

How to show an empty view with a RecyclerView?

Here is a solution using only a custom adapter with a different view type for the empty situation.

public class EventAdapter extends 
    RecyclerView.Adapter<EventAdapter.ViewHolder> {

    private static final int VIEW_TYPE_EVENT = 0;
    private static final int VIEW_TYPE_DATE = 1;
    private static final int VIEW_TYPE_EMPTY = 2;

    private ArrayList items;

    public EventAdapter(ArrayList items) {
        this.items = items;
    }

    @Override
    public int getItemCount() {
        if(items.size() == 0){
            return 1;
        }else {
            return items.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (items.size() == 0) {
            return VIEW_TYPE_EMPTY;
        }else{
            Object item = items.get(position);
            if (item instanceof Event) {
                return VIEW_TYPE_EVENT;
            } else {
                return VIEW_TYPE_DATE;
            }
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v;
        ViewHolder vh;
        if (viewType == VIEW_TYPE_EVENT) {
            v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_event, parent, false);
            vh = new ViewHolderEvent(v);
        } else if (viewType == VIEW_TYPE_DATE) {
            v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_event_date, parent, false);
            vh = new ViewHolderDate(v);
        } else {
            v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_event_empty, parent, false);
            vh = new ViewHolder(v);
        }

        return vh;
    }

    @Override
    public void onBindViewHolder(EventAdapter.ViewHolder viewHolder, 
                                 final int position) {
        int viewType = getItemViewType(position);
        if (viewType == VIEW_TYPE_EVENT) {
            //...
        } else if (viewType == VIEW_TYPE_DATE) {
            //...
        } else if (viewType == VIEW_TYPE_EMPTY) {
            //...
        }
    }

    public static class ViewHolder extends ParentViewHolder {
        public ViewHolder(View v) {
            super(v);
        }
    }

    public static class ViewHolderDate extends ViewHolder {
        public ViewHolderDate(View v) {
            super(v);
        }
    }

    public static class ViewHolderEvent extends ViewHolder {
        public ViewHolderEvent(View v) {
            super(v);
        }
    }

}

How can I convert a dictionary into a list of tuples?

What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

How do you Programmatically Download a Webpage in Java

You'd most likely need to extract code from a secure web page (https protocol). In the following example, the html file is being saved into c:\temp\filename.html Enjoy!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * <b>Get the Html source from the secure url </b>
 */
public class HttpsClientUtil {
    public static void main(String[] args) throws Exception {
        String httpsURL = "https://stackoverflow.com";
        String FILENAME = "c:\\temp\\filename.html";
        BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));
        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
        con.setRequestProperty ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" );
        InputStream ins = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins, "Windows-1252");
        BufferedReader in = new BufferedReader(isr);
        String inputLine;

        // Write each line into the file
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
            bw.write(inputLine);
        }
        in.close(); 
        bw.close();
    }
}

How to describe "object" arguments in jsdoc?

If a parameter is expected to have a specific property, you can document that property by providing an additional @param tag. For example, if an employee parameter is expected to have name and department properties, you can document it as follows:

/**
 * Assign the project to a list of employees.
 * @param {Object[]} employees - The employees who are responsible for the project.
 * @param {string} employees[].name - The name of an employee.
 * @param {string} employees[].department - The employee's department.
 */
function(employees) {
    // ...
}

If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties.

/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function({ name, department }) {
    // ...
};

Source: JSDoc

Is there a printf converter to print in binary format?

None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use %B with the printf!

/*
 * File:   main.c
 * Author: Techplex.Engineer
 *
 * Created on February 14, 2012, 9:16 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
#include <math.h>
#include <string.h>

static int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)
{
    /* "%M" always takes one argument, a pointer to uint8_t[6]. */
    if (n > 0) {
        argtypes[0] = PA_POINTER;
    }
    return 1;
}

static int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)
{
    int value = 0;
    int len;

    value = *(int **) (args[0]);

    // Beginning of my code ------------------------------------------------------------
    char buffer [50] = "";  // Is this bad?
    char buffer2 [50] = "";  // Is this bad?
    int bits = info->width;
    if (bits <= 0)
        bits = 8;  // Default to 8 bits

    int mask = pow(2, bits - 1);
    while (mask > 0) {
        sprintf(buffer, "%s", ((value & mask) > 0 ? "1" : "0"));
        strcat(buffer2, buffer);
        mask >>= 1;
    }
    strcat(buffer2, "\n");
    // End of my code --------------------------------------------------------------
    len = fprintf(stream, "%s", buffer2);
    return len;
}

int main(int argc, char** argv)
{
    register_printf_specifier('B', printf_output_M, printf_arginfo_M);

    printf("%4B\n", 65);

    return EXIT_SUCCESS;
}

Output in a table format in Java's System.out

public class Main {
 public static void main(String args[]) {
   String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
   System.out.format(format, "A", "AA", "AAA");
   System.out.format(format, "B", "", "BBBBB");
   System.out.format(format, "C", "CCCCC", "CCCCCCCC");

   String ex[] = { "E", "EEEEEEEEEE", "E" };

   System.out.format(String.format(format, (Object[]) ex));
 }
}

differece in sizes of input doesnt effect the output

How to redirect to a different domain using NGINX?

You can simply write a if condition inside server {} block:

server { 

    if ($host = mydomain.com) {
        return 301 http://www.adifferentdomain.com;
    } 
}

Removing MySQL 5.7 Completely

Run these commands in the terminal:

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo apt-get autoremove

sudo apt-get autoclean

Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).

Please refer to How do I uninstall Mysql?

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

How to install Android Studio on Ubuntu?

You can also Install using a PPA link

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

and all the other things will remain same...

For those who are having problem Drawerlayout overlaying toolbar

add android:layout_marginTop="?attr/actionBarSize" to root layout of drawer content

Number of rows affected by an UPDATE in PL/SQL

You use the sql%rowcount variable.

You need to call it straight after the statement which you need to find the affected row count for.

For example:

set serveroutput ON; 
DECLARE 
    i NUMBER; 
BEGIN 
    UPDATE employees 
    SET    status = 'fired' 
    WHERE  name LIKE '%Bloggs'; 
    i := SQL%rowcount; 
    --note that assignment has to precede COMMIT
    COMMIT; 
    dbms_output.Put_line(i); 
END; 

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

CSS selector for text input fields?

I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:

$(document).ready(function(){
  $("input[type='text']").addClass('text');
)};

And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.

Why does CSS not support negative padding?

Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)

Negative margins would be an easy solution.

How to change default install location for pip

Open Terminal and type:

pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages

except instead of

/Users/Bob/Library/Python/3.8/lib/python/site-packages

you would use whatever directory you want.

How to get WordPress post featured image URL

Use:

<?php 
    $image_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail_size');

    $feature_image_url = $image_src[0]; 
?>

You can change the thumbnail_size value as per your required size.

surface plots in matplotlib

Just to chime in, Emanuel had the answer that I (and probably many others) are looking for. If you have 3d scattered data in 3 separate arrays, pandas is an incredible help and works much better than the other options. To elaborate, suppose your x,y,z are some arbitrary variables. In my case these were c,gamma, and errors because I was testing a support vector machine. There are many potential choices to plot the data:

  • scatter3D(cParams, gammas, avg_errors_array) - this works but is overly simplistic
  • plot_wireframe(cParams, gammas, avg_errors_array) - this works, but will look ugly if your data isn't sorted nicely, as is potentially the case with massive chunks of real scientific data
  • ax.plot3D(cParams, gammas, avg_errors_array) - similar to wireframe

Wireframe plot of the data

Wireframe plot of the data

3d scatter of the data

3d scatter of the data

The code looks like this:

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_xlabel('c parameter')
    ax.set_ylabel('gamma parameter')
    ax.set_zlabel('Error rate')
    #ax.plot_wireframe(cParams, gammas, avg_errors_array)
    #ax.plot3D(cParams, gammas, avg_errors_array)
    #ax.scatter3D(cParams, gammas, avg_errors_array, zdir='z',cmap='viridis')

    df = pd.DataFrame({'x': cParams, 'y': gammas, 'z': avg_errors_array})
    surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.1)
    fig.colorbar(surf, shrink=0.5, aspect=5)    
    plt.savefig('./plots/avgErrs_vs_C_andgamma_type_%s.png'%(k))
    plt.show()

Here is the final output:

plot_trisurf of xyz data

In android how to set navigation drawer header image and name programmatically in class file?

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.addHeaderView(yourview);

How can I disable an <option> in a <select> based on its value in JavaScript?

I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.

HTML

Status:  
<div id="option">
   <select class="status">
      <option value="hand" selected>Hand</option>
      <option value="simple">Typed</option>
      <option value="printed">Printed</option>
   </select>
</div>

Javascript

The idea here is how to disable Printed option when current Status is Hand

var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;

You may see how it works here:

https://jsfiddle.net/chetabahana/f7ejxhnk/28/

How to convert a currency string to a double with jQuery or Javascript?

    $ 150.00
    Fr. 150.00
    € 689.00

I have tested for above three currency symbols .You can do it for others also.

    var price = Fr. 150.00;
    var priceFloat = price.replace(/[^\d\.]/g, '');

Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as

    console.log('priceFloat : '+priceFloat);

    output will be like  priceFloat : .150.00

which is wrong so you check the index of "." then split that and get the proper result.

    if (priceFloat.indexOf('.') == 0) {
            priceFloat = parseFloat(priceFloat.split('.')[1]);
    }else{
            priceFloat = parseFloat(priceFloat);
    }

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How can I upgrade specific packages using pip and a requirements file?

Defining a specific version to upgrade helped me instead of only the upgrade command.

pip3 install larapy-installer==0.4.01 -U

How to edit incorrect commit message in Mercurial?

Rollback-and-reapply is realy simple solution, but it can help only with the last commit. Mercurial Queues is much more powerful thing (note that you need to enable Mercurial Queues Extension in order to use "hg q*" commands).

How best to determine if an argument is not sent to the JavaScript function

If you are using jQuery, one option that is nice (especially for complicated situations) is to use jQuery's extend method.

function foo(options) {

    default_options = {
        timeout : 1000,
        callback : function(){},
        some_number : 50,
        some_text : "hello world"
    };

    options = $.extend({}, default_options, options);
}

If you call the function then like this:

foo({timeout : 500});

The options variable would then be:

{
    timeout : 500,
    callback : function(){},
    some_number : 50,
    some_text : "hello world"
};

What is the meaning of ToString("X2")?

It prints the byte in Hexadecimal format.

No format string: 13

'X2' format string: 0D

http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx

How to turn on/off MySQL strict mode in localhost (xampp)?

on server console:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';" 

How to create a circle icon button in Flutter?

You just need to use the shape: CircleBorder()

MaterialButton(
  onPressed: () {},
  color: Colors.blue,
  textColor: Colors.white,
  child: Icon(
    Icons.camera_alt,
    size: 24,
  ),
  padding: EdgeInsets.all(16),
  shape: CircleBorder(),
)

enter image description here

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

Selecting/excluding sets of columns in pandas

You just need to convert your set to a list

import pandas as pd
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
my_cols = set(df.columns)
my_cols.remove('B')
my_cols.remove('D')
my_cols = list(my_cols)
df2 = df[my_cols]

100% width in React Native Flexbox

Here you go:

Just change the line1 style as per below:

line1: {
    backgroundColor: '#FDD7E4',
    width:'100%',
    alignSelf:'center'
}

How to generate keyboard events?

For Python2.7(windows32) I installed only pywin32-223. And I wrote simple python`s code:

import win32api
import time
import win32con

# simulate the pressing-DOWN "ARROW key" of 200 times

for i in range(200):
   time.sleep(0.5)
   win32api.keybd_event(0x28, 0,0,0)
   time.sleep(.05)
   win32api.keybd_event(0x28,0 ,win32con.KEYEVENTF_KEYUP ,0)

It can be checked if you run the code and immediately go to the notepad window (where the text already exists) and place the cursor on the top line.

Representing Directory & File Structure in Markdown Syntax

If you're using VS Code, this is an awesome extension for generating file trees.

Added directly to markdown...

quakehunter
 ? client
 ? node_modules
 ? server
 ? ? index.js
 ? .gitignore
 ? package-lock.json
 ? package.json

What is Ad Hoc Query?

Ad hoc is latin for "for this purpose". You might call it an "on the fly" query, or a "just so" query. It's the kind of SQL query you just loosely type out where you need it

var newSqlQuery = "SELECT * FROM table WHERE id = " + myId;

...which is an entirely different query each time that line of code is executed, depending on the value of myId. The opposite of an ad hoc query is a predefined query such as a Stored Procedure, where you have created a single query for the entire generalized purpose of selecting from that table (say), and pass the ID as a variable.

SQL Insert Multiple Rows

For MSSQL, there are two ways:(Consider you have a 'users' table,below both examples are using this table for example)

1) In case, you need to insert different values in users table. Then you can write statement like:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

2) Another case, if you need to insert same value for all rows(for example, 10 rows you need to insert here). Then you can use below sample statement:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe')
GO 10

Hope this helps.

OnClick vs OnClientClick for an asp:CheckBox?

Because they are two different kinds of controls...

You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

renders to

<input type="check" OnClick="alert(this.checked);" />

and

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

renders to

<input type="check" OnClientClick="alert(this.checked);" />

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

Hiding a password in a python script (insecure obfuscation only)

You could also consider the possibility of storing the password outside the script, and supplying it at runtime

e.g. fred.py

import os
username = 'fred'
password = os.environ.get('PASSWORD', '')
print(username, password)

which can be run like

$ PASSWORD=password123 python fred.py
fred password123

Extra layers of "security through obscurity" can be achieved by using base64 (as suggested above), using less obvious names in the code and further distancing the actual password from the code.

If the code is in a repository, it is often useful to store secrets outside it, so one could add this to ~/.bashrc (or to a vault, or a launch script, ...)

export SURNAME=cGFzc3dvcmQxMjM=

and change fred.py to

import os
import base64
name = 'fred'
surname = base64.b64decode(os.environ.get('SURNAME', '')).decode('utf-8')
print(name, surname)

then re-login and

$ python fred.py
fred password123

What is the first character in the sort order used by Windows Explorer?

From my testing, there are three criteria for sorting characters as described below. Aside from this, shorter strings are sorted above longer strings that start with the same characters.

Note: This testing only looked at the first character sorting and did not look into edge cases described by this answer, which found that, for all characters after the first character, numbers take precedence over symbols (i.e. the order is 1. Symbols 2. Numbers 3. Letters for first character, 1. Numbers 2. Symbols 3. Letters after). This answer also indicated that the Unicode/ASCII layer of sorting might not be entirely consistent. I'll update this answer if I get time to look into these edge cases.

Note: It's important to note that sorting order might be subject to change as described by this answer. It is not clear to me though the extent to which this actually ever changes. I've done this testing and found it to be valid on both Windows 7 and Windows 10.


Symbols
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Numbers
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Letters
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

enter image description here


Sorting Rule Sequence vs Observed Order

It's worth noting that there are really two ways of looking at this. Ultimately, what you have are sorting rules that are applied in a certain order, in turn, this produces an observed order. The ordering of older rules becomes nested under the ordering of newer rules. This means that the first rule applied is the last rule observed, while the last rule applied is the first or topmost rule observed.

Sorting Rule Sequence

1.) Sort on Unicode Value (U+xxxx)
2.) Sort on culture/language
3.) Sort on Type (Symbol, Number, Letter)

Observed Order

  • The highest level of grouping is by type in the following order...

    1.) Symbols
    2.) Numbers
    3.) Letters

    Therefore, any symbol from any language comes before any number from any language, while any letter from any language appears after all symbols and numbers.

  • The second level of grouping is by culture/language. The following order seems to apply for this:

    Latin
    Greek
    Cyrillic
    Hebrew
    Arabic

  • The lowest rule observed is Unicode order, so items within a type-language group are ordered by Unicode value (U+xxxx).


Adapted from here: https://superuser.com/a/971721/496260

How to get full path of a file?

You could use the fpn (full path name) script:

% pwd
/Users/adamatan/bins/scripts/fpn

% ls
LICENSE   README.md fpn.py

% fpn *
/Users/adamatan/bins/scripts/fpn/LICENSE
/Users/adamatan/bins/scripts/fpn/README.md
/Users/adamatan/bins/scripts/fpn/fpn.py

fpn is not a standard Linux package, but it's a free and open github project and you could set it up in a minute.

Space between two rows in a table?

You may try to add separator row:

html:

<tr class="separator" />

css:

table tr.separator { height: 10px; }

How to make a Bootstrap accordion collapse when clicking the header div?

Simple solution would be to remove padding from .panel-heading and add to .panel-title a.

.panel-heading {
    padding: 0;
}
.panel-title a {
    display: block;
    padding: 10px 15px;
}

This solution is similar to the above one posted by calfzhou, slightly different.

How to set ANDROID_HOME path in ubuntu?

better way is to reuse ANDROID_HOME variable in path variable. if your ANDROID_HOME variable changes you just have to make change at one place.

export ANDROID_HOME=/home/arshid/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Following many hours of search and testing i found following solution(by implementing different SO solutions) here it what didn't failed in any case i was getting crash.

     Runnable runnable = new Runnable() {
            @Override
            public void run() {

          //displayPopup,progress dialog or what ever action. example

                ProgressDialogBox.setProgressBar(Constants.LOADING,youractivityName.this);
            }};

Where logcat is indicating the crash is happening.. start a runnable .in my case at receiving broadcast.

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!isFinishing()) {
                    new Handler().postAtTime(runnable,2000);
                }
            }
        });

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was unable to access to S3 because

  • first I configured key access on the instance (it was impossible to attach role after the launch then)
  • forgot about it for a few months
  • attached role to instance
  • tried to access. The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

Create WordPress Page that redirects to another URL

Alternately, use a filter.

Create an empty page in your WordPress blog, named appropriately to what you need it to be. Take note of the post_id. Then create a filter that alters its permalink.

add_filter('get_the_permalink','my_permalink_redirect');
function my_permalink_redirect($permalink) {
    global $post;
    if ($post->ID == your_post_id_here) {
        $permalink = 'http://new-url.com/pagename';
    }
    return $permalink;
}

This way the url will show up correctly in the page no funny redirects are required.

If you need to do this a lot, then think about using the custom postmeta fields to define a postmeta value for "offsite_url" or something like that, then you can create pages as needed, enter the "offsite_url" value and then use a filter like the one above to instead of checking the post_id you check to see if it has the postmeta required and alter the permalink as needed.

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

How to get response from S3 getObject in Node.js?

At first glance it doesn't look like you are doing anything wrong but you don't show all your code. The following worked for me when I was first checking out S3 and Node:

var AWS = require('aws-sdk');

if (typeof process.env.API_KEY == 'undefined') {
    var config = require('./config.json');
    for (var key in config) {
        if (config.hasOwnProperty(key)) process.env[key] = config[key];
    }
}

var s3 = new AWS.S3({accessKeyId: process.env.AWS_ID, secretAccessKey:process.env.AWS_KEY});
var objectPath = process.env.AWS_S3_FOLDER +'/test.xml';
s3.putObject({
    Bucket: process.env.AWS_S3_BUCKET, 
    Key: objectPath,
    Body: "<rss><data>hello Fred</data></rss>",
    ACL:'public-read'
}, function(err, data){
    if (err) console.log(err, err.stack); // an error occurred
    else {
        console.log(data);           // successful response
        s3.getObject({
            Bucket: process.env.AWS_S3_BUCKET, 
            Key: objectPath
        }, function(err, data){
            console.log(data.Body.toString());
        });
    }
});

How to set IE11 Document mode to edge as default?

try to add this section in your web.config file on web server, sometimes it happens with php pages:

<httpProtocol>
    <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=edge" />
    </customHeaders>
</httpProtocol>

What is Common Gateway Interface (CGI)?

CGI is an interface specification between a web server (HTTP server) and an executable program of some type that is to handle a particular request.

It describes how certain properties of that request should be communicated to the environment of that program and how the program should communicate the response back to the server and how the server should 'complete' the response to form a valid reply to the original HTTP request.

For a while CGI was an IETF Internet Draft and as such had an expiry date. It expired with no update so there was no CGI 'standard'. It is now an informational RFC, but as such documents common practice and isn't a standard itself. rfc3875.txt, rfc3875.html

Programs implementing a CGI interface can be written in any language runnable on the target machine. They must be able to access environment variables and usually standard input and they generate their output on standard output.

Compiled languages such as C were commonly used as were scripting languages such as perl, often using libraries to make accessing the CGI environment easier.

One of the big disadvantages of CGI is that a new program is spawned for each request so maintaining state between requests could be a major performance issue. The state might be handled in cookies or encoded in a URL, but if it gets to large it must be stored elsewhere and keyed from encoded url information or a cookie. Each CGI invocation would then have to reload the stored state from a store somewhere.

For this reason, and for a greatly simple interface to requests and sessions, better integrated environments between web servers and applications are much more popular. Environments like a modern php implementation with apache integrate the target language much better with web server and provide access to request and sessions objects that are needed to efficiently serve http requests. They offer a much easier and richer way to write 'programs' to handle HTTP requests.

Whether you wrote a CGI script rather depends on interpretation. It certainly did the job of one but it is much more usual to run php as a module where the interface between the script and the server isn't strictly a CGI interface.

Which JRE am I using?

As you are expecting it to know using the Javascript, I believe you want to know the JRE versioned being used in your browser. Hence you can include Java version tester applet which can exactly tell you the version of the current browser.

import java.applet.*;
import java.awt.*;

public class JavaVersionDisplayApplet extends Applet
{
  private Label m_labVersionVendor;

  public JavaVersionDisplayApplet() // Constructor
  {
    Color colFrameBackground = Color.pink;
    this.setBackground(colFrameBackground);
    m_labVersionVendor = new Label (" Java Version: " +
                                   System.getProperty("java.version") +
                          " from "+System.getProperty("java.vendor"));
    this.add(m_labVersionVendor);
  }
}

Convert special characters to HTML in Javascript

Use the javaScript Function escape(), that lets you encode strings.

e.g.,

escape("yourString");

How can I add a space in between two outputs?

+"\n" + can be added in print command to display the code block after it in next line

E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.

Why do I need to do `--set-upstream` all the time?

If the below doesn't work:

git config --global push.default current

You should also update your project's local config, as its possible your project has local git configurations:

git config --local push.default current

jquery drop down menu closing by clicking outside

You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

/* Anything that gets to the document
   will hide the dropdown */
$(document).click(function(){
  $("#dropdown").hide();
});

/* Clicks within the dropdown won't make
   it past the dropdown itself */
$("#dropdown").click(function(e){
  e.stopPropagation();
});

Demo: http://jsbin.com/umubad/2/edit

Updating records codeigniter

In codeigniter doc if you update specific field just do this

$data = array(
    'yourfieldname' => value,
    'name' => $name,
    'date' => $date
);

$this->db->where('yourfieldname', yourfieldvalue);
$this->db->update('yourtablename', $data);

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I had old project and same problem and I solved .

1.Go to summary
2.Summary have keychain groups and delete keychanin groups's object.

I hope it's will work for you . Regards.

Having services in React application

I am in the same boot like you. In the case you mention, I would implement the input validation UI component as a React component.

I agree the implementation of the validation logic itself should (must) not be coupled. Therefore I would put it into a separate JS module.

That is, for logic that should not be coupled use a JS module/class in separate file, and use require/import to de-couple the component from the "service".

This allows for dependency injection and unit testing of the two independently.

How to Store Historical Data

I Know this old post but Just wanted to add few points. The standard for such problems is what works best for the situation. understanding the need for such storage, and potential use of the historical/audit/change tracking data is very importat.

Audit (security purpose) : Use a common table for all your auditable tables. define structure to store column name , before value and after value fields.

Archive/Historical: for cases like tracking previous address , phone number etc. creating a separate table FOO_HIST is better if you your active transaction table schema does not change significantly in the future(if your history table has to have the same structure). if you anticipate table normalization , datatype change addition/removal of columns, store your historical data in xml format . define a table with the following columns (ID,Date, Schema Version, XMLData). this will easily handle schema changes . but you have to deal with xml and that could introduce a level of complication for data retrieval .

"Cloning" row or column vectors

Use numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

or for repeating columns:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

Script Tag - async & defer

This image explains normal script tag, async and defer

enter image description here

  • Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )

  • Defer scripts guarantees the order of execution in which they appear in the page.

Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

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

For Python 3, I did:

sudo apt install python3-dev postgresql postgresql-contrib python3-psycopg2 libpq-dev

and then I was able to do:

pip3 install psycopg2

"Permission Denied" trying to run Python on Windows 10

Simple answer: replace python with PY everything will work as expected

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

What are Maven goals and phases and what is their difference?

The chosen answer is great, but still I would like to add something small to the topic. An illustration.

It clearly demonstrates how the different phases binded to different plugins and the goals that those plugins expose.

So, let's examine a case of running something like mvn compile:

  • It's a phase which execute the compiler plugin with compile goal
  • Compiler plugin got different goals. For mvn compile it's mapped to a specific goal, the compile goal.
  • It's the same as running mvn compiler:compile

Therefore, phase is made up of plugin goals.

enter image description here

Link to the reference

How to move a file?

Although os.rename() and shutil.move() will both rename files, the command that is closest to the Unix mv command is shutil.move(). The difference is that os.rename() doesn't work if the source and destination are on different disks, while shutil.move() doesn't care what disk the files are on.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

The most simple tool: use pdftk (or pdftk.exe, if you are on Windows):

pdftk 10_MB.pdf 100_MB.pdf cat output 110_MB.pdf

This will be a valid PDF. Download pdftk here.

Update: if you want really large (and valid!), non-optimized PDFs, use this command:

pdftk 100MB.pdf 100MB.pdf 100MB.pdf 100MB.pdf 100MB.pdf cat output 500_MB.pdf

or even (if you are on Linux, Unix or Mac OS X):

pdftk $(for i in $(seq 1 100); do echo -n "100MB.pdf "; done) cat output 10_GB.pdf

How do I get a file's last modified time in Perl?

Calling the built-in function stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions)
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated

Element number 9 in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);

Alternatively, you can use the built-in module File::stat (included as of Perl 5.004) for a more object-oriented interface.

And to avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). Together these lead to some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

How do I check whether an array contains a string in TypeScript?

You can use filter too

this.products = array_products.filter((x) => x.Name.includes("ABC"))

How do I move focus to next input with jQuery?

JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters

HTML:

text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
    <option value="1">1</option>
    <option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
    <option value="1">1</option>
    <option value="1">2</option>
</select>

Javascript:

$(function() {
    var focusables = $(":focusable");   
    focusables.keyup(function(e) {
        var maxchar = false;
        if ($(this).attr("maxchar")) {
            if ($(this).val().length >= $(this).attr("maxchar"))
                maxchar = true;
            }
        if (e.keyCode == 13 || maxchar) {
            var current = focusables.index(this),
                next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
            next.focus();
        }
    });
});

simple Jquery hover enlarge

To create simple hover enlarge plugin, try this. (DEMO)

HTML

     <div id="content">
     <img src="http://www.freevectorgallery.com/wp-content/uploads/2011/10/Vintage-Microphone- 11395-large.jpg" style="width:50%;" />
     </div>

js

        $(function () {
          $('#content img').hover(function () {
          $(this).toggle(function () {
          $(this).width('70%');
                   });
              });
         });

How to replace (null) values with 0 output in PIVOT

I have encountered similar problem. The root cause is that (use your scenario for my case), in the #temp table, there is no record for
a. CLASS=RICE and STATE=TX
b. CLASS=VEGIE and (STATE=AZ or STATE=CA)
So, when MSSQL does pivot for no record, MSSQL always shows NULL for MAX, SUM, ... (aggregate functions)

None of above solutions (IsNull([AZ], 0)) works for me. But I do get ideas from these solutions. Thanks.

Sorry, it really depends on the #TEMP table. I can only provide some suggestions.
1. Make sure #TEMP table have records for below condition, even Data is null.
a. CLASS=RICE and STATE=TX
b. CLASS=VEGIE and (STATE=AZ or STATE=CA) You may need to use cartesian product: select A.*, B.* from A, B 2. In the select query for #temp, if you need to join any table with WHERE, then would better put where inside another sub select query. (Goal is 1.)
3. Use isnull(DATA, 0) in #TEMP table.
4. Before pivot, make sure you have achieved Goal 1.

I can't give an answer to the orginal question, since there is no enough info for #temp table. I have pasted my code as example here, hope this will help others.

_x000D_
_x000D_
SELECT * FROM (_x000D_
   SELECT eeee.id as enterprise_id_x000D_
   , eeee.name AS enterprise_name_x000D_
   , eeee.indicator_name_x000D_
   , CONVERT(varchar(12) , isnull(eid.[date],'2019-12-01') , 23) AS data_date_x000D_
   , isnull(eid.value,0) AS indicator_value_x000D_
   FROM (select ei.id as indicator_id, ei.name as indicator_name, e.* FROM tbl_enterprise_indicator ei, tbl_enterprise e) eeee            _x000D_
   LEFT JOIN  (select * from tbl_enterprise_indicator_data WHERE [date]='2020-01-01') eid_x000D_
     ON  eeee.id = eid.enterprise_id and eeee.indicator_id = enterprise_indicator_id_x000D_
  ) AS P _x000D_
  PIVOT _x000D_
  (_x000D_
   SUM(P.indicator_value) FOR P.indicator_name IN(TX,CA)_x000D_
  ) AS T 
_x000D_
_x000D_
_x000D_

What is the difference between 127.0.0.1 and localhost

Wikipedia sums this up well:

On modern computer systems, localhost as a hostname translates to an IPv4 address in the 127.0.0.0/8 (loopback) net block, usually 127.0.0.1, or ::1 in IPv6.

The only difference is that it would be looking up in the DNS for the system what localhost resolves to. This lookup is really, really quick. For instance, to get to stackoverflow.com you typed in that to the address bar (or used a bookmarklet that pointed here). Either way, you got here through a hostname. localhost provides a similar functionality.

fatal: could not read Username for 'https://github.com': No such file or directory

For me nothing worked from suggested above, I use git pull from jenkins shell script and apparently it takes wrong user name. I spent ages before I found a way to fix it without switching to SSH.

In your the user's folder create .gitconfig file (if you don't have it already) and put your credentials in following format: https://user:[email protected], more info. After your .gitconfig file link to those credentials, in my case it was:

[credential] helper = store --file /Users/admin/.git-credentials

Now git will always use those credentials no matter what. I hope it will help someone, like it helped me.

How to create a drop-down list?

enter image description here

Here is the code for it.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Spinner
    android:id="@+id/static_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:layout_marginTop="20dp" />

<Spinner
    android:id="@+id/dynamic_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ahotbrew.com - Dropdown</string> 
<string-array name="brew_array">
    <item>Cappuccino</item>
    <item>Espresso</item>
    <item>Mocha</item>
    <item>Caffè Americano</item>
    <item>Cafe Zorro</item>
</string-array> 

MainActivity

Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);

    // Create an ArrayAdapter using the string array and a default spinner
    ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
            .createFromResource(this, R.array.brew_array,
                    android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    staticAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    staticSpinner.setAdapter(staticAdapter);

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);

    dynamicSpinner.setAdapter(adapter);

    dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    });

This example is from http://www.ahotbrew.com/android-dropdown-spinner-example/

How to remove all characters after a specific character in python?

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

Output: "This is a test"

What is "Advanced" SQL?

I would expect:

  • stored procedure creation and usage
  • joins (inner and outer) and how to correctly use GROUP BY
  • performance evaluation/tuning
  • knowledge of efficient (and inefficient) ways of doing things in queries (understanding how certain things can affect performance, e.g. using functions in WHERE clauses)
  • dynamic SQL and knowledge of cursors (and IMO the few times they should be used)
  • understanding of schema design, indexing, and referential integrity

how to open a jar file in Eclipse

A project is not exactly the same thing as an executable jar file.

For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.

How to target the href to div

havent tried but this might help

$(document).ready(function(){
r=0;s=-1;
$(a).click(function(){
v=$(this).html();
$(a).each(function(){
if($(this).html()==v)
return;
else ++r;
$(div).each(function(){
if(s==r)
$(div).appendTo($(".target")); 
++S;
});

});

});

});

How to pass List from Controller to View in MVC 3

  1. Create a model which contains your list and other things you need for the view.

    For example:

    public class MyModel
    {
        public List<string> _MyList { get; set; }
    }
    
  2. From the action method put your desired list to the Model, _MyList property, like:

    public ActionResult ArticleList(MyModel model)
    {
        model._MyList = new List<string>{"item1","item2","item3"};
        return PartialView(@"~/Views/Home/MyView.cshtml", model);
    }
    
  3. In your view access the model as follows

    @model MyModel
    foreach (var item in Model)
    {
       <div>@item</div>
    }
    

I think it will help for start.

How to debug PDO database queries?

How to debug PDO mysql database queries in Ubuntu

TL;DR Log all your queries and tail the mysql log.

These directions are for my install of Ubuntu 14.04. Issue command lsb_release -a to get your version. Your install might be different.

Turn on logging in mysql

  1. Go to your dev server cmd line
  2. Change directories cd /etc/mysql. You should see a file called my.cnf. That’s the file we’re gonna change.
  3. Verify you’re in the right place by typing cat my.cnf | grep general_log. This filters the my.cnf file for you. You should see two entries: #general_log_file = /var/log/mysql/mysql.log && #general_log = 1.
  4. Uncomment those two lines and save via your editor of choice.
  5. Restart mysql: sudo service mysql restart.
  6. You might need to restart your webserver too. (I can’t recall the sequence I used). For my install, that’s nginx: sudo service nginx restart.

Nice work! You’re all set. Now all you have to do is tail the log file so you can see the PDO queries your app makes in real time.

Tail the log to see your queries

Enter this cmd tail -f /var/log/mysql/mysql.log.

Your output will look something like this:

73 Connect  xyz@localhost on your_db
73 Query    SET NAMES utf8mb4
74 Connect  xyz@localhost on your_db
75 Connect  xyz@localhost on your_db
74 Quit 
75 Prepare  SELECT email FROM customer WHERE email=? LIMIT ?
75 Execute  SELECT email FROM customer WHERE email='[email protected]' LIMIT 5
75 Close stmt   
75 Quit 
73 Quit 

Any new queries your app makes will automatically pop into view, as long as you continue tailing the log. To exit the tail, hit cmd/ctrl c.

Notes

  1. Careful: this log file can get huge. I’m only running this on my dev server.
  2. Log file getting too big? Truncate it. That means the file stays, but the contents are deleted. truncate --size 0 mysql.log.
  3. Cool that the log file lists the mysql connections. I know one of those is from my legacy mysqli code from which I'm transitioning. The third is from my new PDO connection. However, not sure where the second is coming from. If you know a quick way to find it, let me know.

Credit & thanks

Huge shout out to Nathan Long’s answer above for the inspo to figure this out on Ubuntu. Also to dikirill for his comment on Nathan’s post which lead me to this solution.

Love you stackoverflow!

MySQL: Curdate() vs Now()

Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-

NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.

NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;

How do you share code between projects/solutions in Visual Studio?

You can include a project in more than one solution. I don't think a project has a concept of which solution it's part of. However, another alternative is to make the first solution build to some well-known place, and reference the compiled binaries. This has the disadvantage that you'll need to do a bit of work if you want to reference different versions based on whether you're building in release or debug configurations.

I don't believe you can make one solution actually depend on another, but you can perform your automated builds in an appropriate order via custom scripts. Basically treat your common library as if it were another third party dependency like NUnit etc.

Is there a difference between using a dict literal and a dict constructor?

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):

Gen ADID

  • prepare web-page https://mypage.com/manager-login where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to https://mypage.com/statistics and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.

UPDATE

Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK https://mypage.com/access-link/ZD34jse24Sfses3J (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from https://mypage.com/statistics because it has ADID which is on servers whitelist

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

How to unescape a Java string literal in Java?

I'm a little late on this, but I thought I'd provide my solution since I needed the same functionality. I decided to use the Java Compiler API which makes it slower, but makes the results accurate. Basically I live create a class then return the results. Here is the method:

public static String[] unescapeJavaStrings(String... escaped) {
    //class name
    final String className = "Temp" + System.currentTimeMillis();
    //build the source
    final StringBuilder source = new StringBuilder(100 + escaped.length * 20).
            append("public class ").append(className).append("{\n").
            append("\tpublic static String[] getStrings() {\n").
            append("\t\treturn new String[] {\n");
    for (String string : escaped) {
        source.append("\t\t\t\"");
        //we escape non-escaped quotes here to be safe 
        //  (but something like \\" will fail, oh well for now)
        for (int i = 0; i < string.length(); i++) {
            char chr = string.charAt(i);
            if (chr == '"' && i > 0 && string.charAt(i - 1) != '\\') {
                source.append('\\');
            }
            source.append(chr);
        }
        source.append("\",\n");
    }
    source.append("\t\t};\n\t}\n}\n");
    //obtain compiler
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    //local stream for output
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    //local stream for error
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    //source file
    JavaFileObject sourceFile = new SimpleJavaFileObject(
            URI.create("string:///" + className + Kind.SOURCE.extension), Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return source;
        }
    };
    //target file
    final JavaFileObject targetFile = new SimpleJavaFileObject(
            URI.create("string:///" + className + Kind.CLASS.extension), Kind.CLASS) {
        @Override
        public OutputStream openOutputStream() throws IOException {
            return out;
        }
    };
    //file manager proxy, with most parts delegated to the standard one 
    JavaFileManager fileManagerProxy = (JavaFileManager) Proxy.newProxyInstance(
            StringUtils.class.getClassLoader(), new Class[] { JavaFileManager.class },
            new InvocationHandler() {
                //standard file manager to delegate to
                private final JavaFileManager standard = 
                    compiler.getStandardFileManager(null, null, null); 
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("getJavaFileForOutput".equals(method.getName())) {
                        //return the target file when it's asking for output
                        return targetFile;
                    } else {
                        return method.invoke(standard, args);
                    }
                }
            });
    //create the task
    CompilationTask task = compiler.getTask(new OutputStreamWriter(err), 
            fileManagerProxy, null, null, null, Collections.singleton(sourceFile));
    //call it
    if (!task.call()) {
        throw new RuntimeException("Compilation failed, output:\n" + 
                new String(err.toByteArray()));
    }
    //get the result
    final byte[] bytes = out.toByteArray();
    //load class
    Class<?> clazz;
    try {
        //custom class loader for garbage collection
        clazz = new ClassLoader() { 
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                if (name.equals(className)) {
                    return defineClass(className, bytes, 0, bytes.length);
                } else {
                    return super.findClass(name);
                }
            }
        }.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    //reflectively call method
    try {
        return (String[]) clazz.getDeclaredMethod("getStrings").invoke(null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

It takes an array so you can unescape in batches. So the following simple test succeeds:

public static void main(String[] meh) {
    if ("1\02\03\n".equals(unescapeJavaStrings("1\\02\\03\\n")[0])) {
        System.out.println("Success");
    } else {
        System.out.println("Failure");
    }
}

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I was up to date with everything and still got this error, not sure why but I think the image was corrupted in a strange way and after replacing the image I got rid of the error. Might be worth to try with a different image :)

Can HTML be embedded inside PHP "if" statement?

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).

Better is to use heredoc syntax. It is the same concept as in other languages (like bash).

 <?php
 if ($condition) {
   echo <<< END_OF_TEXT
     <b>lots of html</b> <i>$variable</i>
     lots of text...
 many lines possible, with any indentation, until the closing delimiter...
 END_OF_TEXT;
 }
 ?>

END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.

Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).

Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

Allow user to select camera or gallery for image

Building upon David's answer, my two pennies on the onActivityResult() part. It takes care of the changes introduced in 5.1.1 and detects whether the user has picked a single or multiple image from the library.

private enum Outcome {
    camera, singleLibrary, multipleLibrary, unknown
}

/**
 * Returns a List<Uri> containing the image uri(s) chosen by the user
 *
 * @param data      The data intent coming from the onActivityResult()
 * @param cameraUri The uri that had been passed to the intent when the chooser was invoked.
 * @return A List<Uri>, never null.
 */
public List<Uri> getPicturesUriFromIntent(Intent data, Uri cameraUri) {

    Outcome outcome = Outcome.unknown;

    if (data == null || (data.getData() == null && data.getClipData() == null)) {
        outcome = Outcome.camera;
    } else if (data.getData() != null && data.getClipData() == null) {
        outcome = Outcome.singleLibrary;
    } else if (data.getData() == null) {
        outcome = Outcome.multipleLibrary;
    } else {
        final String action = data.getAction();
        if (action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
            outcome = Outcome.camera;
        }
    }

    // list the uri(s) we got back
    List<Uri> uris = new ArrayList<>();
    switch (outcome) {
        case camera:
            uris.add(cameraUri);
            break;

        case singleLibrary:
            uris.add(data.getData());
            break;

        case multipleLibrary:
            final ClipData clipData = data.getClipData();
            for (int i = 0; i < clipData.getItemCount(); i++) {
                ClipData.Item item = clipData.getItemAt(i);
                uris.add(item.getUri());
            }
            break;
    }

    return uris;
}

Passing struct to function

The line function implementation should be:

void addStudent(struct student person) {

}

person is not a type but a variable, you cannot use it as the type of a function parameter.

Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

5 different ways to refresh a webpage using Selenium Webdriver

There is no special extra coding. I have just used the existing functions in different ways to get it work. Here they are :

  1. Using sendKeys.Keys method

    driver.get("https://accounts.google.com/SignUp");
    driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
    
  2. Using navigate.refresh() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().refresh();
    
  3. Using navigate.to() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().to(driver.getCurrentUrl());
    
  4. Using get() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.get(driver.getCurrentUrl());
    
  5. Using sendKeys() method

    driver.get("https://accounts.google.com/SignUp"); 
    driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
    

How to append to New Line in Node.js

Use the os.EOL constant instead.

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

GROUP BY without aggregate function

Given this data:

Col1  Col2  Col3
 A     X     1
 A     Y     2
 A     Y     3
 B     X     0
 B     Y     3
 B     Z     1

This query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

Would result in exactly the same table.

However, this query:

SELECT Col1, Col2 FROM data GROUP BY Col1, Col2

Would result in:

Col1  Col2
 A     X  
 A     Y  
 B     X  
 B     Y  
 B     Z  

Now, a query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2

Would create a problem: the line with A, Y is the result of grouping the two lines

 A     Y     2
 A     Y     3

So, which value should be in Col3, '2' or '3'?

Normally you would use a GROUP BY to calculate e.g. a sum:

SELECT Col1, Col2, SUM(Col3) FROM data GROUP BY Col1, Col2

So in the line, we had a problem with we now get (2+3) = 5.

Grouping by all your columns in your select is effectively the same as using DISTINCT, and it is preferable to use the DISTINCT keyword word readability in this case.

So instead of

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

use

SELECT DISTINCT Col1, Col2, Col3 FROM data

Configure DataSource programmatically in Spring Boot

You can use DataSourceBuilder if you are using jdbc starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

In my case I have properties starting with datasource.postgres prefix.

E.g

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .build();
}

If it is not feasible for you, then you can use

@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .username("")
        .password("")
        .url("")
        .driverClassName("")
        .build();
}

a page can have only one server-side form tag

I think you did like this:

<asp:Content ID="Content2" ContentPlaceHolderID="MasterContent" runat="server">
  <form id="form1" runat="server">

 </form>
</asp:Content>

The form tag isn't needed. because you already have the same tag in the master page.

So you just remove that and it should be working.

Ubuntu apt-get unable to fetch packages

ON MAC: Nothing was helping until I realised ScreenTime was blocking the update website! Turning off content filtering fix it

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

Is it possible to set a number to NaN or infinity?

Is it possible to set a number to NaN or infinity?

Yes, in fact there are several ways. A few work without any imports, while others require import, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).

The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float:

+-------------------------------------------------------------------+
¦   result ¦ NaN          ¦ Infinity           ¦ -Infinity          ¦
¦ module   ¦              ¦                    ¦                    ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf")       ¦ -float("inf")      ¦
¦          ¦              ¦ float("infinity")  ¦ -float("infinity") ¦
¦          ¦              ¦ float("+inf")      ¦ float("-inf")      ¦
¦          ¦              ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math     ¦ math.nan     ¦ math.inf           ¦ -math.inf          ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath    ¦ cmath.nan    ¦ cmath.inf          ¦ -cmath.inf         ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy    ¦ numpy.nan    ¦ numpy.PINF         ¦ numpy.NINF         ¦
¦          ¦ numpy.NaN    ¦ numpy.inf          ¦ -numpy.inf         ¦
¦          ¦ numpy.NAN    ¦ numpy.infty        ¦ -numpy.infty       ¦
¦          ¦              ¦ numpy.Inf          ¦ -numpy.Inf         ¦
¦          ¦              ¦ numpy.Infinity     ¦ -numpy.Infinity    ¦
+-------------------------------------------------------------------+

A couple remarks to the table:

  • The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy").
  • The cmath and numpy constants return plain Python float objects.
  • The numpy.NINF is actually the only constant I know of that doesn't require the -.
  • It is possible to create complex NaN and Infinity with complex and cmath:

    +------------------------------------------------------------------------------------------+
    ¦   result ¦ NaN+0j         ¦ 0+NaNj          ¦ Inf+0j              ¦ 0+Infj               ¦
    ¦ module   ¦                ¦                 ¦                     ¦                      ¦
    ¦----------+----------------+-----------------+---------------------+----------------------¦
    ¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf")      ¦ complex("infj")      ¦
    ¦          ¦                ¦                 ¦ complex("infinity") ¦ complex("infinityj") ¦
    +----------+----------------+-----------------+---------------------+----------------------¦
    ¦ cmath    ¦ cmath.nan ¹    ¦ cmath.nanj      ¦ cmath.inf ¹         ¦ cmath.infj           ¦
    +------------------------------------------------------------------------------------------+
    

    The options with ¹ return a plain float, not a complex.

is there any function to check whether a number is infinity or not?

Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import:

+--------------------------------------------------------------+
¦      for ¦ NaN         ¦ Infinity or    ¦ not NaN and        ¦
¦          ¦             ¦ -Infinity      ¦ not Infinity and   ¦
¦ module   ¦             ¦                ¦ not -Infinity      ¦
¦----------+-------------+----------------+--------------------¦
¦ math     ¦ math.isnan  ¦ math.isinf     ¦ math.isfinite      ¦
+----------+-------------+----------------+--------------------¦
¦ cmath    ¦ cmath.isnan ¦ cmath.isinf    ¦ cmath.isfinite     ¦
+----------+-------------+----------------+--------------------¦
¦ numpy    ¦ numpy.isnan ¦ numpy.isinf    ¦ numpy.isfinite     ¦
+--------------------------------------------------------------+

Again a couple of remarks:

  • The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.
  • The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.)
  • There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf.
  • Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT)
  • Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

To summarize the expected results for these functions (assuming the input is a float):

+----------------------------------------------------------------------+
¦          input ¦ NaN   ¦ Infinity   ¦ -Infinity   ¦ something else   ¦
¦ function       ¦       ¦            ¦             ¦                  ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan          ¦ True  ¦ False      ¦ False       ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf          ¦ False ¦ True       ¦ True        ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite       ¦ False ¦ False      ¦ False       ¦ True             ¦
+----------------------------------------------------------------------+

Is it possible to set an element of an array to NaN in Python?

In a list it's no problem, you can always include NaN (or Infinity) there:

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

However if you want to include it in an array (for example array.array or numpy.array) then the type of the array must be float or complex because otherwise it will try to downcast it to the arrays type!

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer

Accessing last x characters of a string in Bash

You can use tail:

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

A somewhat roundabout way to get the last three characters would be to say:

echo $foo | rev | cut -c1-3 | rev

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

Sending private messages to user

If your looking to type up the message and then your bot will send it to the user, here is the code. It also has a role restriction on it :)

_x000D_
_x000D_
case 'dm':
  mentiondm = message.mentions.users.first();
  message.channel.bulkDelete(1);
  if (!message.member.roles.cache.some(role => role.name === "Owner")) return message.channel.send('Beep Boing: This command is way too powerful for you to use!');
  if (mentiondm == null) return message.reply('Beep Boing: No user to send message to!');
  mentionMessage = message.content.slice(3);
  mentiondm.send(mentionMessage);
  console.log('Message Sent!')
  break;
_x000D_
_x000D_
_x000D_

Random / noise functions for GLSL

Please see below an example how to add white noise to the rendered texture. The solution is to use two textures: original and pure white noise, like this one: wiki white noise

private static final String VERTEX_SHADER =
    "uniform mat4 uMVPMatrix;\n" +
    "uniform mat4 uMVMatrix;\n" +
    "uniform mat4 uSTMatrix;\n" +
    "attribute vec4 aPosition;\n" +
    "attribute vec4 aTextureCoord;\n" +
    "varying vec2 vTextureCoord;\n" +
    "varying vec4 vInCamPosition;\n" +
    "void main() {\n" +
    "    vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
    "    gl_Position = uMVPMatrix * aPosition;\n" +
    "}\n";

private static final String FRAGMENT_SHADER =
        "precision mediump float;\n" +
        "uniform sampler2D sTextureUnit;\n" +
        "uniform sampler2D sNoiseTextureUnit;\n" +
        "uniform float uNoseFactor;\n" +
        "varying vec2 vTextureCoord;\n" +
        "varying vec4 vInCamPosition;\n" +
        "void main() {\n" +
                "    gl_FragColor = texture2D(sTextureUnit, vTextureCoord);\n" +
                "    vec4 vRandChosenColor = texture2D(sNoiseTextureUnit, fract(vTextureCoord + uNoseFactor));\n" +
                "    gl_FragColor.r += (0.05 * vRandChosenColor.r);\n" +
                "    gl_FragColor.g += (0.05 * vRandChosenColor.g);\n" +
                "    gl_FragColor.b += (0.05 * vRandChosenColor.b);\n" +
        "}\n";

The fragment shared contains parameter uNoiseFactor which is updated on every rendering by main application:

float noiseValue = (float)(mRand.nextInt() % 1000)/1000;
int noiseFactorUniformHandle = GLES20.glGetUniformLocation( mProgram, "sNoiseTextureUnit");
GLES20.glUniform1f(noiseFactorUniformHandle, noiseFactor);

Way to create multiline comments in Bash?

Here's how I do multiline comments in bash.

This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.

Running that example will produce this output:

foo {
./example: line 5: fn: command not found
foo }
can't happen

When should I use cross apply over inner join?

Cross apply works well with an XML field as well. If you wish to select node values in combination with other fields.

For example, if you have a table containing some xml

<root>
    <subnode1>
       <some_node value="1" />
       <some_node value="2" />
       <some_node value="3" />
       <some_node value="4" />
    </subnode1>
</root>

Using the query

SELECT
       id as [xt_id]
      ,xmlfield.value('(/root/@attribute)[1]', 'varchar(50)') root_attribute_value
  ,node_attribute_value = [some_node].value('@value', 'int')
  ,lt.lt_name   
FROM dbo.table_with_xml xt
CROSS APPLY xmlfield.nodes('/root/subnode1/some_node') as g ([some_node])
LEFT OUTER JOIN dbo.lookup_table lt
ON [some_node].value('@value', 'int') = lt.lt_id

Will return a result

xt_id root_attribute_value node_attribute_value lt_name
----------------------------------------------------------------------
1     test1            1                    Benefits
1     test1            4                    FINRPTCOMPANY

CSS table layout: why does table-row not accept a margin?

There is a pretty simple fix for this, the border-spacing and border-collapse CSS attributes work on display: table.

You can use the following to get padding/margins in your cells.

_x000D_
_x000D_
.container {_x000D_
  width: 850px;_x000D_
  padding: 0;_x000D_
  display: table;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 15px;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.home_1 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_2 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_3 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_4 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
    <div class="home_3">Foo</div>_x000D_
    <div class="home_4">Foo</div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you have to have

border-collapse: separate;

Otherwise it will not work.

Regex to remove all special characters from string?

For my purposes I wanted all English ASCII chars, so this worked.

html = Regex.Replace(html, "[^\x00-\x80]+", "")

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

What is token-based authentication?

I think it's well explained here -- quoting just the key sentences of the long article:

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

In other words: add one level of indirection for authentication -- instead of having to authenticate with username and password for each protected resource, the user authenticates that way once (within a session of limited duration), obtains a time-limited token in return, and uses that token for further authentication during the session.

Advantages are many -- e.g., the user could pass the token, once they've obtained it, on to some other automated system which they're willing to trust for a limited time and a limited set of resources, but would not be willing to trust with their username and password (i.e., with every resource they're allowed to access, forevermore or at least until they change their password).

If anything is still unclear, please edit your question to clarify WHAT isn't 100% clear to you, and I'm sure we can help you further.

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

How to disable margin-collapsing?

In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root. However, you would still need other techniques to prevent adjacent element collapsing.

DEMO (before)

_x000D_
_x000D_
.parent {_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DEMO (after)

_x000D_
_x000D_
.parent {_x000D_
  display: flow-root;_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to read and write INI file with Python3?

contents in my backup_settings.ini file

[Settings]
year = 2020

python code for reading

import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year") 
print(year)

for writing or updating

from pathlib import Path
import configparser
myfile = Path('backup_settings.ini')  #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry 
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))

output

[Settings]
year = 2050
day = sunday

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

What is a practical use for a closure in JavaScript?

If you're comfortable with the concept of instantiating a class in the object-oriented sense (i.e. to create an object of that class) then you're close to understanding closures.

Think of it this way: when you instantiate two Person objects you know that the class member variable "Name" is not shared between instances; each object has its own 'copy'. Similarly, when you create a closure, the free variable ('calledCount' in your example above) is bound to the 'instance' of the function.

I think your conceptual leap is slightly hampered by the fact that every function/closure returned by the warnUser function (aside: that's a higher-order function) closure binds 'calledCount' with the same initial value (0), whereas often when creating closures it is more useful to pass different initializers into the higher-order function, much like passing different values to the constructor of a class.

So, suppose when 'calledCount' reaches a certain value you want to end the user's session; you might want different values for that depending on whether the request comes in from the local network or the big bad internet (yes, it's a contrived example). To achieve this, you could pass different initial values for calledCount into warnUser (i.e. -3, or 0?).

Part of the problem with the literature is the nomenclature used to describe them ("lexical scope", "free variables"). Don't let it fool you, closures are more simple than would appear... prima facie ;-)

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

List of lists into numpy array

It's as simple as:

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

Detecting an undefined object property

Crossposting my answer from related question How can I check for "undefined" in JavaScript?.

Specific to this question, see test cases with someObject.<whatever>.


Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

A top-like utility for monitoring CUDA activity on a GPU

Just use watch nvidia-smi, it will output the message by 2s interval in default.

For example, as the below image:

enter image description here

You can also use watch -n 5 nvidia-smi (-n 5 by 5s interval).

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

How to return the current timestamp with Moment.js?

If you just want the milliseconds since 01-JAN-1970, then you can use

var theMoment = moment(); // or whatever your moment instance is
var millis;

millis = +theMoment; // a short but not very readable form
// or
millis = theMoment.valueOf();
// or (almost sure not as efficient as above)
millis = theMoment.toDate().getTime();

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

How to SSH into Docker?

It is a short way but not permanent

first create a container

docker run  ..... -p 22022:2222 .....

port 22022 on your host machine will map on 2222, we change the ssh port on container later , then on your container executing the following commands

apt update && apt install  openssh-server # install ssh server
passwd #change root password

in file /etc/ssh/sshd_config change these : uncomment Port and change it to 2222

Port 2222

uncomment PermitRootLogin to

PermitRootLogin yes

and finally restart ssh server

/etc/init.d/ssh start

you can login to your container now

ssh -p 2022 root@HostIP

Remember : if you restart the container you need to restart ssh server again

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Linking a UNC / Network drive on an html page

Alternative (Insert tooltip to user):

<style>
    a.tooltips {
        position: relative;
        display: inline;
    }
    a.tooltips span {
        position: absolute;
        width: 240px;
        color: #FFFFFF;
        background: #000000;
        height: 30px;
        line-height: 30px;
        text-align: center;
        visibility: hidden;
        border-radius: 6px;
    }
    a.tooltips span:after {
        content: '';
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -8px;
        width: 0;
        height: 0;
        border-top: 8px solid #000000;
        border-right: 8px solid transparent;
        border-left: 8px solid transparent;
    }
    a:hover.tooltips span {
        visibility: visible;
        opacity: 0.8;
        bottom: 30px;
        left: 50%;
        margin-left: -76px;
        z-index: 999;
    }
</style>
<a class="tooltips" href="#">\\server\share\docs<span>Copy link and open in Explorer</span></a>

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

Spring schemaLocation fails when there is no internet connection

If you are using eclipse for your development , it helps if you install STS plugin for Eclipse [ from the marketPlace for the specific version of eclipse .

Now When you try to create a new configuration file in a folder(normally resources) inside the project , the options would have a "Spring Folder" and you can choose a "Spring Bean Definition File " option Spring > Spring Bean Configuation File .

With this option selected , when you follow steps , it asks you to select for namespaces and the specific versions :

And so the possibility of having a non-existent jar Or old version can be eliminated .

Would have posted images as well , but my reputation is pretty low.. :(

Copy values from one column to another in the same table

Following worked for me..

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

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

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

Good Luck!

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

PostgreSQL: Show tables in PostgreSQL

From the psql command line interface,

First, choose your database

\c database_name

Then, this shows all tables in the current schema:

\dt

Programmatically (or from the psql interface too, of course):

SELECT * FROM pg_catalog.pg_tables;

The system tables live in the pg_catalog database.

Start ssh-agent on login

Old question, but I did come across a similar situation. Don't think the above answer fully achieves what is needed. The missing piece is keychain; install it if it isn't already.

sudo apt-get install keychain

Then add the following line to your ~/.bashrc

eval $(keychain --eval id_rsa)

This will start the ssh-agent if it isn't running, connect to it if it is, load the ssh-agent environment variables into your shell, and load your ssh key.

Change id_rsa to whichever private key in ~/.ssh you want to load.

Some useful options for keychain:

  • -q Quiet mode
  • --noask Don't ask for the password upon start, but on demand when ssh key is actually used.

Reference

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

In my case, when I run df -i it shows me that my number of inodes are full and then I have to delete some of the small files or folder. Otherwise it will not allow us to create files or folders once inodes get full.

All you have to do is delete files or folder that has not taken up full space but is responsible for filling inodes.

How do I make a splash screen?

In Kotlin write this code:-

 Handler().postDelayed({
            val mainIntent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(mainIntent)
            finish()
        }, 500)

Hope this will help you.Thanks........

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me on a mm/dd/yyyy format:

=DATE(VALUE(RIGHT(A1,4)),VALUE(LEFT(A1,2)),VALUE(MID(A1,4,2)))

Convert the cell with the formula to date format and drag the formula down.

Center Oversized Image in Div

The width and height are only for example:

parentDiv{
    width: 100px;
    height: 100px;
    position:relative; 
}
innerDiv{
    width: 200px;
    height: 200px;
    position:absolute; 
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

jQuery autohide element after 5 seconds

$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

How are cookies passed in the HTTP protocol?

Apart from what it's written in other answers, other details related to path of cookie, maximum age of cookie, whether it's secured or not also passed in Set-Cookie response header. For instance:

Set-Cookie:name=value[; expires=date][; domain=domain][; path=path][; secure]


However, not all of these details are passed back to the server by the client when making next HTTP request.

You can also set HttpOnly flag at the end of your cookie, to indicate that your cookie is httponly and must not allowed to be accessed, in scripts by javascript code. This helps to prevent attacks such as session-hijacking.

For more information, see RFC 2109. Also have a look at Nicholas C. Zakas's article, HTTP cookies explained.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

How to insert image in mysql database(table)?

I tried all above solution and fail, it just added a null file to the DB.

However, I was able to get it done by moving the image(fileName.jpg) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads and then I executed below command and it works for me,

INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));

Hope this helps.

Way to get number of digits in an int?

Using Java

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

use import java.lang.Math.*; in the beginning

Using C

int nDigits = floor(log10(abs(the_integer))) + 1;

use inclue math.h in the beginning

Running AMP (apache mysql php) on Android

I think this is what you're looking for: PAW Server from http://paw-android.fun2code.de/

hope it works

Batch Extract path and filename from a variable

All of this works for me:

@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul

Output:

Directory = D:\Users\Thejordster135\Desktop\Code\BAT\

Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"

Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat

Bat File Drive = D:

Full File Name = Path.bat

File Name Without Extension = Path

File Extension = .bat

What is a plain English explanation of "Big O" notation?

From (source) one can read:

Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. (..) In computer science, big O notation is used to classify algorithms according to how their run time or space requirements grow as the input size grows.

Big O notation does not represent a function per si but rather a set of functions with a certain asymptotic upper-bound; as one can read from source:

Big O notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation.

Informally, in computer-science time-complexity and space-complexity theories, one can think of the Big O notation as a categorization of algorithms with a certain worst-case scenario concerning time and space, respectively. For instance, O(n):

An algorithm is said to take linear time/space, or O(n) time/space, if its time/space complexity is O(n). Informally, this means that the running time/space increases at most linearly with the size of the input (source).

and O(n log n) as:

An algorithm is said to run in quasilinear time/space if T(n) = O(n log^k n) for some positive constant k; linearithmic time/space is the case k = 1 (source).

Nonetheless, typically such relaxed phrasing is normally used to quantify (for the worst-case scenario) how a set of algorithms behaves compared with another set of algorithms regarding the increase of their input sizes. To compare two classes of algorithms (e.g., O(n log n) and O(n)) one should analyze how both classes of algorithms behaves with the increase of their input size (i.e., n) for the worse-case scenario; analyzing n when it tends to the infinity

enter image description here

In the image above big-O denote one of the asymptotically least upper-bounds of the plotted functions, and does not refer to the sets O(f(n)).

For instance comparing O(n log n) vs. O(n) as one can see in the image after a certain input, O(n log n) (green line) grows faster than O(n) (yellow line). That is why (for the worst-case) O(n) is more desirable than O(n log n) because one can increase the input size, and the growth rate will increase slower with the former than with the latter.

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

Difference between a User and a Login in SQL Server

I think there is a really good MSDN blog post about this topic by Laurentiu Cristofor:

The first important thing that needs to be understood about SQL Server security is that there are two security realms involved - the server and the database. The server realm encompasses multiple database realms. All work is done in the context of some database, but to get to do the work, one needs to first have access to the server and then to have access to the database.

Access to the server is granted via logins. There are two main categories of logins: SQL Server authenticated logins and Windows authenticated logins. I will usually refer to these using the shorter names of SQL logins and Windows logins. Windows authenticated logins can either be logins mapped to Windows users or logins mapped to Windows groups. So, to be able to connect to the server, one must have access via one of these types or logins - logins provide access to the server realm.

But logins are not enough, because work is usually done in a database and databases are separate realms. Access to databases is granted via users.

Users are mapped to logins and the mapping is expressed by the SID property of logins and users. A login maps to a user in a database if their SID values are identical. Depending on the type of login, we can therefore have a categorization of users that mimics the above categorization for logins; so, we have SQL users and Windows users and the latter category consists of users mapped to Windows user logins and of users mapped to Windows group logins.

Let's take a step back for a quick overview: a login provides access to the server and to further get access to a database, a user mapped to the login must exist in the database.

that's the link to the full post.

Removing viewcontrollers from navigation stack

Use this code and enjoy:

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

// [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.
[navigationArray removeObjectAtIndex: 2];  // You can pass your index here
self.navigationController.viewControllers = navigationArray;
[navigationArray release];

Hope this will help you.

Edit: Swift Code

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray

Edit: To remove all ViewController except last one -> no Back Button in the upper left corner

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
let temp = navigationArray.last
navigationArray.removeAll()
navigationArray.append(temp!) //To remove all previous UIViewController except the last one
self.navigationController?.viewControllers = navigationArray

Apache 13 permission denied in user's home directory

Can't you set the Loglevel in httpd.conf to debug? (I'm using FreeBSD)

ee usr/local/etc/apache22/httpd.conf

change loglevel :

'LogLevel: Control the number of messages logged to the error_log. Possible values include: debug, info, notice, warn, error, crit, alert, emerg.'

Try changing to debug and re-checking the error log after that.

serialize/deserialize java 8 java.time with Jackson JSON mapper

For those who use Spring Boot 2.x

There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.

See this reference too JSON Java 8 LocalDateTime format in Spring Boot

How to print to the console in Android Studio?

Android has its own method of printing messages (called logs) to the console, known as the LogCat.

When you want to print something to the LogCat, you use a Log object, and specify the category of message.

The main options are:

  • DEBUG: Log.d
  • ERROR: Log.e
  • INFO: Log.i
  • VERBOSE: Log.v
  • WARN: Log.w

You print a message by using a Log statement in your code, like the following example:

Log.d("myTag", "This is my message");

Within Android Studio, you can search for log messages labelled myTag to easily find the message in the LogCat. You can also choose to filter logs by category, such as "Debug" or "Warn".

Text overflow ellipsis on two lines

Use this if above is not working

 display: -webkit-box;
 max-width: 100%;
 margin: 0 auto;
 -webkit-line-clamp: 2;
 /* autoprefixer: off */
 -webkit-box-orient: vertical;
 /* autoprefixer: on */
 overflow: hidden;
 text-overflow: ellipsis;

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

What's the best way of scraping data from a website?

You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.

Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.

Tools

Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.

You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.

Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.

Language

PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.

A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.

Javascript-heavy sites

In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.

There are two approaches to this problem:

The low level approach:

You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.

The embedded browser approach:

Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.

If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.

You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.

Which approach is best?

That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.

The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.

Rate Limiting/Bot behaviour

You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.

Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.

You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.

Testing

Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.

There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.

The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.

You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.

Legal Issues

The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.

The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.

It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.

Who am I to write this giant wall of text anyway?

I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.

I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)

I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.

I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.

Non-Static method cannot be referenced from a static context with methods and variables

You need to make both your method - printMenu() and getUserChoice() static, as you are directly invoking them from your static main method, without creating an instance of the class, those methods are defined in. And you cannot invoke a non-static method without any reference to an instance of the class they are defined in.

Alternatively you can change the method invocation part to:

BookStoreApp2 bookStoreApp = new BookStoreApp2();
bookStoreApp.printMenu();
bookStoreApp.getUserChoice();

How can I change CSS display none or block property using jQuery?

For hide:

$("#id").css("display", "none");

For show:

$("#id").css("display", "");

Android: Align button to bottom-right of screen using FrameLayout?

It can be achieved using RelativeLayout

<RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

   <ImageView 
      android:src="@drawable/icon"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_alignParentRight="true"
      android:layout_alignParentBottom="true" />

</RelativeLayout>

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

How to find out if an installed Eclipse is 32 or 64 bit version?

In Linux, run file on the Eclipse executable, like this:

$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped

Comment shortcut Android Studio

In Android studio CTRL + SHIFT + / for windows.

How can I temporarily disable a foreign key constraint in MySQL?

I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;

Timeout jQuery effects

I just figured it out below:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

I will keep the post for other users!

Kubernetes how to make Deployment to update image

kubectl rollout restart deployment myapp

This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout like rollbacks.

How can I determine if an image has loaded, using Javascript/jQuery?

Using the jquery data store you can define a 'loaded' state.

<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />

Then elsewhere you can do:

if ($('#myimage').data('loaded')) {
    // loaded, so do stuff
}

How do I delete multiple rows with different IDs?

If you have to select the id:

 DELETE FROM table WHERE id IN (SELECT id FROM somewhere_else)

If you already know them (and they are not in the thousands):

 DELETE FROM table WHERE id IN (?,?,?,?,?,?,?,?)

Animate background image change with jQuery

$('.clickable').hover(function(){
      $('.selector').stop(true,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic2.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
},
function(){
      $('.selector').stop(false,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
}

);

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Reactjs: Unexpected token '<' Error

The issue Unexpected token '<' is because of missing the babel preset.

Solution : You have to configure your webpack configuration as follows

{
  test   : /\.jsx?$/,
  exclude: /(node_modules|bower_components)/,
  loader : 'babel',
  query  : {
    presets:[ 'react', 'es2015' ]
  }
}

here .jsx checks both .js and .jsx formats.

you can simply install the babel dependency using node as follows

npm install babel-preset-react

Thank you

posting hidden value

You should never assume register_global_variables is turned on. Even if it is, it's deprecated and you should never use it that way.

Refer directly to the $_POST or $_GET variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:

<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />

If this doesn't work for you right away, print out the $_POST or $_GET variable on the page that would have the hidden form field and determine exactly what you want and refer to it.

echo "<pre>";
print_r($_POST);
echo "</pre>";

Convert UTF-8 to base64 string

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

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

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

Edit:

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

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

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

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

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

How to maintain state after a page refresh in React.js?

Load state from localStorage if exist:

constructor(props) {
    super(props);           
    this.state = JSON.parse(localStorage.getItem('state'))
        ? JSON.parse(localStorage.getItem('state'))
        : initialState

override this.setState to automatically save state after each update :

const orginial = this.setState;     
this.setState = function() {
    let arguments0 = arguments[0];
    let arguments1 = () => (arguments[1], localStorage.setItem('state', JSON.stringify(this.state)));
    orginial.bind(this)(arguments0, arguments1);
};

How to calculate the SVG Path for an arc (of a circle)

You want to use the elliptical Arc command. Unfortunately for you, this requires you to specify the Cartesian coordinates (x, y) of the start and end points rather than the polar coordinates (radius, angle) that you have, so you have to do some math. Here's a JavaScript function which should work (though I haven't tested it), and which I hope is fairly self-explanatory:

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = angleInDegrees * Math.PI / 180.0;
  var x = centerX + radius * Math.cos(angleInRadians);
  var y = centerY + radius * Math.sin(angleInRadians);
  return [x,y];
}

Which angles correspond to which clock positions will depend on the coordinate system; just swap and/or negate the sin/cos terms as necessary.

The arc command has these parameters:

rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y

For your first example:

rx=ry=25 and x-axis-rotation=0, since you want a circle and not an ellipse. You can compute both the starting coordinates (which you should Move to) and ending coordinates (x, y) using the function above, yielding (200, 175) and about (182.322, 217.678), respectively. Given these constraints so far, there are actually four arcs that could be drawn, so the two flags select one of them. I'm guessing you probably want to draw a small arc (meaning large-arc-flag=0), in the direction of decreasing angle (meaning sweep-flag=0). All together, the SVG path is:

M 200 175 A 25 25 0 0 0 182.322 217.678

For the second example (assuming you mean going the same direction, and thus a large arc), the SVG path is:

M 200 175 A 25 25 0 1 0 217.678 217.678

Again, I haven't tested these.

(edit 2016-06-01) If, like @clocksmith, you're wondering why they chose this API, have a look at the implementation notes. They describe two possible arc parameterizations, "endpoint parameterization" (the one they chose), and "center parameterization" (which is like what the question uses). In the description of "endpoint parameterization" they say:

One of the advantages of endpoint parameterization is that it permits a consistent path syntax in which all path commands end in the coordinates of the new "current point".

So basically it's a side-effect of arcs being considered as part of a larger path rather than their own separate object. I suppose that if your SVG renderer is incomplete it could just skip over any path components it doesn't know how to render, as long as it knows how many arguments they take. Or maybe it enables parallel rendering of different chunks of a path with many components. Or maybe they did it to make sure rounding errors didn't build up along the length of a complex path.

The implementation notes are also useful for the original question, since they have more mathematical pseudocode for converting between the two parameterizations (which I didn't realize when I first wrote this answer).

Sending Email in Android using JavaMail API without using the default/built-in app

I tried using the code that @Vinayak B submitted. However I'm getting an error saying: No provider for smtp

I created a new question for this with more information HERE

I was able to fix it myself after all. I had to use an other mail.jar and I had to make sure my "access for less secure apps" was turned on.

I hope this helps anyone who has the same problem. With this done, this piece of code works on the google glass too.

How do I reference a cell range from one worksheet to another using excel formulas?

I rewrote the code provided by Ninja2k because I didn't like that it looped through cells. For future reference here's a version using arrays instead which works noticeably faster over lots of ranges but has the same result:

Function concat2(useThis As Range, Optional delim As String) As String
    Dim tempValues
    Dim tempString
    Dim numValues As Long
    Dim i As Long, j As Long
    tempValues = useThis
    numValues = UBound(tempValues) * UBound(tempValues, 2)
    ReDim values(1 To numValues)
    For i = UBound(tempValues) To LBound(tempValues) Step -1
        For j = UBound(tempValues, 2) To LBound(tempValues, 2) Step -1
            values(numValues) = tempValues(i, j)
            numValues = numValues - 1
        Next j
    Next i
    concat2 = Join(values, delim)
End Function

I can't help but think there's definitely a better way...

Here are steps to do it manually without VBA which only works with 1d arrays and makes static values instead of retaining the references:

  1. Update cell formula to something like =Sheet2!A1:A15
  2. Hit F9
  3. Remove the curly braces { and }
  4. Place CONCATENATE( at the front of the formula after the = sign and ) at the end of the formula.
  5. Hit enter.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package