Programs & Examples On #Yfrog

Extract filename and extension in Bash

You can use the magic of POSIX parameter expansion:

bash-3.2$ FILENAME=somefile.tar.gz
bash-3.2$ echo "${FILENAME%%.*}"
bash-3.2$ echo "${FILENAME%.*}"

There's a caveat in that if your filename was of the form ./somefile.tar.gz then echo ${FILENAME%%.*} would greedily remove the longest match to the . and you'd have the empty string.

(You can work around that with a temporary variable:

echo ${FILENAME%%.*}


This site explains more.

  Trim the shortest match from the end
  Trim the longest match from the beginning
  Trim the longest match from the end
  Trim the shortest match from the beginning

Include another JSP file

At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.

Syntax for include a jsp file:

<%@ include file="relative url">


<%@include file="page_name.jsp" %>

Change EditText hint color when using TextInputLayout

Refer the below code it worked for me.But it will affect all your controls color.

 <!-- In your style.xml file -->
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
            <!--EditText hint color-->
            <item name="android:textColorHint">@color/default_app_white</item>
           <!-- TextInputLayout text color-->
            <item name="colorControlActivated">@color/default_app_green</item>
            <!-- EditText line color when EditText on-focus-->
            <item name="colorControlHighlight">@color/default_app_green</item>
            <!-- EditText line color when EditText  in un-focus-->
            <item name="colorControlNormal">@color/default_app_white</item>

What's the quickest way to multiply multiple cells by another number?

Select Product from formula bar in your answer cell.

Select cells you want to multiply.

How to set my default shell on Mac?

The only thing that worked for me was a combination of all these methods.

  1. First I had to add fish to the /etc/shells file

  2. Then I ran chsh -s /usr/local/bin/fish

  3. Finally, I typed Command+, and added /usr/local/bin/fish to the default path there

Only after I had done all three things did fish start popping up as the default for new terminal windows.

Key value pairs using JSON

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:


Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.


here's the gist of the demo


  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;



<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,

enter image description here

Java ArrayList - Check if list is empty

Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.


Groovy Shell warning "Could not open/create prefs root node ..."

If anyone is trying to solve this on a 64-bit version of Windows, you might need to create the following key:


What are the differences between the BLOB and TEXT datatypes in MySQL?

A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field

L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.


Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]

<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

installing vmware tools: location of GCC binary?

First execute this

sudo apt-get install gcc binutils make linux-source

Then run again


This is all you need to do. Now your system has the gcc make and the linux kernel sources.

Docker - Cannot remove dead container

Tried all of the above (short of reboot/ restart docker).

So here is the error om docker rm:

$ docker rm 08d51aad0e74
Error response from daemon: driver "devicemapper" failed to remove root filesystem for 08d51aad0e74060f54bba36268386fe991eff74570e7ee29b7c4d74047d809aa: remove /var/lib/docker/devicemapper/mnt/670cdbd30a3627ae4801044d32a423284b540c5057002dd010186c69b6cc7eea: device or resource busy

Then I did a the following:

$  grep docker /proc/*/mountinfo | grep 958722d105f8586978361409c9d70aff17c0af3a1970cb3c2fb7908fe5a310ac
/proc/20416/mountinfo:629 574 253:15 / /var/lib/docker/devicemapper/mnt/958722d105f8586978361409c9d70aff17c0af3a1970cb3c2fb7908fe5a310ac rw,relatime shared:288 - xfs /dev/mapper/docker-253:5-786536-958722d105f8586978361409c9d70aff17c0af3a1970cb3c2fb7908fe5a310ac rw,nouuid,attr2,inode64,logbsize=64k,sunit=128,swidth=128,noquota

This got be the PID of the offending process keeping it busy - 20416 (the item after /proc/

So I did a ps -p and to my surprise find:

[devops@dp01app5030 SeGrid]$ ps -p 20416
  PID TTY          TIME CMD
20416 ?        00:00:19 ntpd

A true WTF moment. So I pair problem solved with Google and found this: Then found this

Turns out I had to restart ntp daemon and that fixed the issue!!!

How to format DateTime in Flutter , How to get current time in flutter?

there is some change since the 0.16 so here how i did,

import in the pubspec.yaml

        sdk: flutter
      intl: ^0.16.1

then use



How to Resize image in Swift?

For Swift 4.0 and iOS 10

    extension UIImage {
        func resizeImage(_ dimension: CGFloat, opaque: Bool, contentMode: UIViewContentMode = .scaleAspectFit) -> UIImage {
            var width: CGFloat
            var height: CGFloat
            var newImage: UIImage

            let size = self.size
            let aspectRatio =  size.width/size.height

            switch contentMode {
                case .scaleAspectFit:
                    if aspectRatio > 1 {                            // Landscape image
                        width = dimension
                        height = dimension / aspectRatio
                    } else {                                        // Portrait image
                        height = dimension
                        width = dimension * aspectRatio

                fatalError("UIIMage.resizeToFit(): FATAL: Unimplemented ContentMode")

            if #available(iOS 10.0, *) {
                let renderFormat = UIGraphicsImageRendererFormat.default()
                renderFormat.opaque = opaque
                let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
                newImage = renderer.image {
                    (context) in
                    self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
            } else {
                UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
                    self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
                    newImage = UIGraphicsGetImageFromCurrentImageContext()!

            return newImage

using setTimeout on promise chain

To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.

Instead, you can make a simple little delay function like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)

And, then use it like this:

    let all_links = (JSON.parse(links));

    return getLinks(globalObj["one"]+".txt");

    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");

Here you're returning a promise from the .then() handler and thus it is chained appropriately.

You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:

function delay(t, v) {_x000D_
   return new Promise(function(resolve) { _x000D_
       setTimeout(resolve.bind(null, v), t)_x000D_
Promise.prototype.delay = function(t) {_x000D_
    return this.then(function(v) {_x000D_
        return delay(t, v);_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_

Or, use the Bluebird promise library which already has the .delay() method built-in.

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

How to edit .csproj file

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

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

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

Add Foreign Key to existing table

this is basically happens because your tables are in two different charsets. as a example one table created in charset=utf-8 and other tables is created in CHARSET=latin1 so you want be able add foriegn key to these tables. use same charset in both tables then you will be able to add foriegn keys. error 1005 foriegn key constraint incorrectly formed can resolve from this

Stylesheet not loaded because of MIME-type

For a Node.js application, just use this after importing all the required modules in your server file:

  • express.static built-in middleware function in Express and this in your .html file: <link rel="stylesheet" href="style.css">

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );



With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

Find the files that have been changed in last 24 hours

Another, more humane way:

find /<directory> -newermt "-24 hours" -ls


find /<directory> -newermt "1 day ago" -ls


find /<directory> -newermt "yesterday" -ls

How can I change property names when serializing with

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

How to convert FormData (HTML5 object) to JSON

You can try this


# Create a function to convert the serialize and convert the form data
# to JSON
# @param : $('#form_example');
# @return a JSON Stringify
function formDataToJSON(form) {
    let obj = {};
    let formData = form.serialize();
    let formArray = formData.split("&");

    for (inputData of formArray){
        let dataTmp = inputData.split('=');
        obj[dataTmp[0]] = dataTmp[1];
    return JSON.stringify(obj);

Intercept a form submit in JavaScript and prevent normal submission

Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests. These code should be added in the top of body element to create listener before any form rendered and submitted.

In example I set hidden field to any form on page on its submission even if it happens before page load.

//Handles jquery, dojo, etc. ajax requests
(function (send) {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    XMLHttpRequest.prototype.send = function (data) {
        if (isNotEmptyString(token) && isNotEmptyString(header)) {
            this.setRequestHeader(header, token);
        }, data);

//Handles javascript submit
(function (submit) {
    HTMLFormElement.prototype.submit = function (data) {
        var token = $("meta[name='_csrf']").attr("content");
        var paramName = $("meta[name='_csrf_parameterName']").attr("content");
            type: 'hidden',
            name: paramName,
            value: token
        }).appendTo(this);, data);

//Handles html submit
document.body.addEventListener('submit', function (event) {
    var token = $("meta[name='_csrf']").attr("content");
    var paramName = $("meta[name='_csrf_parameterName']").attr("content");
        type: 'hidden',
        name: paramName,
        value: token
}, false);

Javascript search inside a JSON object

If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOf or a regular expression to test the strings.

For the loop, you have at least three choices:

  1. A boring old for loop.

  2. On ES5-enabled environments (or with a shim), Array#filter.

  3. Because you're using jQuery,

Boring old for loop example:

function search(source, name) {
    var results = [];
    var index;
    var entry;

    name = name.toUpperCase();
    for (index = 0; index < source.length; ++index) {
        entry = source[index];
        if (entry && && !== -1) {

    return results;

Where you'd call that with obj.list as source and the desired name fragment as name.

Or if there's any chance there are blank entries or entries without names, change the if to:

        if (entry && && !== -1) {

Array#filter example:

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = source.filter(function(entry) {
        return !== -1;
    return results;

And again, if any chance that there are blank entries (e.g., undefined, as opposed to missing; filter will skip missing entries), change the inner return to:

        return entry && && !== -1; example (here I'm assuming jQuery = $ as is usually the case; change $ to jQuery if you're using noConflict):

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = $.map(source, function(entry) {
        var match = !== -1;
        return match ? entry : null;
    return results;

(And again, add entry && && in there if necessary.)

What's the algorithm to calculate aspect ratio?

Here is a version of James Farey's best rational approximation algorithm with adjustable level of fuzziness ported to javascript from the aspect ratio calculation code originally written in python.

The method takes a float (width/height) and an upper limit for the fraction numerator/denominator.

In the example below I am setting an upper limit of 50 because I need 1035x582 (1.77835051546) to be treated as 16:9 (1.77777777778) rather than 345:194 which you get with the plain gcd algorithm listed in other answers.

<script type="text/javascript">
function aspect_ratio(val, lim) {

    var lower = [0, 1];
    var upper = [1, 0];

    while (true) {
        var mediant = [lower[0] + upper[0], lower[1] + upper[1]];

        if (val * mediant[1] > mediant[0]) {
            if (lim < mediant[1]) {
                return upper;
            lower = mediant;
        } else if (val * mediant[1] == mediant[0]) {
            if (lim >= mediant[1]) {
                return mediant;
            if (lower[1] < upper[1]) {
                return lower;
            return upper;
        } else {
            if (lim < mediant[1]) {
                return lower;
            upper = mediant;

document.write (aspect_ratio(800 / 600, 50) +"<br/>");
document.write (aspect_ratio(1035 / 582, 50) + "<br/>");
document.write (aspect_ratio(2560 / 1440, 50) + "<br/>");


The result:

 4,3  // (1.33333333333) (800 x 600)
 16,9 // (1.77777777778) (2560.0 x 1440)
 16,9 // (1.77835051546) (1035.0 x 582)

How to use JavaScript variables in jQuery selectors?

  1. ES6 String Template

    Here is a simple way if you don't need IE/EDGE support




    This is a es6 feature called template string

        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                var x = $(this).attr("name");_x000D_
                $(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
        <script src=""></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_

  1. String Concatenation

    If you need IE/EDGE support use

    $("#" + $(this).attr("name")).hide();

        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                $("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
        <script src=""></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_

  1. Selector in DOM as data attribute

    This is my preferred way as it makes you code really DRY

    // HTML
    <input type="text"   id="bx" />
    <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>

        (function($) {_x000D_
            $(".js-hide-onclick").click(function() {_x000D_
                $($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
        <script src=""></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

How to delay the .keyup() handler until the user stops typing?

Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:

function makeDelay(ms) {
    var timer = 0;
    return function(callback){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);

If you want to reuse the same delay, just do

var delay = makeDelay(250);
$(selector1).on('keyup', function() {delay(someCallback);});
$(selector2).on('keyup', function() {delay(someCallback);});

If you want separate delays, you can do

$(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
$(selector2).on('keyup', function() {makeDelay(250)(someCallback);});

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

public ActionResult SubmitAction(FormCollection collection)
     // Get Post Params Here
 string var1 = collection["var1"];

You can also use a class, that is mapped with Form values, and mvc engine automagically fills it:

//Defined in another file
class MyForm
  public string var1 { get; set; }

public ActionResult SubmitAction(MyForm form)
  string var1 = form1.Var1;

Dynamic instantiation from string name of a class in dynamically imported module?

Copy-paste snippet:

import importlib
def str_to_class(module_name, class_name):
    """Return a class instance from a string reference"""
        module_ = importlib.import_module(module_name)
            class_ = getattr(module_, class_name)()
        except AttributeError:
            logging.error('Class does not exist')
    except ImportError:
        logging.error('Module does not exist')
    return class_ or None

Efficiently sorting a numpy array in descending order?

>>> a=np.array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

>>> np.sort(a)
array([2, 2, 4, 4, 4, 4, 5, 6, 7, 8])

>>> -np.sort(-a)
array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

Change the mouse pointer using JavaScript

Look at this page: Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well. = 'wait';

How to get key names from JSON using jq

In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:

     cat input.json | jq -r 'keys'

From jq help:

     -r     output raw strings, not JSON texts;

Apply formula to the entire column

This worked for me.

  • Write the formula in the first cell.
  • Click Enter.
  • Click on the first cell and press Ctrl + Shift + down_arrow. This will select the last cell in the column used on the worksheet.
  • Ctrl + D. This will fill copy the formula in the remaining cells.

Log all requests from the python-requests module

Just improving this answer

This is how it worked for me:

import logging
import sys    
import requests
import textwrap
root = logging.getLogger('httplogger')

def logRoundtrip(response, *args, **kwargs):
    extra = {'req': response.request, 'res': response}
    root.debug('HTTP roundtrip', extra=extra)

class HttpFormatter(logging.Formatter):

    def _formatHeaders(self, d):
        return '\n'.join(f'{k}: {v}' for k, v in d.items())

    def formatMessage(self, record):
        result = super().formatMessage(record)
        if == 'httplogger':
            result += textwrap.dedent('''
                ---------------- request ----------------
                {req.method} {req.url}

                ---------------- response ----------------
                {res.status_code} {res.reason} {res.url}


        return result

formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler(sys.stdout)

session = requests.Session()

PHP Sort a multidimensional array by element containing date

You can simply solve this problem using usort() with callback function. No need to write any custom function.

$your_date_field_name = 'datetime';
usort($your_given_array_name, function ($a, $b) use (&$your_date_field_name) {
    return strtotime($a[$your_date_field_name]) - strtotime($b[$your_date_field_name]);

Scanner vs. BufferedReader

See this link, following is quoted from there:

A BufferedReader is a simple class meant to efficiently read from the underling stream. Generally, each read request made of a Reader like a FileReader causes a corresponding read request to be made to underlying stream. Each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Efficiency is improved appreciably if a Reader is warped in a BufferedReader.

BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads.

A scanner on the other hand has a lot more cheese built into it; it can do all that a BufferedReader can do and at the same level of efficiency as well. However, in addition a Scanner can parse the underlying stream for primitive types and strings using regular expressions. It can also tokenize the underlying stream with the delimiter of your choice. It can also do forward scanning of the underlying stream disregarding the delimiter!

A scanner however is not thread safe, it has to be externally synchronized.

The choice of using a BufferedReader or a Scanner depends on the code you are writing, if you are writing a simple log reader Buffered reader is adequate. However if you are writing an XML parser Scanner is the more natural choice.

Even while reading the input, if want to accept user input line by line and say just add it to a file, a BufferedReader is good enough. On the other hand if you want to accept user input as a command with multiple options, and then intend to perform different operations based on the command and options specified, a Scanner will suit better.

List to array conversion to use ravel() function

Use the following code:

import numpy as np

myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array


I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

What are .a and .so files?

.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.

To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

In Maven how to exclude resources from the generated jar?

Put those properties files in src/test/resources. Files in src/test/resources are available within Eclipse automatically via eclipse:eclipse but will not be included in the packaged JAR by Maven.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               col.names=c("id", "name"), 

will specify exact columns and fill=FALSE will force a two column data frame.

Is it possible to display my iPhone on my computer monitor?

This is a tool that will help you, i installed it myself

Here is the link

How to get domain root url in Laravel 4?

use directly where you want controller or web.php


Splitting templated C++ classes into .hpp/.cpp files--is it possible?

If you know what types your stack will be used with, you can instantiate them expicitly in the cpp file, and keep all relevant code there.

It is also possible to export these across DLLs (!) but it's pretty tricky to get the syntax right (MS-specific combinations of __declspec(dllexport) and the export keyword).

We've used that in a math/geom lib that templated double/float, but had quite a lot of code. (I googled around for it at the time, don't have that code today though.)

Save file Javascript with file name

Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());, 'filename.txt');


Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?

How to convert all elements in an array to integer in JavaScript?

Using jQuery, you can like the map() method like so;

 $.map(arr, function(val,i) { 
     return parseInt(val); 

Why Would I Ever Need to Use C# Nested Classes

There is good uses of public nested members too...

Nested classes have access to the private members of the outer class. So a scenario where this is the right way would be when creating a Comparer (ie. implementing the IComparer interface).

In this example, the FirstNameComparer has access to the private _firstName member, which it wouldn't if the class was a separate class...

public class Person
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    public class FirstNameComparer : IComparer<Person>
        public int Compare(Person x, Person y)
            return x._firstName.CompareTo(y._firstName);

How do I extract part of a string in t-sql

LEFT ('BTA200', 3) will work for the examples you have given, as in :

FROM MyTable

To extract the numeric part, you can use this code

SELECT RIGHT(MyField, LEN(MyField) - 3)
FROM MyTable
--Only have this test if your data does not always start with BTA.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

The problem happened because I was trying to bind a HTML element before it was created.

My script was loaded on top of the HTML and it needs to be loaded at the bottom of my HTML code.

Is it possible to change the location of packages for NuGet?

  1. Create nuget.config in same directory where your solution file is, with following content:
<?xml version="1.0" encoding="utf-8"?>
    <add key="repositoryPath" value="packages" />

'packages' will be the folder where all packages will be restored.

  1. Close Visual studio solution and open it again.

Facebook API: Get fans of / people who like a page

Technically this FQL query should work, but for some reason Facebook disallows it because of a missing index. Not sure if that is because of policy or they just forgot.

SELECT uid FROM page_fans WHERE page_id="YOUR_PAGE_ID"

Javascript: How to loop through ALL DOM elements on a page?

i think this is really quick

document.querySelectorAll('body,body *').forEach(function(e) {

Calculate time difference in minutes in SQL Server

Use DateDiff with MINUTE difference:

SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff

Query that may help you:

SELECT StartTime, EndTime, DATEDIFF(MINUTE, StartTime , EndTime) AS MinuteDiff 
FROM TableName

Best way to alphanumeric check in JavaScript

Here are some notes: The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".

All the answers I read here, returned true in both cases. This is not right.

If I want to check if my "00000" string is alphanumeric, my intuition is unquestionably FALSE.

Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].

On the other hand, if I wanted to check my "abcdefg" string, my intuition is still FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].

The Michael Martin-Smucker's answer has been illuminating.

However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same. The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way. The reason why the regex does not work is as simple as obvious. The syntax [] indicates or, not and. So, if is it only numeric or if is it only letters, regex returns true.

But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me. It allowed me to think at "low level", to create a real function that unambiguously processes an alphanumeric string. I called it like PHP relative function ctype_alnum (edit 2020-02-18: Where, however, this checks OR and not AND).

Here's the code:

function ctype_alnum(str) {
  var code, i, len;
  var isNumeric = false, isAlpha = false; // I assume that it is all non-alphanumeric

  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);

    switch (true) {
      case code > 47 && code < 58: // check if 0-9
        isNumeric = true;

      case (code > 64 && code < 91) || (code > 96 && code < 123): // check if A-Z or a-z
        isAlpha = true;

        // not 0-9, not A-Z or a-z
        return false; // stop function with false result, no more checks

  return isNumeric && isAlpha; // return the loop results, if both are true, the string is certainly alphanumeric

And here is a demo:

function ctype_alnum(str) {
  var code, i, len;
    var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric

  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);
        switch (true){
            case code > 47 && code < 58: // check if 0-9
                isNumeric = true;
            case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
                isAlpha = true;
            default: // not 0-9, not A-Z or a-z
                return false; //stop function with false result, no more checks

  return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric

$("#input").on("keyup", function(){

if ($(this).val().length === 0) {$("#results").html(""); return false};
var isAlphaNumeric = ctype_alnum ($(this).val());
        (isAlphaNumeric) ? 'Yes' : 'No'
<script src=""></script>
<input id="input">

<div> is Alphanumeric? 
<span id="results"></span>

This is an implementation of Michael Martin-Smucker's method in JavaScript.

Dynamic tabs with user-click chosen components

there is component ready to use (rc5 compatible) ng2-steps which uses Compiler to inject component to step container and service for wiring everything together (data sync)

    import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';

import { StepsService } from './ng2-steps';

export class StepDirective implements OnInit{

  @Input('content') content:any;
  @Input('index') index:string;
  public instance;

    private compiler:Compiler,
    private viewContainerRef:ViewContainerRef,
    private sds:StepsService

      const injector = this.viewContainerRef.injector;
      this.viewContainerRef.createComponent(cmpFactory, 0,  injector);


Checking if a file is a directory or just a file

Use the S_ISDIRmacro:

int isDirectory(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);

Attach parameter to button.addTarget action in Swift

For Swift 3.0 you can use following

button.addTarget(self, action: #selector(YourViewController.YourMethodName(_:)), for:.touchUpInside)

func YourMethodName(_ sender : UIButton) {


How do you create a daemon in Python?

Current solution

A reference implementation of PEP 3143 (Standard daemon process library) is now available as python-daemon.

Historical answer

Sander Marechal's code sample is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:


// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
   NewWindow *mMyNewWindow;
// ...


// ...
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
// ...
void MainWindow::openNewWindow()
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   // ...

This is an example on how display a custom new window. There are a lot of ways to do this.

Symfony2 Setting a default choice field selection

the solution: for type entity use option "data" but value is a object. ie:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array

    'class' => 'TestGeneralBundle:Sucursal',
    'label' => 'Sucursal',
    'required' => false,


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

They look pretty much the same on Python 3.2.

As gnibbler pointed out, the first doesn't need to lookup dict, which should make it a tiny bit faster.

>>> def literal():
...   d = {'one': 1, 'two': 2}
>>> def constructor():
...   d = dict(one='1', two='2')
>>> import dis
>>> dis.dis(literal)
  2           0 BUILD_MAP                2
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 ('one')
              9 STORE_MAP
             10 LOAD_CONST               3 (2)
             13 LOAD_CONST               4 ('two')
             16 STORE_MAP
             17 STORE_FAST               0 (d)
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE
>>> dis.dis(constructor)
  2           0 LOAD_GLOBAL              0 (dict)
              3 LOAD_CONST               1 ('one')
              6 LOAD_CONST               2 ('1')
              9 LOAD_CONST               3 ('two')
             12 LOAD_CONST               4 ('2')
             15 CALL_FUNCTION          512
             18 STORE_FAST               0 (d)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE

How can I trim leading and trailing white space?

A simple function to remove leading and trailing whitespace:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)


> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"

Intel's HAXM equivalent for AMD on Windows OS

You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".

Base table or view not found: 1146 Table Laravel 5

If your error is not related to the issue of

Laravel can't determine the plural form of the word you used for your table name.

with this solution

and still have this error, try my approach. you should find the problem in the default "AppServiceProvider.php" or other ServiceProviders defined for that application specifically or even in Kernel.php in App\Console

This error happened for me and I solved it temporary and still couldn't figure out the exact origin and description.

In my case the main problem for causing my table unable to migrate, is that I have running code/query on my "PermissionsServiceProvider.php" in the boot() method.

In the same way, maybe, you defined something in boot() method of AppServiceProvider.php or in the Kernel.php

So first check your Serviceproviders and disable code for a while, and run php artisan migrate and then undo changes in your code.

is there a css hack for safari only NOT chrome?

  • UPDATED FOR CATALINA & SAFARI 13 (early 2020 Update) *

PLEASE PLEASE -- If you are having trouble, and really want to get help or help others by posting a comment about it, Post Your Browser and Device (MacBook/IPad/etc... with both browser and OS version numbers!)

Claiming none of these work is not accurate (and actually not even possible.) Many of these are not really 'hacks' but code built into versions of Safari by Apple. More info is needed. I love the fact that you came here, and really want things to work out for you.

If you have issues getting something from here working on your site, please do check the test site via links below -- If a hack is working there, but not on your site, the hack is not the issue - there is something else happening with your site, often just a CSS conflict as mentioned below, or perhaps nothing is working but you may be unaware that you are not actually using Safari at all. Remember that this info is here to help people with (hopefully) short term issues.

The test site:


NOTE: Filters and compilers (such as the SASS engine) expect standard 'cross-browser' code -- NOT CSS hacks like these which means they will rewrite, destroy or remove the hacks since that is not what hacks do. Much of this is non-standard code that has been painstakingly crafted to target single browser versions only and cannot work if they are altered. If you wish to use it with those, you must load your chosen CSS hack AFTER any filter or compiler. This may seem like a given but there has been a lot of confusion among people who do not realize that they are undoing a hack by running it through such software which was not designed for this purpose.

Safari has changed since version 6.1, as many have noticed.

Please note: if you are using Chrome [and now also Firefox] on iOS (at least in iOS versions 6.1 and newer) and you wonder why none of the hacks seem to be separating Chrome from Safari, it is because the iOS version of Chrome is using the Safari engine. It uses Safari hacks not the Chrome ones. More about that here: Firefox for iOS was released in Fall 2015. It also responds to the Safari Hacks, but none of the Firefox ones, same as iOS Chrome.

ALSO: If you have tried one or more of the hacks and have trouble getting them to work, please post sample code (better yet a test page) - the hack you are attempting, and what browser(s) (exact version!) you are using as well as the device you are using. Without that additional information, it is impossible for me or anyone else here to assist you.

Often it is a simple fix or a missing semicolon. With CSS it is usually that or a problem of which order the code is listed in the style sheets, if not just CSS errors. Please do test the hacks here on the test site. If it works there, that means the hack really is working for your setup, but it is something else that needs to be resolved. People here really do love to help, or at least point you in the right direction.

That out of the way here are hacks for you to use for more recent versions of Safari.

You should try this one first as it covers current Safari versions and is pure-Safari only:

This one still works properly with Safari 13 (early-2020):

/* Safari 7.1+ */

_::-webkit-full-page-media, _:future, :root .safari_only {



To cover more versions, 6.1 and up, at this time you have to use the next pair of css hacks. The one for 6.1-10.0 to go with one that handles 10.1 and up.

So then -- here is one I worked out for Safari 10.1+:

The double media query is important here, don't remove it.

/* Safari 10.1+ */

@media not all and (min-resolution:.001dpcm) { @media {

    .safari_only { 



Try this one if SCSS or other tool set has trouble with the nested media query:

/* Safari 10.1+ (alternate method) */

@media not all and (min-resolution:.001dpcm)
{ @supports (-webkit-appearance:none) {

    .safari_only { 



This next one works for 6.1-10.0 but not 10.1 (Late March 2017 update)

This hack I created over many months of testing and experimentation by combining multiple other hacks.

NOTES: like above, the double media query is NOT an accident -- it rules out many older browsers that cannot handle media query nesting. -- The missing space after one of the 'and's is important as well. This is after all, a hack... and the only one that works for 6.1 and all newer Safari versions at this time. Also be aware as listed in the comments below, the hack is non-standard css and must be applied AFTER a filter. Filters such as SASS engines will rewrite/undo or completely remove it outright.

As mentioned above, please check my test page to see it working as-is (without modification!)

And here is the code:

/* Safari 6.1-10.0 (not 10.1) */

@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) 
{ @media {
    .safari_only { 



For more 'version specific' Safari CSS, please continue to read below.

/* Safari 11+ */

@media not all and (min-resolution:.001dpcm)
{ @supports (-webkit-appearance:none) and (stroke-color:transparent) {

    .safari_only { 



One for Safari 11.0:

/* Safari 11.0 (not 11.1) */

html >> * .safari_only {



One for Safari 10.0:

/* Safari 10.0 (not 10.1) */

_::-webkit-:host:not(:root:root), .safari_only {



Slightly modified works for 10.1 (only):

/* Safari 10.1 */

@media not all and (min-resolution:.001dpcm)
{ @supports (-webkit-appearance:none) and (not (stroke-color:transparent)) {

    .safari_only { 



Safari 10.0 (Non-iOS Devices):

/* Safari 10.0 (not 10.1) but not on iOS */

_::-webkit-:-webkit-full-screen:host:not(:root:root), .safari_only {



Safari 9 CSS Hacks:

A simple supports feature query hack for Safari 9.0 and up:

@supports (-webkit-hyphens:none)

  .safari_only {


A simple underscore hack for Safari 9.0 and up:

_:not(a,b), .safari_only {



Another one for Safari 9.0 and up:

/* Safari 9+ */

_:default:not(:root:root), .safari_only {



and another support features query too:

/* Safari 9+ */

@supports (-webkit-marquee-repetition:infinite) and (object-fit:fill) {

    .safari_only { 



One for Safari 9.0-10.0:

/* Safari 9.0-10.0 (not 10.1) */

_::-webkit-:not(:root:root), .safari_only {



Safari 9 now includes feature detection so we can use that now...

/* Safari 9 */

@supports (overflow:-webkit-marquee) and (justify-content:inherit) 

  .safari_only {


Now to target iOS devices only. As mentioned above, since Chrome on iOS is rooted in Safari, it of course hits that one as well.

/* Safari 9.0 (iOS Only) */

@supports (-webkit-text-size-adjust:none) and (not (-ms-ime-align:auto))
and (not (-moz-appearance:none))

  .safari_only {


one for Safari 9.0+ but not iOS devices:

/* Safari 9+ (non-iOS) */

_:default:not(:root:root), .safari_only {



And one for Safari 9.0-10.0 but not iOS devices:

/* Safari 9.0-10.0 (not 10.1) (non-iOS) */

_:-webkit-full-screen:not(:root:root), .safari_only {



Below are hacks that separate 6.1-7.0, and 7.1+ These also required a combination of multiple hacks in order to get the right result:

/* Safari 6.1-7.0 */

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
   .safari_only {(;



Since I have pointed out the way to block iOS devices, here is the modified version of Safari 6.1+ hack that targets non-iOS devices:

/* Safari 6.1-10.0 (not 10.1) (non-iOS) */

@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) 
{ @media {
    _:-webkit-full-screen, .safari_only { 



To use them:

<div class="safari_only">This text will be Blue in Safari</div>

Usually [like in this question] the reason people ask about Safari hacks is mostly in reference to separating it from Google Chrome (again NOT iOS!) It may be important to post the alternative: how to target Chrome separately from Safari as well, so I am providing that for you here in case it is needed.

Here are the basics, again check my test page for lots of specific versions of Chrome, but these cover Chrome in general. Chrome is version 45, Dev and Canary versions are up to version 47 at this time.

My old media query combo I put on browserhacks still works just for Chrome 29+:

/* Chrome 29+ */

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-resolution:.001dpcm)
    .chrome_only {



An @supports feature query works well for Chrome 29+ as well... a modified version of the one we were using for Chrome 28+ below. Safari 9, the coming Firefox browsers, and the Microsoft Edge browser are not picked up with this one:

/* Chrome 29+ */

@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none))
    .chrome_only {



Previously, Chrome 28 and newer were easy to target. This is one I sent to browserhacks after seeing it included within a block of other CSS code (not originally intended as a CSS hack) and realized what it does, so I extracted the relevant portion for our purposes:

[ NOTE: ] This older method below now pics up Safari 9 and the Microsoft Edge browser without the above update. The coming versions of Firefox and Microsoft Edge have added support for multiple -webkit- CSS codes in their programming, and both Edge and Safari 9 have added support for @supports feature detection. Chrome and Firefox included @supports previously.

/* Chrome 28+, Now Also Safari 9+, Firefox, and Microsoft Edge */

@supports (-webkit-appearance:none) 
    .chrome_and_safari {



The block of Chrome versions 22-28 (If needed to support older versions) are also possible to target with a twist on my Safari combo hacks I posted above:

/* Chrome 22-28 */

@media screen and(-webkit-min-device-pixel-ratio:0)
    .chrome_only {-chrome-:only(;



NOTE: If you are new, change class name but leave this the same-> {-chrome-:only(;

Like the Safari CSS formatting hacks above, these can be used as follows:

<div class="chrome_only">This text will be Blue in Chrome</div>

So you don't have to search for it in this post, here is my live test page again:

[Or the Mirror]

The test page has many others as well, specifically version-based to further help you differentiate between Chrome and Safari, and also many hacks for Firefox, Microsoft Edge, and Internet Explorer web browsers.

NOTE: If something doesn't work for you, check the test page first, but provide example code and WHICH hack you are attempting for anyone to assist you.

hasNext in Python iterators?

No. The most similar concept is most likely a StopIteration exception.

Print Html template in Angular 2 (ng-print in Angular 2)

In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();


<div class="doNotPrint">
    Header is here.

    all my beautiful print-related material is here.

<div class="doNotPrint">
    my footer is here.
    <button (click)="onPrint()">Print</button>




@media print{
  .doNotPrint{display:none !important;}

You can optionally also add other elements / sections you do not wish to print in the media query.

You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.

Webdriver and proxy server for firefox

According to the latest documentation

from selenium import webdriver

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "proxyType": "MANUAL",


with webdriver.Firefox() as driver:
    # Open URL

Run/install/debug Android applications over Wi-Fi?

  1. make sure your pc and android is on same wifi connection.

  2. start adb server from your phone... download any wireless adb app from is what I am using WiFi ADB - Debug Over Air

  3. on your computer start cmd and run: Code (csharp): adb connect Be sure to replace with the IP address that is actually assigned to your device.

check if it is connected by : Code (csharp): adb devices 4. start unity or restart if it is already running and hit play..

  1. tadaa...........:eek:

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

How to create a file in Android?

Write to a file test.txt:

String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        if(fos != null)

Read from file test.txt:

String filepath ="/mnt/sdcard/test.txt";        
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];, 0, length);
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        if(fis != null)

Note: don't forget to add these two permission in AndroidManifest.xml

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

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of using a PreferenceActivity to directly load preferences, use an AppCompatActivity or equivalent that loads a PreferenceFragmentCompat that loads your preferences. It's part of the support library (now Android Jetpack) and provides compatibility back to API 14.

In your build.gradle, add a dependency for the preference support library:

dependencies {
    // ...
    implementation "androidx.preference:preference:1.0.0-alpha1"

Note: We're going to assume you have your preferences XML already created.

For your activity, create a new activity class. If you're using material themes, you should extend an AppCompatActivity, but you can be flexible with this:

public class MyPreferencesActivity extends AppCompatActivity {

    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
                    .replace(, MyPreferencesFragment())

Now for the important part: create a fragment that loads your preferences from XML:

public class MyPreferencesFragment extends PreferenceFragmentCompat {

    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.my_preferences_fragment); // Your preferences fragment

For more information, read the Android Developers docs for PreferenceFragmentCompat.

Adding a favicon to a static HTML page

As recommended by, you can use the rel attribute to achieve this.


<link rel="icon" 

Write single CSV file using spark-csv

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs._
import org.apache.spark.sql.{DataFrame,SaveMode,SparkSession}
import org.apache.spark.sql.functions._

I solved using below approach (hdfs rename file name):-

Step 1:- (Crate Data Frame and write to HDFS)

df.coalesce(1).write.format("csv").option("header", "false").mode(SaveMode.Overwrite).save("/hdfsfolder/blah/")

Step 2:- (Create Hadoop Config)

val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)

Step3 :- (Get path in hdfs folder path)

val pathFiles = new Path("/hdfsfolder/blah/")

Step4:- (Get spark file names from hdfs folder)

val fileNames = hdfs.listFiles(pathFiles, false)

setp5:- (create scala mutable list to save all the file names and add it to the list)

    var fileNamesList = scala.collection.mutable.MutableList[String]()
    while (fileNames.hasNext) {
      fileNamesList +=

Step 6:- (filter _SUCESS file order from file names scala list)

    // get files name which are not _SUCCESS
    val partFileName = fileNamesList.filterNot(filenames => filenames == "_SUCCESS")

step 7:- (convert scala list to string and add desired file name to hdfs folder string and then apply rename)

val partFileSourcePath = new Path("/yourhdfsfolder/"+ partFileName.mkString(""))
    val desiredCsvTargetPath = new Path(/yourhdfsfolder/+ "op_"+ ".csv")
    hdfs.rename(partFileSourcePath , desiredCsvTargetPath)

What does %s and %d mean in printf in the C language?

% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here:

No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.

How to read an http input stream

Try with this code:

InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {

How do I import CSV file into a MySQL table?

The mysql command line is prone to too many problems on import. Here is how you do it:

  • use excel to edit the header names to have no spaces
  • save as .csv
  • use free Navicat Lite Sql Browser to import and auto create a new table (give it a name)
  • open the new table insert a primary auto number column for ID
  • change the type of the columns as desired.
  • done!

How to install and run Typescript locally in npm?

Note if you are using typings do the following:

rm -r typings
typings install

If your doing the angular 2 tutorial use this:

rm -r typings
npm run postinstall
npm start

if the postinstall command dosen't work, try installing typings globally like so:

npm install -g typings

you can also try the following as opposed to postinstall:

typings install

and you should have this issue fixed!

Can I use an HTML input type "date" to collect only a year?

I try with this, no modifications on the css.

$(function() {_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    dateFormat: 'yy',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).datepicker('setDate', new Date(year, 1));_x000D_
  $("#datepicker").focus(function() {_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<p>Date: <input type="text" id="datepicker" /></p>

Example code jsfiddle

Define the selected option with the old input in Laravel / Blade

<option value="{{ $key }}" {{ Input::old('title') == $key ? 'selected="selected"' : '' }}>{{ $val }}</option>

Hiding an Excel worksheet with VBA

Just wanted to add a little more detail to the answers given. You can also use

sheet.Visible = False

to hide and

sheet.Visible = True

to unhide.


Read entire file in Scala?

For faster overall reading / uploading a (large) file, consider increasing the size of bufferSize (Source.DefaultBufSize set to 2048), for instance as follows,

val file = new"myFilename")
io.Source.fromFile(file, bufferSize = Source.DefaultBufSize * 2)

Note Source.scala. For further discussion see Scala fast text file read and upload to memory.

Animate a custom Dialog

I've been struggling with Dialog animation today, finally got it working using styles, so here is an example.

To start with, the most important thing — I probably had it working 5 different ways today but couldn't tell because... If your devices animation settings are set to "No Animations" (Settings ? Display ? Animation) then the dialogs won't be animated no matter what you do!

The following is a stripped down version of my styles.xml. Hopefully it is self-explanatory. This should be located in res/values.

<?xml version="1.0" encoding="utf-8"?>
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>

    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/spin_in</item>
        <item name="android:windowExitAnimation">@android:anim/slide_out_right</item>

The windowEnterAnimation is one of my animations and is located in res\anim. The windowExitAnimation is one of the animations that is part of the Android SDK.

Then when I create the Dialog in my activities onCreateDialog(int id) method I do the following.

Dialog dialog = new Dialog(this,;

// Setting the title and layout for the dialog

Alternatively you could set the animations the following way instead of using the Dialog constructor that takes a theme.

Dialog dialog = new Dialog(this);
dialog.getWindow().getAttributes().windowAnimations =;

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Global keyboard capture in C# application

Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
        _hookID = SetHook(_proc);

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            int vkCode = Marshal.ReadInt32(lParam);
        return CallNextHookEx(_hookID, nCode, wParam, lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

Textarea to resize based on content length

One method is to do it without JavaScript and this is something like this:

    <textarea style="overflow: visible" />

Adding dictionaries together, Python


Note this doesn't actually return the combined dictionary, it just mutates dic0.

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details ..

IIS7 folder permissions for web application

Worked for me in 30 seconds, short and sweet:

  1. In IIS Manager (run inetmgr)
  2. Go to ApplicationPool -> Advanced Settings
  3. Set ApplicationPoolIdentity to NetworkService
  4. Go to the file, right click properties, go to security, click edit, click add, enter Network Service (with space, then click 'check names'), and give full control (or just whatever permissions you need)

datetime datatype in java


The java.time framework built into Java 8 and later supplants both the old date-time classes bundled with the earliest versions of Java and the Joda-Time library. The java.time classes have been back-ported to Java 6 & 7 and to Android.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant =;

Apply an offset-from-UTC (a number of hours and possible minutes and seconds) to get an OffsetDateTime.

ZoneOffset offset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );

Better yet is applying a full time zone which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


Hopefully the JDBC drivers will be updated to work directly with the java.time classes. Until then we must use the java.sql classes to move date-time values to/from the database. But limit your use of the java.sql classes to the chore of database transit. Do not use them for business logic. As part of the old date-time classes they are poorly designed, confusing, and troublesome.

Use new methods added to the old classes to convert to/from java.time. Look for to… and valueOf methods.

Use the java.sql.Timestamp class for date-time values.

java.sql.Timestamp ts = java.sql.Timestamp.valueOf( instant );

And going the other direction…

Instant instant = ts.toInstant();

For date-time data you virtually always want the TIMESTAMP WITH TIME ZONE data type rather than WITHOUT when designing your table columns in your database.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#


Alternatively, you can embed Edge browser, but only targetting windows 10.

Here is the solution.

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[] <- 0

Note the difference is.nan when it's a matrix vs. when it's a data frame.


b[is.nan(b)] <- 0

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

Another solution for many cases is to make sure that the transition between UIViewControllers happens after the not-suitable (like during initialization) procedure finishes, by doing:

__weak MyViewController *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [weakSelf presentViewController:vc animated:YES];

This is general for also pushViewController:animated:, etc.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty directory as I've been using it's for 8 years. For this I used a simple for command for bash shell to do all files:

cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;

Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.

How to get line count of a large file cheaply in Python?

print open('file.txt', 'r').read().count("\n") + 1

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

for a list of invalid characters that you may want to check for.


Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Immutable array in Java

In some situations, it will be lighter weight to use this static method from Google Guava library: List<Integer> Ints.asList(int... backingArray)


  • List<Integer> x1 = Ints.asList(0, 1, 2, 3)
  • List<Integer> x1 = Ints.asList(new int[] { 0, 1, 2, 3})

How to force div to appear below not next to another?

what u can also do i place an extra "dummy" div before your last div.

Make it 1 px heigh and the width as much needed to cover the container div/body

This will make the last div appear under it, starting from the left.

Returning anonymous type in C#

C# compiler is a two phase compiler. In the first phase it just checks namespaces, class hierarchies, Method signatures etc. Method bodies are compiled only during the second phase.

Anonymous types are not determined until the method body is compiled.

So the compiler has no way of determining the return type of the method during the first phase.

That is the reason why anonymous types can not be used as return type.

As others have suggested if you are using .net 4.0 or grater, you can use Dynamic.

If I were you I would probably create a type and return that type from the method. That way it is easy for the future programmers who maintains your code and more readable.

Calling a JSON API with Node.js

I'm using get-json very simple to use:

$ npm install get-json --save

Import get-json

var getJSON = require('get-json')

To do a GET request you would do something like:

getJSON('', function(error, response){

Javascript: Call a function after specific time period

sounds like you're looking for setInterval. It's as easy as this:

function FetchData() {
  // do something
setInterval(FetchData, 60000);

if you only want to call something once, theres setTimeout.

Makefiles with source files in different directories

If the sources are spread in many folders, and it makes sense to have individual Makefiles then as suggested before, recursive make is a good approach, but for smaller projects I find it easier to list all the source files in the Makefile with their relative path to the Makefile like this:

# common sources
COMMON_SRC := ./main.cpp \
              ../src1/somefile.cpp \
              ../src1/somefile2.cpp \
              ../src2/somefile3.cpp \

I can then set VPATH this way:

VPATH := ../src1:../src2

Then I build the objects:

COMMON_OBJS := $(patsubst %.cpp, $(ObjDir)/%$(ARCH)$(DEBUG).o, $(notdir $(COMMON_SRC)))

Now the rule is simple:

# the "common" object files
$(ObjDir)/%$(ARCH)$(DEBUG).o : %.cpp Makefile
    @echo creating $@ ...
    $(CXX) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<

And building the output is even easier:

# This will make the cbsdk shared library
    @echo building output ...
    $(CXX) -o $(BinDir)/$(OUTPUTBIN) $(COMMON_OBJS) $(LFLAGS)

One can even make the VPATH generation automated by:

VPATH := $(dir $(COMMON_SRC))

Or using the fact that sort removes duplicates (although it should not matter):

VPATH := $(sort  $(dir $(COMMON_SRC)))

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

NullInjectorError: No provider for AngularFirestore

Weird thing for me was that I had the provider:[], but the HTML tag that uses the provider was what was causing the error. I'm referring to the red box below: enter image description here

It turns out I had two classes in different components with the same "employee-list.component.ts" filename and so the project compiled fine, but the references were all messed up.

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

Histogram using gnuplot?

Do you want to plot a graph like this one? enter image description here yes? Then you can have a look at my blog article:

Key lines from the code:

n=100 #number of intervals
max=3. #max value
min=-3. #min value
width=(max-min)/n #interval width
#function used to map a value to the intervals
set boxwidth width*0.9
set style fill solid 0.5 # fill style

#count and plot
plot "data.dat" u (hist($1,width)):(1.0) smooth freq w boxes lc rgb"green" notitle

Bootstrap 3 Navbar with Logo

Although your question is interesting i don't expect there will be one answer for it. Maybe your question is too broad. Your solution should depend on: other content in the navbar (number of items), sizes of your logo, should your logo act responsive, etc. Adding the logo in the a (with navbar-brand) seems a good starting point. I should use the navbar-brand class because this will add a padding (top / bottom) of 15 pixels.

I test this setting on with a logo of 300x150 pixels.

Full screen > 1200:

enter image description here

between 768 and 992 pixels (menu not collapsed):

enter image description here

<768 (menu collapsed)

enter image description here

Beside the aesthetic aspects i did not find any technical problem. On small screens a big logo will overlap or break out the viewport maybe. Screens between 768 and 992 pixels also have other problems when the content doesn't fit in a line, see for example:

The default navbar has The default navbar example adds a bottom-margin of 30px so the content of your navbar should never overlap the content of your page. (fixed navbars will have problems when the height of the navbar varies).

You will need some css and media queries to adapt the navbar to your need on different screen sizes. Please try to narrow your question. b.e. describe the problem you found on android.

update see for an example.

On smaller screens such as a phone, the collapsed menu appears above the logo

interchange the button and the logo in your code, logo first (set float:left on the logo)

There is no way to align the menu items to anything except top

set the margin-top for .navbar-collapse ul. Use logo height minus navbar height, to align to the bottom or (logo height - navbar height) / 2 to center

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

Try to remove multidex from default config and check the build error log. If that log is some relatable with INotification class. Use this in android{}

configurations {
    all*.exclude group: '', module: 'support-v4'

This helps me.

Linq code to select one item

Just to make someone's life easier, the linq query with lambda expression

(from x in Items where x.Id == 123 select x).FirstOrDefault();

does result in an SQL query with a select top (1) in it.

How do I repair an InnoDB table?

stop your application...or stop your slave so no new rows are being added

create table <new table> like <old table>;
insert <new table> select * from <old table>;
truncate table  <old table>;
insert <old table> select * from <new table>;

restart your server or slave

Input type for HTML form for integer

You should change your type to number If you accept decimals first and remove them on keyUp, you might solve this...

$("#state").on('keyup', function(){
    $(this).val($(this).val().replace(".", ''));


$("#state").on('keyup', function(){

This will remove the period, but there is no 'Integer Type'.

Order Bars in ggplot2 bar graph

I found it very annoying that ggplot2 doesn't offer an 'automatic' solution for this. That's why I created the bar_chart() function in ggcharts.

ggcharts::bar_chart(theTable, Position)

enter image description here

By default bar_chart() sorts the bars and displays a horizontal plot. To change that set horizontal = FALSE. In addition, bar_chart() removes the unsightly 'gap' between the bars and the axis.

Command to delete all pods in all kubernetes namespaces

I tried commands from listed answers here but pods were stuck in terminating state.
I found below command to delete all pods from particular namespace if stuck in terminating state or you are not able to delete it then you can delete pods forcefully.

kubectl delete pods --all --grace-period=0 --force --namespace namespace

Hope it might be useful to someone.

SQL- Ignore case while searching for a string

Like this.


In postgresql.

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

Running Groovy script from the command line

sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;


What is duck typing?

Duck typing:

If it talks and walks like a duck, then it is a duck

This is typically called abduction (abductive reasoning or also called retroduction, a clearer definition I think):

  • from C (conclusion, what we see) and R (rule, what we know), we accept/decide/assume P (Premise, property) in other words a given fact

    ... the very basis of medical diagnosis

    with ducks: C = walks, talks, R = like a duck, P = it's a duck

Back to programming:

  • object o has method/property mp1 and interface/type T requires/defines mp1

  • object o has method/property mp2 and interface/type T requires/defines mp2

  • ...

So, more than simply accepting mp1... on any object as long has it meets some definition of mp1..., compiler/runtime should also be okay with the assertion o is of type T

And well, is it the case with examples above? Is Duck typing is essentially no typing at all? Or should we call it implicit typing?

Selecting a Record With MAX Value

The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)

select * 
from (
    select PEAA.PresupuestoEtapaActividadId,
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId                                                         
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId    
) as t
where exists (
    select 1 
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId                                                                     
        from hgc.PresupuestoEtapaActividadHistorico as PEAH                       
        group by PEAH.PresupuestoEtapaActividadId  
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId 

How to install pip for Python 3 on Mac OS X?

Also, it's worth to mention that Max OSX/macOS users can just use Homebrew to install pip3.

$> brew update
$> brew install python3
$> pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

Cannot read property 'push' of undefined when combining arrays

I fixed in the below way with typescript

  1. Define and initialize firest

pageNumbers: number[] = [];

  1. than populate it

    for (let i = 1; i < 201; i++) {

JUnit Testing Exceptions

If your constructor is similar to this one:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    //do fun things with valid example here

Then, when you run this JUnit test you will get a green bar:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

Compiler error: "class, interface, or enum expected"

You miss the class declaration.

public class DerivativeQuiz{
   public static void derivativeQuiz(String args[]){ ... }

how much memory can be accessed by a 32 bit machine?

Basically, the term "x-bit machine" does not depend on your machine. That is why we do not need to change our processors or other hardware in order to migrate from a 32bit system to a 64bit one (or vice versa).

32bit and 64bit stands for the addressing capability of the OS running on your machine.

However, it still does not mean that a x-bit operating system is capable to address 2^x GB memory. Because the 'B' in "GB" means "byte" and not "bit". 1 byte equals 8 bits.

Actually a 32bit system can not even address 2^32/8 = 2^29 GB memory space while there should some memory be reserved to the OS.

It is something just below 3 GB.

Hidden Features of C#?

I don't think someone has mentioned that appending ? after a value type name will make it nullable.

You can do:

DateTime? date = null;

DateTime is a structure.

How do I remove a CLOSE_WAIT socket connection

It should be mentioned that the Socket instance in both client and the server end needs to explicitly invoke close(). If only one of the ends invokes close() then too, the socket will remain in CLOSE_WAIT state.

Git push hangs when pushing to Github?

For the sake of completeness (sometimes problems like this are not as complicated as they might seem):

Having a non-existing remote repository configured can also result in this behavior - I recently found out by accidentally changing my origin's URL to

Python: How do I make a subclass from a superclass?

class MySubClass(MySuperClass):
    def __init__(self):

        # <the rest of your custom initialization code goes here>

The section on inheritance in the python documentation explains it in more detail

how to delete default values in text field using selenium?

.clear() can be used to clear the text


using clear with the locator deletes all the value in that exact locator.

How do I install the OpenSSL libraries on Ubuntu?

You want the openssl-devel package. At least I think it's -devel on Ubuntu. Might be -dev. It's one of the two.

Safest way to get last record ID from a table

SELECT LAST(row_name) FROM table_name

Guid.NewGuid() vs. new Guid()

Guid.NewGuid() creates a new UUID using an algorithm that is designed to make collisions very, very unlikely.

new Guid() creates a UUID that is all-zeros.

Generally you would prefer the former, because that's the point of a UUID (unless you're receiving it from somewhere else of course).

There are cases where you do indeed want an all-zero UUID, but in this case Guid.Empty or default(Guid) is clearer about your intent, and there's less chance of someone reading it expecting a unique value had been created.

In all, new Guid() isn't that useful due to this lack of clarity, but it's not possible to have a value-type that doesn't have a parameterless constructor that returns an all-zeros-and-nulls value.

Edit: Actually, it is possible to have a parameterless constructor on a value type that doesn't set everything to zero and null, but you can't do it in C#, and the rules about when it will be called and when there will just be an all-zero struct created are confusing, so it's not a good idea anyway.

String replacement in java, similar to a velocity template

Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.

  1. Create a map of all the objects that will be referenced in the template.
  2. Use a regular expression to find variable references in the template and replace them with their values (see step 3). The Matcher class will come in handy for find-and-replace.
  3. Split the variable name at the dot. would become user and name. Look up user in your map to get the object and use reflection to obtain the value of name from the object. Assuming your objects have standard getters, you will look for a method getName and invoke it.

Insert/Update/Delete with function in SQL Server

"Functions have only READ-ONLY Database Access" If DML operations would be allowed in functions then function would be prety similar to stored Procedure.

Of Countries and their Cities

This service returns Countries (name,code) and cities for any country as REST, SErvice. You can also download database and sample REST service

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Group array items using object

First, in JavaScript it's generally not a good idea to iterate over arrays using for ... in. See Why is using "" with array iteration a bad idea? for details.

So you might try something like this:

var groups = {};
for (var i = 0; i < myArray.length; i++) {
  var groupName = myArray[i].group;
  if (!groups[groupName]) {
    groups[groupName] = [];
myArray = [];
for (var groupName in groups) {
  myArray.push({group: groupName, color: groups[groupName]});

Using the intermediary groups object here helps speed things up because it allows you to avoid nesting loops to search through the arrays. Also, because groups is an object (rather than an array) iterating over it using for ... in is appropriate.


FWIW, if you want to avoid duplicate color entries in the resulting arrays you could add an if statement above the line groups[groupName].push(myArray[i].color); to guard against duplicates. Using jQuery it would look like this;

if (!$.inArray(myArray[i].color, groups[groupName])) {

Without jQuery you may want to add a function that does the same thing as jQuery's inArray:

Array.prototype.contains = function(value) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === value)
      return true;
  return false;

and then use it like this:

if (!groups[groupName].contains(myArray[i].color)) {

Note that in either case you are going to slow things down a bit due to all the extra iteration, so if you don't need to avoid duplicate color entries in the result arrays I would recommend avoiding this extra code. There

How can I use a carriage return in a HTML tooltip?

Tested this in IE, Chrome, Safari, Firefox (latest versions 2012-11-27):

Works in all of them...

Shell script to capture Process ID and kill it if exist


#Find the Process ID for syncapp running instance

PID=`ps -ef | grep syncapp 'awk {print $2}'`

if [[ -z "$PID" ]] then
--->    Kill -9 PID

Not sure if this helps, but 'kill' is not spelled correctly. It's capitalized.

Try 'kill' instead.

How do I update the element at a certain position in an ArrayList?


and if u want to update it then add this line also


How to check if running as root in a bash script

One simple way to make the script only runnable by root is to start the script with the line:

#!/bin/su root

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {

How to open my files in data_folder with pandas using relative path?

current_file = os.path.abspath(os.path.dirname(__file__)) #older/folder2/scripts_folder

csv_filename = os.path.join(current_file, '../data_folder/data.csv')

Disable copy constructor

You can make the copy constructor private and provide no implementation:

    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;

What's the difference between a method and a function?

A function is a mathematical concept. For example:

f(x,y) = sin(x) + cos(y)

says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.

A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).

So, if you have an object Z with a method g(x), you might see the following:

Z.g(x) = sin(x) + cos(Z.y)

In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context; = data;

 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(;
   holder.textAddress = (TextView) row.findViewById(;
   holder.textLocation = (TextView) row.findViewById(;
   holder.btnEdit = (Button) row.findViewById(;
   holder.btnDelete = (Button) row.findViewById(;
  } else {
   holder = (UserHolder) row.getTag();
  User user = data.get(position);
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
  return row;


 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;

Hey Please have a look here-

I have same answer here on my blog ..

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:



Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

Error: EACCES: permission denied

FWIW I had the same symptoms, but with a different package. Creating package.json and running npm init did NOT solve my issue.

On this system, apparently new folders in this location were being created with root permissions. During npm install, new folders are created. This caused npm install to fail partway, even with sudo.

The solution was to run npm install app in a different location with no root umask.

What is the best way to find the users home directory in Java?

The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty("user.home") approach is probably still the best. The user.home approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.

If user.home isn't good enough for you I would suggest choosing a definition of home directory for windows and using it, getting the appropriate environment variable with System.getenv(String).

PHP how to get local IP of system

  • PHP_SELF Returns the filename of the current script with the path relative to the root

  • SERVER_PROTOCOL Returns the name and revision of the page-requested protocol

  • REQUEST_METHOD Returns the request method used to access the page

  • DOCUMENT_ROOT Returns the root directory under which the current script is executing

Hiding table data using <div style="display:none">

Instead of using <div>, it would be better to use to provide the <tr> (which you want to hide) an id and then hiding it using javascript.

insert datetime value in sql database with c#

you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"

Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.

DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";

sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );

How to change heatmap.2 color range in R?

You could try to create your own color palette using the RColorBrewer package

my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)

and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette instead of the redgreen()

I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.

Iterate through object properties

jquery allows you to do this now:

$.each( obj, function( key, value ) {
  alert( key + ": " + value );

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

   brugernavn1 varchar(64),
   password varchar(64)
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 

@ points to a global var in mysql. The above syntax is correct.

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

When should I use the new keyword in C++?

The second method creates the instance on the stack, along with such things as something declared int and the list of parameters that are passed into the function.

The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated on the heap - or free store.

The first method also requires that you delete what you create with new, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="'OtherPage.aspx', 'OtherPage');" />

Check if string ends with one of the strings from a list

another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

List of IP addresses/hostnames from local network in Python

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).

Removing the password from a VBA project

Another way to remove VBA project password is;

  • Open xls file with a hex editor. (ie. Hex Edit
  • Search for DPB
  • Replace DPB to DPx
  • Save file.
  • Open file in Excel.
  • Click "Yes" if you get any message box.
  • Set new password from VBA Project Properties.
  • Close and open again file, then type your new password to unprotect.

UPDATE: For Excel 2010 (Works for MS Office Pro Plus 2010 [14.0.6023.1000 64bit]),

  • Open the XLSX file with 7zip

If workbook is protected:

  • Browse the folder xl
  • If the workbook is protected, right click workbook.xml and select Edit
  • Find the portion <workbookProtection workbookPassword="XXXX" lockStructure="1"/> (XXXX is your encrypted password)
  • Remove XXXX part. (ie. <workbookProtection workbookPassword="" lockStructure="1"/>)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Protect Workbook on Review tab.
  • Optional: Save your file.

If worksheets are protected:

  • Browse to xl/worksheets/ folder.
  • Right click the Sheet1.xml, sheet2.xml, etc and select Edit.
  • Find the portion <sheetProtection password="XXXX" sheet="1" objects="1" scenarios="1" />
  • Remove the encrypted password (ie. <sheetProtection password="" sheet="1" objects="1" scenarios="1" />)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Unprotect Sheet on Review tab.
  • Optional: Save your file.

Test if registry value exists

The best way to test if a registry value exists is to do just that - test for its existence. This is a one-liner, even if it's a little hard to read.

PS C:> (Get-ItemProperty $regkey).PSObject.Properties.Name -contains $name

If you actually look up its data, then you run into the complication of how Powershell interprets 0.

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

This worked for me (win10), place before you import keras:

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

What is DOM Event delegation?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

See this link -->

How to find where javaw.exe is installed?

For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe in case it is not found in the path: (Still Reimeus' suggestion should be your first attempt.)

Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome

Newer versions of JRE/JDK, seem to also place a copy of javaw.exe in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).

Of course there are the "usual" install locations:

  • 'C:\Program Files\Java\jre*\bin'
  • 'C:\Program Files\Java\jdk*\bin'
  • 'C:\Program Files (x86)\Java\jre*\bin'
  • 'C:\Program Files (x86)\Java\jdk*\bin'

[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]

A little while back, I wrote this piece of code to check for javaw.exe in the aforementioned places. Maybe someone finds it useful:

static protected String findJavaw() {
    Path pathToJavaw = null;
    Path temp;

    /* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
    String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
    List<String> output = new ArrayList<>();
    executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                 "/v", "CurrentVersion"}, 
    Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
    for (String line : output) {
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            keyNode += "\\" +;
            List<String> output2 = new ArrayList<>();
                    new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                  "/v", "JavaHome"}, 
            Pattern pattern2 
                    = Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
            for (String line2 : output2) {
                Matcher matcher2 = pattern2.matcher(line2);
                if (matcher2.find()) {
                    pathToJavaw = Paths.get(, "bin", 
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
    } catch (Exception ignored) {}

    /* Check in 'C:\Windows\System32' */
    pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
    } catch (Exception ignored) {}

    /* Check in 'C:\Program Files\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
        } catch (Exception ignored) {}

    /* Check in 'C:\Program Files (x86)\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
        } catch (Exception ignored) {}

    /* Check in 'C:\Program Files\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
        } catch (Exception ignored) {}

    /* Check in 'C:\Program Files (x86)\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
        } catch (Exception ignored) {}

    return "javaw.exe";   // Let's just hope it is in the path :)

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:


Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android=""
        android:versionName="1.0" >

            android:targetSdkVersion="19" />

            android:theme="@style/AppTheme" >
                android:label="@string/app_name" >
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />


It's that simple!

How to get the value of an input field using ReactJS?

I succeeded in doing this by binding the "this" to the function updateInputValue(evt) with

this.updateInputValue = this.updateInputValue.bind(this);

However input value={this.state.inputValue} ... turned out to be no good idea.

Here's the full code in babel ES6 :

class InputField extends React.Component{

   //this.state={inputfield: "no value"};   
   this.handleClick = this.handleClick.bind(this);
   this.updateInputValue = this.updateInputValue.bind(this);

   console.log("trying to add picture url");
   console.log("value of input field : "+this.state.inputfield);


    //console.log("input field updated with ";


    var r; 
    r=<div><input type="text" id="addpixinputfield" 
            onChange={this.updateInputValue} />
      <input type="button" value="add" id="addpix" onClick={this.handleClick}/>
    return r;

Vertical dividers on horizontal UL menu

Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.

#navigation ul
    margin: 0;
    padding: 0;

#navigation ul li
    list-style-type: none;
    display: inline;

#navigation li:not(:first-child):before {
    content: " | ";

Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:

<div id="navigation">
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Support</a></li>
</div><!-- navigation -->

The result will be just like this:


Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates



enter image description here

Communicating between a fragment and an activity - best practices

There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle

implementation 'androidx.fragment:fragment:1.3.0-rc01'

Get decimal portion of a number with JavaScript

After looking at several of these, I am now using...

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);

Moment.js transform to date object

Use this to transform a moment object into a date object:




Tue Nov 04 2014 14:04:01 GMT-0600 (CST)

How to change the Push and Pop animations in a navigation based app

There are UINavigationControllerDelegate and UIViewControllerAnimatedTransitioning there you can change animation for anything you want.

For example this is vertical pop animation for VC:

@objc class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {

func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
    return 0.5

func animateTransition(transitionContext: UIViewControllerContextTransitioning) {

    let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
    let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
    let containerView = transitionContext.containerView()
    let bounds = UIScreen.mainScreen().bounds
    containerView!.insertSubview(toViewController.view, belowSubview: fromViewController.view)
    toViewController.view.alpha = 0.5

    let finalFrameForVC = fromViewController.view.frame

    UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
        fromViewController.view.frame = CGRectOffset(finalFrameForVC, 0, bounds.height)
        toViewController.view.alpha = 1.0
        }, completion: {
            finished in


And then

func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    if operation == .Pop {
        return PopAnimator()
    return nil;

Useful tutorial

Remove "whitespace" between div element

use line-height: 0px;


The CSS Code:


This will affect generically to all your Div's. If you want your existing parent div only to have no spacing, you can apply the same into it.

Is there a way to take a screenshot using Java and save it to some sort of image?

Toolkit returns pixels based on PPI, as a result, a screenshot is not created for the entire screen when using PPI> 100% in Windows. I propose to do this:

DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();
Rectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());
BufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use the is_cart() conditional tag:

if (! is_cart() ) {
  // Do something.

How to modify list entries during for loop?

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]


list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

What characters do I need to escape in XML documents?

Abridged from: XML, Escaping

There are five predefined entities:

&lt; represents "<"
&gt; represents ">"
&amp; represents "&"
&apos; represents '
&quot; represents "

"All permitted Unicode characters may be represented with a numeric character reference." For example:


Most of the control characters and other Unicode ranges are specifically excluded, meaning (I think) they can't occur either escaped or direct:

Valid characters in XML

How do I return a proper success/error message for JQuery .ajax() using PHP? may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Place cursor at the end of text in EditText

public class CustomEditText extends EditText {
    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

    public CustomEditText(Context context) {

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);

    protected void onSelectionChanged(int selStart, int selEnd) {


User this CustomEditText in your XML file, this will work. I have tested this and it is working for me.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Before digging into the solution lets first see why this happens.

Before any transaction with git that your machine does git checks for your authentication which can be done using

  1. An SSH key token present in your machine and shared with git-repo(most preferred) OR
  2. Using your username/password (mostly used)

Why did this happen

In simple words, this happened because the credentials stored in your machine are not authentic i.e.there are chances that your password stored in the machine has changed from whats there in git therefore


Head towards, control panel and search for Credential Manager look for your use git url and change the creds.

There you go this works with mostly every that windows keep track off

How to check if $_GET is empty?

i guess the simplest way which doesn't require any operators is

//do something if $_GET is set 
//do something if $_GET is NOT set 

How to read file from relative path in Java project? cannot find the path specified

For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem

Markdown and including multiple files

I know that this is an old question, but I have not seen any answers to this effect: Essentially, if you are using markdown and pandoc to convert your file to pdf, in your yaml data at the top of the page, you can include something like this:

- \usepackage{pdfpages}
output: pdf_document


# Section

Blah blah

## Section 

Blah blah

Since pandoc using latex to convert all of your documents, the header-includes section calls the pdfpages package. Then when you include \includepdf{/path/to/pdf/document.pdf} it will insert whatever is include in that document. Furthermore, you can include multiple pdf files this way.

As a fun bonus, and this is only because I often use markdown, if you would like to include files other than markdown, for instance latex files. I have modified this answer somewhat. Say that you have a markdown file

title: Something meaning full
author: Talking head

And two addtional latex file document1, that looks like this:




Razor's edge.

And another, document2.tex, that looks like this:




Balh Balh

Assuming that you want to include document1.tex and document2.tex into, you would just do this to

title: Something meaning full
author: Talking head


Run pandoc over it, e.g.

in terminal pandoc -o markdown1.pdf

Your final document will look somewhat like this:

Something Meaning Full

Talking Head




Razor's edge.




Balh Balh

Zoom in on a point (using scale and translate)

The better solution is to simply move the position of the viewport based on the change in the zoom. The zoom point is simply the point in the old zoom and the new zoom that you want to remain the same. Which is to say the viewport pre-zoomed and the viewport post-zoomed have the same zoompoint relative to the viewport. Given that we're scaling relative to the origin. You can adjust the viewport position accordingly:

scalechange = newscale - oldscale;
offsetX = -(zoomPointX * scalechange);
offsetY = -(zoomPointY * scalechange);

So really you can just pan over down and to the right when you zoom in, by a factor of how much you zoomed in, relative to the point you zoomed at.

enter image description here

When is each sorting algorithm used?

Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2), you should avoid it.

Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).

Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.

Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.

In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.

C# get string from textbox

if in string:

string yourVar = yourTextBoxname.Text;

if in numbers:

int yourVar = int.Parse(yourTextBoxname.Text);

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

SSH Key - Still asking for password and passphrase

Mobaxterme had a UI interface for it

setting > configuration > SSH > SSH Agent > [check] Use internal SSH agent "moboAgent" > add [your id_rsa and restart mobaxterme to set changes]