Programs & Examples On #Roundup

Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces.

Representing Directory & File Structure in Markdown Syntax

You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre> tag to preserve the plain text formatting.

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

C++: Rounding up to the nearest multiple of a number

I'm using:

template <class _Ty>
inline _Ty n_Align_Up(_Ty n_x, _Ty n_alignment)
{
    assert(n_alignment > 0);
    //n_x += (n_x >= 0)? n_alignment - 1 : 1 - n_alignment; // causes to round away from zero (greatest absolute value)
    n_x += (n_x >= 0)? n_alignment - 1 : -1; // causes to round up (towards positive infinity)
    //n_x += (_Ty(-(n_x >= 0)) & n_alignment) - 1; // the same as above, avoids branch and integer multiplication
    //n_x += n_alignment - 1; // only works for positive numbers (fastest)
    return n_x - n_x % n_alignment; // rounds negative towards zero
}

and for powers of two:

template <class _Ty>
bool b_Is_POT(_Ty n_x)
{
    return !(n_x & (n_x - 1));
}

template <class _Ty>
inline _Ty n_Align_Up_POT(_Ty n_x, _Ty n_pot_alignment)
{
    assert(n_pot_alignment > 0);
    assert(b_Is_POT(n_pot_alignment)); // alignment must be power of two
    -- n_pot_alignment;
    return (n_x + n_pot_alignment) & ~n_pot_alignment; // rounds towards positive infinity (i.e. negative towards zero)
}

Note that both of those round negative values towards zero (that means round to positive infinity for all values), neither of them relies on signed overflow (which is undefined in C/C++).

This gives:

n_Align_Up(10, 100) = 100
n_Align_Up(110, 100) = 200
n_Align_Up(0, 100) = 0
n_Align_Up(-10, 100) = 0
n_Align_Up(-110, 100) = -100
n_Align_Up(-210, 100) = -200
n_Align_Up_POT(10, 128) = 128
n_Align_Up_POT(130, 128) = 256
n_Align_Up_POT(0, 128) = 0
n_Align_Up_POT(-10, 128) = 0
n_Align_Up_POT(-130, 128) = -128
n_Align_Up_POT(-260, 128) = -256

How do you round UP a number in Python?

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.

In javascript, the exact same code produces a different result:

console.log(Math.ceil(4500/1000));
5

ImportError: No module named mysql.connector using Python2

Depending on your python version and how you installed it, it is possible that mysql connector isn't installed, you can install it with pip

To install mysql connector:

pip install mysql-connector-python

Connecting to SQL Server Express - What is my server name?

This was provided after installation of Sql Express 2019

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

So just use 'localhost\SQLEXPRESS' in server name and windows authentication worked for me.

enter image description here

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I had this problem and I'm not entirely sure which step below made it work, but hope this helps somebody else...this is what I did:

  • Install the downloaded certificate (.crt) into certificates (I put it into “personal” store) - right click on .crt file and click Install Certificate.
  • Run certmgr.msc and export the certificate (found in whichever store you used in the 1st step) as a pfx file including private key, and extended properties (probably unnecessary)
  • Use the exported .pfx file when signing your project
  • Example signtool: signtool sign /f "c:\mycert.pfx" /p mypassword /d "description" /t http://timestamp.verisign.com/scripts/timstamp.dll $(TargetPath)
    where the password is the same as provided during Export

How to truncate the time on a DateTime object in Python?

You cannot truncate a datetime object because it is immutable.

However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:

newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)

Set the absolute position of a view

A more cleaner and dynamic way without hardcoding any pixel values in the code.

I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.

and solved it this way :

    // get the yoffset of the position where your View has to be placed 
    final int yoffset = < calculate the position of the view >

    // position using top margin
    if(myView.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
    }

However you have to make sure the parent layout of myView is an instance of RelativeLayout.

more complete code :

    // identify the button
    final Button clickedButton = <... code to find the button here ...>

    // inflate the dialog - the following style preserves xml layout params
    final View floatingDialog = 
        this.getLayoutInflater().inflate(R.layout.floating_dialog,
            this.floatingDialogContainer, false);

    this.floatingDialogContainer.addView(floatingDialog);

    // get the buttons position
    final int[] buttonPos = new int[2];
    clickedButton.getLocationOnScreen(buttonPos);        
    final int yOffset =  buttonPos[1] + clickedButton.getHeight();

    // position using top margin
    if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
    }

This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.

Can functions be passed as parameters?

I hope the below example will provide more clarity.

package main

type EmployeeManager struct{
    category            string
    city                string
    calculateSalary     func() int64
}


func NewEmployeeManager() (*EmployeeManager,error){

    return &EmployeeManager{
        category : "MANAGEMENT",
        city : "NY",
        calculateSalary: func() int64 {
            var calculatedSalary int64
            // some formula
            return calculatedSalary
        },
    },nil
}

func (self *EmployeeManager) emWithSalaryCalculation(){
    self.calculateSalary = func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }
}

func updateEmployeeInfo(em EmployeeManager){
    // Some code
}

func processEmployee(){
    updateEmployeeInfo(struct {
        category        string
        city            string
        calculateSalary func() int64
    }{category: "", city: "", calculateSalary: func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }})
}

Find and replace entire mysql database

Update old URL to new URL in word-press mysql Query:

UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');

UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');

UPDATE wp_posts SET post_excerpt = replace(post_excerpt, 'http://olddomain.com', 'http://newdomain.com');

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');

Correct way to write loops for promise.

function promiseLoop(promiseFunc, paramsGetter, conditionChecker, eachFunc, delay) {
    function callNext() {
        return promiseFunc.apply(null, paramsGetter())
            .then(eachFunc)
    }

    function loop(promise, fn) {
        if (delay) {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    resolve();
                }, delay);
            })
                .then(function() {
                    return promise
                        .then(fn)
                        .then(function(condition) {
                            if (!condition) {
                                return true;
                            }
                            return loop(callNext(), fn)
                        })
                });
        }
        return promise
            .then(fn)
            .then(function(condition) {
                if (!condition) {
                    return true;
                }
                return loop(callNext(), fn)
            })
    }

    return loop(callNext(), conditionChecker);
}


function makeRequest(param) {
    return new Promise(function(resolve, reject) {
        var req = https.request(function(res) {
            var data = '';
            res.on('data', function (chunk) {
                data += chunk;
            });
            res.on('end', function () {
                resolve(data);
            });
        });
        req.on('error', function(e) {
            reject(e);
        });
        req.write(param);
        req.end();
    })
}

function getSomething() {
    var param = 0;

    var limit = 10;

    var results = [];

    function paramGetter() {
        return [param];
    }
    function conditionChecker() {
        return param <= limit;
    }
    function callback(result) {
        results.push(result);
        param++;
    }

    return promiseLoop(makeRequest, paramGetter, conditionChecker, callback)
        .then(function() {
            return results;
        });
}

getSomething().then(function(res) {
    console.log('results', res);
}).catch(function(err) {
    console.log('some error along the way', err);
});

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

HTML text input allow only numeric input

HTML5 has <input type=number>, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.

Call a Vue.js component method from outside the component

You can use Vue event system

vm.$broadcast('event-name', args)

and

 vm.$on('event-name', function())

Here is the fiddle: http://jsfiddle.net/hfalucas/wc1gg5v4/59/

error: command 'gcc' failed with exit status 1 on CentOS

I bet you have to install libxml2-devel or libxml++-devel or even python-devel. But it is only a wild guess, not seeing the actual error from the log file. But it seems gcc is missing either a header file or a library file.

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

How to increase maximum execution time in php

ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution 

Place this at the top of your PHP script and let your script loose!

Taken from Increase PHP Script Execution Time Limit Using ini_set()

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

How to find the Vagrant IP?

I needed to know this to tell a user what to add to their host machine's host file. This works for me inside vagrant using just bash:

external_ip=$(cat /vagrant/config.yml | grep vagrant_ip | cut -d' ' -f2 | xargs)
echo -e "# Add this line to your host file:\n${external_ip}     host.vagrant.vm"

How To Set Up GUI On Amazon EC2 Ubuntu server

For LXDE/Lubuntu


1. connect to your instance (local forwarding port 5901)

ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

2. Install packages

sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop

3. Create /etc/lightdm/lightdm.conf

sudo nano /etc/lightdm/lightdm.conf

4. Copy and paste the following into the lightdm.conf and save

[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu

5. setup vncserver (you will be asked to create a password for the vncserver)

vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup

6. Restart your instance and reconnect

sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

7. Start vncserver

vncserver -geometry 1280x800

8. In your Remote Desktop Client (e.g. Remmina) set Server to localhost:5901 and protocol to VNC

How to truncate milliseconds off of a .NET DateTime

In my case, I was aiming to save TimeSpan from datetimePicker tool without saving the seconds and the milliseconds, and here is the solution.

First convert the datetimePicker.value to your desired format, which mine is "HH:mm" then convert it back to TimeSpan.

var datetime = datetimepicker1.Value.ToString("HH:mm");
TimeSpan timeSpan = Convert.ToDateTime(datetime).TimeOfDay;

Any way to select without causing locking in MySQL?

From this reference:

If you acquire a table lock explicitly with LOCK TABLES, you can request a READ LOCAL lock rather than a READ lock to enable other sessions to perform concurrent inserts while you have the table locked.

Avoid browser popup blockers

from Google's oauth JavaScript API:

http://code.google.com/p/google-api-javascript-client/wiki/Authentication

See the area where it reads:

Setting up Authentication

The client's implementation of OAuth 2.0 uses a popup window to prompt the user to sign-in and approve the application. The first call to gapi.auth.authorize can trigger popup blockers, as it opens the popup window indirectly. To prevent the popup blocker from triggering on auth calls, call gapi.auth.init(callback) when the client loads. The supplied callback will be executed when the library is ready to make auth calls.

I would guess its relating to the real answer above in how it explains if there is an immediate response, it won't trip the popup alarm. The "gapi.auth.init" is making it so the api happens immediately.

Practical Application

I made an open source authentication microservice using node passport on npm and the various passport packages for each provider. I used a standard redirect approach to the 3rd party giving it a redirect URL to come back to. This was programmatic so I could have different places to redirect back to if login/signup and on particular pages.

github.com/sebringj/athu

passportjs.org

How to count the NaN values in a column in pandas DataFrame

To count zeroes:

df[df == 0].count(axis=0)

To count NaN:

df.isnull().sum()

or

df.isna().sum()

Changing datagridview cell color dynamically

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

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

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

Enzyme - How to access and set <input> value?

I think what you want is:

input.simulate('change', { target: { value: 'Hello' } })

Here's my source.

You shouldn't need to use render() anywhere to set the value. And just FYI, you are using two different render()'s. The one in your first code block is from Enzyme, and is a method on the wraper object mount and find give you. The second one, though it's not 100% clear, is probably the one from react-dom. If you're using Enzyme, just use shallow or mount as appropriate and there's no need for render from react-dom.

How to filter multiple values (OR operation) in angularJS

The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:

<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>   
<ul>
  <li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
    {{movie.name}} ({{movie.genre}}) - {{movie.rating}}
  </li>
</ul>

The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.

HTML forms - input type submit problem with action=URL when URL contains index.aspx

I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.

<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>

How can I convert a std::string to int?

atoi is a built-in function that converts a string to an integer, assuming that the string begins with an integer representation.

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

What is an .inc and why use it?

In my opinion, these were used as a way to quickly find include files when developing. Really these have been made obsolete with conventions and framework designs.

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

When to use IList and when to use List

I would agree with Lee's advice for taking parameters, but not returning.

If you specify your methods to return an interface that means you are free to change the exact implementation later on without the consuming method ever knowing. I thought I'd never need to change from a List<T> but had to later change to use a custom list library for the extra functionality it provided. Because I'd only returned an IList<T> none of the people that used the library had to change their code.

Of course that only need apply to methods that are externally visible (i.e. public methods). I personally use interfaces even in internal code, but as you are able to change all the code yourself if you make breaking changes it's not strictly necessary.

jquery $('.class').each() how many items?

If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.

However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.

Node.js: How to send headers with form data using request module?

I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.

You should add method: 'POST' and your code will work if your backend receive the post method.

var req = require('request');

req.post({
   url: 'someUrl',
   form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
   headers: { 
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
      'Content-Type' : 'application/x-www-form-urlencoded' 
   },
   method: 'POST'
  },

  function (e, r, body) {
      console.log(body);
  });

Exception.Message vs Exception.ToString()

In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.

Wait for a void async method

If you can change the signature of your function to async Task then you can use the code presented here

PHP cURL HTTP PUT

You have mixed 2 standard.

The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";

The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

Can't start Eclipse - Java was started but returned exit code=13

I had the same problem. I was using Windows 8 with a 64-bit OS. I just changed the path to Program Files (x86) and then it started work. I put this line in the eclipse.ini file:

-vm
 C:\Program Files (x86)\Java\jre7\bin\javaw.exe

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

Change directory command in Docker?

To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.

RUN git clone XYZ 
WORKDIR "/XYZ"
RUN make

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

#include <stdio.h>
#include <string.h>

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

Check if string contains \n Java

For portability, you really should do something like this:

public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);

unless you're absolutely certain that "\n" is what you want.

JavaFX - create custom button with image

There are a few different ways to accomplish this, I'll outline my favourites.

Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.

My preferred method is to define a graphic for the button in css:

.toggle-button {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}

.toggle-button:selected {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

OR use the attached css to define a background image.

// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
  -fx-background-repeat: no-repeat;
  -fx-background-position: center;
}

.toggle-button:selected {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.

And some sample code:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImage extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle = new ToggleButton();
    toggle.getStylesheets().add(this.getClass().getResource(
      "imagetogglebutton.css"
    ).toExternalForm());
    toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

Some advantages of doing this are:

  1. You get the default toggle button behavior and don't have to re-implement it yourself by adding your own focus styling, mouse and key handlers etc.
  2. If your app gets ported to different platform such as a mobile device, it will work out of the box responding to touch events rather than mouse events, etc.
  3. Your styling is separated from your application logic so it is easier to restyle your application.

An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImageViaGraphic extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle      = new ToggleButton();
    final Image        unselected  = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
    );
    final Image        selected    = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
    );
    final ImageView    toggleImage = new ImageView();
    toggle.setGraphic(toggleImage);
    toggleImage.imageProperty().bind(Bindings
      .when(toggle.selectedProperty())
        .then(selected)
        .otherwise(unselected)
    );

    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

The code based approach has the advantage that you don't have to use css if you are unfamilar with it.

For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.

What's the simplest way to list conflicted files in Git?

git status displays "both modified" next to files that have conflicts instead of "modified" or "new file", etc

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

Site does not exist error for a2ensite

I just had the same problem. I'd say it has nothing to do with the apache.conf.

a2ensite must have changed - line 532 is the line that enforces the .conf suffix:

else {
    $dir    = 'sites';
    $sffx   = '.conf';
    $reload = 'reload';
}

If you change it to:

else {
    $dir    = 'sites';
    #$sffx   = '.conf';
    $sffx   = '';
    $reload = 'reload';
}

...it will work without any suffix.

Of course you wouldn't want to change the a2ensite script, but changing the conf file's suffix is the correct way.

It's probably just a way of enforcing the ".conf"-suffix.

Centering elements in jQuery Mobile

I had found problems with some of the other methods mentioned here. Another way to do it would be to use layout grid B, and put your content in block b, and leave blocks a and c empty.

http://demos.jquerymobile.com/1.1.2/docs/content/content-grids.html

_x000D_
_x000D_
<div class="ui-grid-b">_x000D_
 <div class="ui-block-a"></div>_x000D_
 <div class="ui-block-b">Your Content Here</div>_x000D_
 <div class="ui-block-c"></div>_x000D_
</div><!-- /grid-b -->
_x000D_
_x000D_
_x000D_

Can't update data-attribute value

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');

// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).data('fruit','7');

// But when you get the value again, it will return old value. 
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7'); 

Read this documentation for vanilla js or this documentation for jquery

Markdown: continue numbered list

If you use tab to indent the code block it will shape the entire block into one line. To avoid this you need to use html ordered list.

  1. item 1
  2. item 2

Code block

<ol start="3">
  <li>item 3</li>
  <li>item 4</li>
</ol>

Representing null in JSON

Let's evaluate the parsing of each:

http://jsfiddle.net/brandonscript/Y2dGv/

var json1 = '{}';
var json2 = '{"myCount": null}';
var json3 = '{"myCount": 0}';
var json4 = '{"myString": ""}';
var json5 = '{"myString": "null"}';
var json6 = '{"myArray": []}';

console.log(JSON.parse(json1)); // {}
console.log(JSON.parse(json2)); // {myCount: null}
console.log(JSON.parse(json3)); // {myCount: 0}
console.log(JSON.parse(json4)); // {myString: ""}
console.log(JSON.parse(json5)); // {myString: "null"}
console.log(JSON.parse(json6)); // {myArray: []}

The tl;dr here:

The fragment in the json2 variable is the way the JSON spec indicates null should be represented. But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. Use your judgement and make an informed decision.


JSON1 {}

This returns an empty object. There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCount or something else) is of type undefined.


JSON2 {"myCount": null}

In this case, myCount is actually defined, albeit its value is null. This is not the same as both "not undefined and not null", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.

This is the definitive way to represent null per the JSON spec.


JSON3 {"myCount": 0}

In this case, myCount is 0. That's not the same as null, and it's not the same as false. If your conditional statement evaluates myCount > 0, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for null however, this is actually not going to work at all.


JSON4 {"myString": ""}

In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "") but you could not test for null or undefined.


JSON5 {"myString": "null"}

This is probably going to get you in trouble, because you're setting the string value to null; in this case, obj.myString == "null" however it is not == null.


JSON6 {"myArray": []}

This will tell you that your array myArray exists, but it's empty. This is useful if you're trying to perform a count or evaluation on myArray. For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.length and it would return 0: defined, but no photos posted.

MVC4 input field placeholder

There are such of ways to Bind a Placeholder to View:

1) With use of MVC Data Annotations:

Model:

[Required]
[Display(Prompt = "Enter Your First Name")]
public string FirstName { get; set; }

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})

2) With use of MVC Data Annotations But with DisplayName:

Model:

[Required]
[DisplayName("Enter Your First Name")]
public string FirstName { get; set; }

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})

3) Without use of MVC Data Annotation (recommended):

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "Enter Your First Name")

How can I pass a parameter to a setTimeout() callback?

You can pass the parameter to the setTimeout callback function as:

setTimeout(function, milliseconds, param1, param2, ...)

eg.

function myFunction() {
  setTimeout(alertMsg, 3000, "Hello");
}

function alertMsg(message) {
    alert(message)
}

"unexpected token import" in Nodejs5 and babel?

Involve following steps to resolve the issue:

1) Install the CLI and env preset

$ npm install --save-dev babel-cli babel-preset-env

2) Create a .babelrc file

{
  "presets": ["env"]
}

3) configure npm start in package.json

"scripts": {
    "start": "babel-node ./server/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

4) then start app

$ npm start

document.all vs. document.getElementById

document.all is very old, you don't have to use it anymore.

To quote Nicholas Zakas:

For instance, when the DOM was young, not all browsers supported getElementById(), and so there was a lot of code that looked like this:

if(document.getElementById){  //DOM
    element = document.getElementById(id);
} else if (document.all) {  //IE
    element = document.all[id];
} else if (document.layers){  //Netscape < 6
    element = document.layers[id];
}

Remove duplicate elements from array in Ruby

The simplest ways for me are these ones:

array = [1, 2, 2, 3]

Array#to_set

array.to_set.to_a

# [1, 2, 3]

Array#uniq

array.uniq

# [1, 2, 3]

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

Center a DIV horizontally and vertically

Here's a demo: http://www.w3.org/Style/Examples/007/center-example

A method (JSFiddle example)

CSS:

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

HTML:

<div id="content">
    Content goes here
</div>

Another method (JSFiddle example)

CSS

body, html, #wrapper {
    width: 100%;
    height: 100%
}
#wrapper {
    display: table
}
#main {
    display: table-cell;
    vertical-align: middle;
    text-align:center
}

HTML

<div id="wrapper">
<div id="main">
    Content goes here
</div>
</div>

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

A variable modified inside a while loop is not remembered

UPDATED#2

Explanation is in Blue Moons's answer.

Alternative solutions:

Eliminate echo

while read line; do
...
done <<EOT
first line
second line
third line
EOT

Add the echo inside the here-is-the-document

while read line; do
...
done <<EOT
$(echo -e $lines)
EOT

Run echo in background:

coproc echo -e $lines
while read -u ${COPROC[0]} line; do 
...
done

Redirect to a file handle explicitly (Mind the space in < <!):

exec 3< <(echo -e  $lines)
while read -u 3 line; do
...
done

Or just redirect to the stdin:

while read line; do
...
done < <(echo -e  $lines)

And one for chepner (eliminating echo):

arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
...
}

Variable $lines can be converted to an array without starting a new sub-shell. The characters \ and n has to be converted to some character (e.g. a real new line character) and use the IFS (Internal Field Separator) variable to split the string into array elements. This can be done like:

lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr

Result is

first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Here is simple sample from android developer.

Basically, you can write a file in the internal storage like this :

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

How to add a JAR in NetBeans

Project Files Services Tabls

go files tabs

drag drop file to libs files hover.

return project tabs and what are you see :)

Swift - encode URL

Had need of this myself, so I wrote a String extension that both allows for URLEncoding strings, as well as the more common end goal, converting a parameter dictionary into "GET" style URL Parameters:

extension String {
    func URLEncodedString() -> String? {
        var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        return escapedString
    }
    static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
        if (parameters.count == 0)
        {
            return nil
        }
        var queryString : String? = nil
        for (key, value) in parameters {
            if let encodedKey = key.URLEncodedString() {
                if let encodedValue = value.URLEncodedString() {
                    if queryString == nil
                    {
                        queryString = "?"
                    }
                    else
                    {
                        queryString! += "&"
                    }
                    queryString! += encodedKey + "=" + encodedValue
                }
            }
        }
        return queryString
    }
}

Enjoy!

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Deserializing a JSON file with JavaScriptSerializer()

  public class User : List<UserData>
    {

        public int id { get; set; }
        public string screen_name { get; set; }

    }


    string json = client.DownloadString(url);
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var Data = serializer.Deserialize<List<UserData>>(json);

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

From Java8 and above, you may use below command:

jcmd JAVA_PROCESS_ID GC.heap_info

You may refer to sum of, total and used memory from the output.

Sample Command And Output: jcmd 9758 GC.heap_info

PSYoungGen  total 1579520K, used 487543K [0x0000000751d80000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 1354240K, 36% used [0x0000000751d80000,0x000000076f99dc40,0x00000007a4800000)
  from space 225280K, 0% used [0x00000007b2400000,0x00000007b2400000,0x00000007c0000000)
  to   space 225280K, 0% used [0x00000007a4800000,0x00000007a4800000,0x00000007b2400000)
ParOldGen       total 3610112K, used 0K [0x0000000675800000, 0x0000000751d80000, 0x0000000751d80000)
  object space 3610112K, 0% used [0x0000000675800000,0x0000000675800000,0x0000000751d80000)
Metaspace       used 16292K, capacity 16582K, committed 16896K, reserved 1064960K
  class space    used 1823K, capacity 1936K, committed 2048K, reserved 1048576K

For more details on jcmd command, visit link here

How can I post an array of string to ASP.NET MVC Controller without a form?

As I discussed here ,

if you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.

public string GetData() {
  // InputStream contains the JSON object you've sent
  String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();

  // Deserialize it to a dictionary
  var dic =
    Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
    dynamic >> (jsonString);

  string result = "";

  result += dic["firstname"] + dic["lastname"];

  // You can even cast your object to their original type because of 'dynamic' keyword
  result += ", Age: " + (int) dic["age"];

  if ((bool) dic["married"])
    result += ", Married";

  return result;
}

The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.

You can use a helper method like this to facilitate your job:

public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
  String jsonString = new StreamReader(request.InputStream).ReadToEnd();
  return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
}

"inappropriate ioctl for device"

Eureka moment!

I have had this error before.

Did you invoke the perl debugger with something like :-

perl -d yourprog.pl > log.txt

If so whats going on is perl debug tries to query and perhaps reset the terminal width. When stdout is not a terminal this fails with the IOCTL message.

The alternative would be for your debug session to hang forever because you did not see the prompt for instructions.

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

What's the difference between lists enclosed by square brackets and parentheses in Python?

The first is a list, the second is a tuple. Lists are mutable, tuples are not.

Take a look at the Data Structures section of the tutorial, and the Sequence Types section of the documentation.

How to align an input tag to the center without specifying the width?

You can also use the tag, this works in divs and everything else:

<center><form></form></center>

This link will help you with the tag:

Why is the <center> tag deprecated in HTML?

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me . Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command

**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**

After that i started my server and downloaded the client certificates via the below mentioned openssl command

**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**

Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command

**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**

How to pass a form input value into a JavaScript function

Well ya you can do that in this way.

    <input type="text" name="address" id="address">
        <div id="map_canvas" style="width: 500px; height: 300px"></div>
    <input type="button" onclick="showAddress(address.value)" value="ShowMap"/>

Java Script

function showAddress(address){

    alert("This is address :"+address)

}

That is one example for the same. and that will run.

Twitter Bootstrap Multilevel Dropdown Menu

[Twitter Bootstrap v3]

To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,

CSS:

.dropdown-menu>li /* To prevent selection of text */
{   position:relative;
    -webkit-user-select: none; /* Chrome/Safari */        
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
    cursor:pointer;
}
.dropdown-menu .sub-menu 
{
    left: 100%;
    position: absolute;
    top: 0;
    display:none;
    margin-top: -1px;
    border-top-left-radius:0;
    border-bottom-left-radius:0;
    border-left-color:#fff;
    box-shadow:none;
}
.right-caret:after,.left-caret:after
 {  content:"";
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    display: inline-block;
    height: 0;
    vertical-align: middle;
    width: 0;
    margin-left:5px;
}
.right-caret:after
{   border-left: 5px solid #ffaf46;
}
.left-caret:after
{   border-right: 5px solid #ffaf46;
}

JQuery:

$(function(){
    $(".dropdown-menu > li > a.trigger").on("click",function(e){
        var current=$(this).next();
        var grandparent=$(this).parent().parent();
        if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
            $(this).toggleClass('right-caret left-caret');
        grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
        grandparent.find(".sub-menu:visible").not(current).hide();
        current.toggle();
        e.stopPropagation();
    });
    $(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
        var root=$(this).closest('.dropdown');
        root.find('.left-caret').toggleClass('right-caret left-caret');
        root.find('.sub-menu:visible').hide();
    });
});

HTML:

<div class="dropdown" style="position:relative">
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a class="trigger right-caret">Level 1</a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Level 2</a></li>
                <li>
                    <a class="trigger right-caret">Level 2</a>
                    <ul class="dropdown-menu sub-menu">
                        <li><a href="#">Level 3</a></li>
                        <li><a href="#">Level 3</a></li>
                        <li>
                            <a class="trigger right-caret">Level 3</a>
                            <ul class="dropdown-menu sub-menu">
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Level 2</a></li>
            </ul>
        </li>
        <li><a href="#">Level 1</a></li>
        <li><a href="#">Level 1</a></li>
    </ul>
</div>

What's the best way to get the current URL in Spring MVC?

in jsp file:

request.getAttribute("javax.servlet.forward.request_uri")

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

How do I center an anchor element in CSS?

css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.

How to prevent SIGPIPEs (or handle them properly)

Handle SIGPIPE Locally

It's usually best to handle the error locally rather than in a global signal event handler since locally you will have more context as to what's going on and what recourse to take.

I have a communication layer in one of my apps that allows my app to communicate with an external accessory. When a write error occurs I throw and exception in the communication layer and let it bubble up to a try catch block to handle it there.

Code:

The code to ignore a SIGPIPE signal so that you can handle it locally is:

// We expect write failures to occur but we want to handle them where 
// the error occurs rather than in a SIGPIPE handler.
signal(SIGPIPE, SIG_IGN);

This code will prevent the SIGPIPE signal from being raised, but you will get a read / write error when trying to use the socket, so you will need to check for that.

Node.js Port 3000 already in use but it actually isn't?

check for any process running on the same port by entering the command:

sudo ps -ef

You can find the process running on the respective node port, then kill the node by

kill -9 <node id>

If the problem still remains then just kill all the node

killall node

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

Is it possible to make Font Awesome icons larger than 'fa-5x'?

You can redefine/overwrite the default font-awesome sizes and also add you own sizes

.fa-1x{
    font-size:0.8em;
}
.fa-2x{
    font-size:1em;
}
.fa-3x{
    font-size:1.2em;
}
.fa-4x{
    font-size:1.4em;
}
.fa-5x{
    font-size:1.6em;
}
.fa-mycustomx{
    font-size:3.2em;
}

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

Relative div height

The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.

You need to set the height of the body and html:

HTML:

<div class="block12">
    <div class="block1">1</div>
    <div class="block2">2</div>
</div>
<div class="block3">3</div>

CSS:

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.block12 {
    width: 100%;
    height: 50%;
    background: yellow;
    overflow: auto;
}
.block1, .block2 {
    width: 50%;
    height: 100%;
    display: inline-block;
    margin-right: -4px;
    background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
    width: 100%;
    height: 50%;
    background: lightblue;
}

And a JSFiddle

New to MongoDB Can not run command mongo

After installing the MongoDB you should manually create a data folder.

By default MongoDB will store data in /data/db, 
but it won't automatically create that directory. To create it, do:

$ sudo mkdir -p /data/db/
$ sudo chown `id -u` /data/db

You can also tell MongoDB to use a different data directory,
with the --dbpath option.

For more detailed information go to MongoDB wiki page.

Why use Gradle instead of Ant or Maven?

I don't use Gradle in anger myself (just a toy project so far) [author means they have used Gradle on only a toy project so far, not that Gradle is a toy project - see comments], but I'd say that the reasons one would consider using it would be because of the frustrations of Ant and Maven.

In my experience Ant is often write-only (yes I know it is possible to write beautifully modular, elegant builds, but the fact is most people don't). For any non-trivial projects it becomes mind-bending, and takes great care to ensure that complex builds are truly portable. Its imperative nature can lead to replication of configuration between builds (though macros can help here).

Maven takes the opposite approach and expects you to completely integrate with the Maven lifecycle. Experienced Ant users find this particularly jarring as Maven removes many of the freedoms you have in Ant. For example there's a Sonatype blog that enumerates many of the Maven criticisms and their responses.

The Maven plugin mechanism allows for very powerful build configurations, and the inheritance model means you can define a small set of parent POMs encapsulating your build configurations for the whole enterprise and individual projects can inherit those configurations, leaving them lightweight. Maven configuration is very verbose (though Maven 3 promises to address this), and if you want to do anything that is "not the Maven way" you have to write a plugin or use the hacky Ant integration. Note I happen to like writing Maven plugins but appreciate that many will object to the effort involved.

Gradle promises to hit the sweet spot between Ant and Maven. It uses Ivy's approach for dependency resolution. It allows for convention over configuration but also includes Ant tasks as first class citizens. It also wisely allows you to use existing Maven/Ivy repositories.

So if you've hit and got stuck with any of the Ant/Maven pain points, it is probably worth trying Gradle out, though in my opinion it remains to be seen if you wouldn't just be trading known problems for unknown ones. The proof of the pudding is in the eating though so I would reserve judgment until the product is a little more mature and others have ironed out any kinks (they call it bleeding edge for a reason). I'll still be using it in my toy projects though, It's always good to be aware of the options.

How to compare two lists in python?

If you mean lists, try ==:

l1 = [1,2,3]
l2 = [1,2,3,4]

l1 == l2 # False

If you mean array:

l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False

If you want to compare strings (per your comment):

date_string  = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False

How to configure heroku application DNS to Godaddy Domain?

You can't use the naked domain of your-domain.com if it is not redirected to the www.your-domain.com. Heroku use the www.yourdomain.com which act here as a subdomain. So when you follow the default instruction to use your-domain.com then you will need to assign both of them.

We can actually assign only the naked domain without the www.your-domain.com. Use only your-domain.com when the domain's dns provider (NameServers) support ALIAS or ANAME for the @ Record to example.herokuapp.com without CNAME www.your-domain.com to it.

It will let you to point www.your-domain.com to other hosting separately (independent).

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

Get file size before uploading

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

Jquery submit form

Try this lets say your form id is formID

$(".nextbutton").click(function() { $("form#formID").submit(); });

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

create table employee
(
   empid int,
   empname varchar(40),
   designation varchar(30),
   hiredate datetime, 
   Bsalary int,
   depno constraint emp_m foreign key references department(depno)
)

We should have an primary key to create foreign key or relationship between two or more table .

how to use getSharedPreferences in android

If someone used this:

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

PreferenceManager is now depricated, refactor to this:

val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

How do I save a String to a text file using Java?

You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file. if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
}

public void SaveFile(String name, ArrayList< String> message) {

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);     
    }   
}

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

Text File Parsing in Java

If you have a 200,000,000 character files and split that every five characters, you have 40,000,000 String objects. Assume they are sharing actual character data with the original 400 MB String (char is 2 bytes). A String is say 32 bytes, so that is 1,280,000,000 bytes of String objects.

(It's probably worth noting that this is very implementation dependent. split could create entirely strings with entirely new backing char[] or, OTOH, share some common String values. Some Java implementations to not use the slicing of char[]. Some may use a UTF-8-like compact form and give very poor random access times.)

Even assuming longer strings, that's a lot of objects. With that much data, you probably want to work with most of it in compact form like the original (only with indexes). Only convert to objects that which you need. The implementation should be database like (although they traditionally don't handle variable length strings efficiently).

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

CSS: create white glow around image

Use simple CSS3 (not supported in IE<9)

img
{
    box-shadow: 0px 0px 5px #fff;
}

This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)

If you're worried about the users that don't have the latest versions of their browsers, use this:

img
{
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;
}

For IE you can use a glow filter (not sure which browsers support it)

img
{
    filter:progid:DXImageTransform.Microsoft.Glow(Color=white,Strength=5);
}

Play with the settings to see what suits you :)

gdb fails with "Unable to find Mach task port for process-id" error

It works when I change to sudo gdb executableFileName! :)

Get a list of dates between two dates

Borrowing an idea from this answer, you can set up a table with 0 through 9 and use that to generate your list of dates.

CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

select adddate('2009-01-01', numlist.id) as `date` from
(SELECT n1.i + n10.i*10 + n100.i*100 AS id
   FROM num n1 cross join num as n10 cross join num as n100) as numlist
where adddate('2009-01-01', numlist.id) <= '2009-01-13';

This will allow you to generate a list of up to 1000 dates. If you need to go larger, you can add another cross join to the inner query.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

How to define a Sql Server connection string to use in VB.NET?

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.IO
Imports System.Configuration
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataAdapter

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

How many socket connections possible?

Realistically for an application, more then 4000-5000 open sockets on a single machine becomes impractical. Just checking for activity on all the sockets and managing them starts to become a performance issue - especially in real-time environments.

Angular is automatically adding 'ng-invalid' class on 'required' fields

the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)

input.ng-invalid.ng-touched{
  border-bottom: 1px solid #e74c3c !important; 
}

Throwing multiple exceptions in a method of an interface in java

I think you are asking for something like the code below:

public interface A
{
    void foo() 
        throws AException;
}

public class B
    implements A
{
    @Overrides 
    public void foo()
        throws AException,
               BException
    {
    }
}

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main
{
    public static void main(final String[] argv)
    {
        A a;

        a = new B();

        try
        {
            a.foo();
        }
        catch(final AException ex)
        {
        }
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.
    }
}

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

npm install errors with Error: ENOENT, chmod

None of the above worked for me. But yarn install worked, then npm i started working. Not sure what yarn fixed, but quick and easy solution!

How to synchronize a static variable among threads running different instances of a class in Java?

If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

public class Test {

    private final static AtomicInteger count = new AtomicInteger(0); 

    public void foo() {  
        count.incrementAndGet();
    }  
}

Drawing an image from a data URL to a canvas

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

How to get a single value from FormGroup

This code also works:

this.formGroup.controls.nameOfcontrol.value

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

What is DOM Event delegation?

dom event delegation is something different from the computer science definition.

It refers to handling bubbling events from many elements, like table cells, from a parent object, like the table. It can keep the code simpler, especially when adding or removing elements, and saves some memory.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

For following Error:

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

Run following NPM command:

$ npm install [email protected]

Source Link

Eclipse does not start when I run the exe?

In my case the problem was not having a proper javabin folder in the PATH variable.

Open the PATH variable and make sure it points to a proper JRE bin folder.

How can I download a specific Maven artifact in one command line?

With the latest version (2.8) of the Maven Dependency Plugin, downloading an artifact from the Maven Central Repository is as simple as:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=groupId:artifactId:version[:packaging[:classifier]]

where groupId:artifactId:version, etc. are the Maven coordinates

An example, tested with Maven 2.0.9, Maven 2.2.1, and Maven 3.0.4:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.hibernate:hibernate-entitymanager:3.4.0.GA:jar:sources

(Thanks to Pascal Thivent for providing his wonderful answer in the first place. I am adding another answer, because it wouldn't fit in a comment and it would be too extensive for an edit.)

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

SQL query to find Nth highest salary from a salary table

+-------+--------+
|  name | salary |
+-------+--------+
|   A   | 100    |
|   B   | 200    |
|   C   | 300    |
|   D   | 400    |
|   E   | 500    |
|   F   | 500    |
|   G   | 600    |
+-------+--------+

IF YOU WANT TO SELECT ONLY Nth HIGHEST SALARY THEN:

SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1;

IF YOU WANT TO SELECT ALL EMPLOYEE WHO GETTING Nth HIGHEST SALARY THEN:

SELECT * FROM emp WHERE salary = (
   SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1
);

How to get base url in CodeIgniter 2.*

Just load helper class

$this->load->helper('url');

thats it.

How do you add an SDK to Android Studio?

And For linux(ubuntu)

/usr/share/android-studio/data/sdk

How can I search an array in VB.NET?

check this..

        string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
        Array.IndexOf(strArray, "C"); // not found, returns -1
        Array.IndexOf(strArray, "CDE"); // found, returns index

Daemon Threads Explanation

A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.

A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.

How to remove constraints from my MySQL table?

For those that come here using MariaDB:

Note that MariaDB allows DROP CONSTRAINT statements in general, for example for dropping check constraints:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

https://mariadb.com/kb/en/library/alter-table/

Convert month name to month number in SQL Server

You can try sth like this, if you have month_name which is string datetype.After converting, you can feel free to order by Month.

For example, your table like this:

 month
 Dec
 Jan
 Feb
 Nov
 Mar
  .
  .
  .

My syntax is:

 Month(cast(month+'1 2016' as datetime))

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

get list of pandas dataframe columns based on data type

You can use boolean mask on the dtypes attribute:

In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])

In [12]: df.dtypes
Out[12]: 
0      int64
1    float64
2     object
dtype: object

In [13]: msk = df.dtypes == np.float64  # or object, etc.

In [14]: msk
Out[14]: 
0    False
1     True
2    False
dtype: bool

You can look at just those columns with the desired dtype:

In [15]: df.loc[:, msk]
Out[15]: 
        1
0  2.3456

Now you can use round (or whatever) and assign it back:

In [16]: np.round(df.loc[:, msk], 2)
Out[16]: 
      1
0  2.35

In [17]: df.loc[:, msk] = np.round(df.loc[:, msk], 2)

In [18]: df
Out[18]: 
   0     1  2
0  1  2.35  c

Disable developer mode extensions pop up in Chrome

Using selenium with Python, you start the driver with extensions disabled like this:

from selenium import webdriver
options = webdriver.chrome.options.Options()
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options)

The popup 'Disable developer mode extensions' will not pop up.

How to align the text middle of BUTTON

You can use text-align: center; line-height: 65px;

Demo

CSS

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here
}

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

For those of you on AWS (Amazon Web Services), remember to add a rule for your SSL port (in my case 443) to your security groups. I was getting this error because I forgot to open the port.

3 hours of tearing my hair out later...

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Format JavaScript date as yyyy-mm-dd

_x000D_
_x000D_
const today = new Date(); // or whatever _x000D_
_x000D_
const yearFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;_x000D_
}_x000D_
_x000D_
const monthFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
const dayFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
console.log(yearFirstFormater(today));_x000D_
console.log(monthFirstFormater(today));_x000D_
console.log(dayFirstFormater(today));
_x000D_
_x000D_
_x000D_

How can I convert my Java program to an .exe file?

javapackager

The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.

– Oracle's documentation

The javapackager utility ships with the JDK. It can generate .exe files with the -native exe flag, among many other things.

WinRun4J

WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:

  • Uses an INI file for specifying classpath, main class, vm args, program args.
  • Custom executable name that appears in task manager.
  • Additional JVM args for more flexible memory use.
  • Built-in icon replacer for custom icon.
  • [more bullet points follow]

– WinRun4J's webpage

WinRun4J is an open source utility. It has many features.

packr

Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.

– packr README

packr is another open source tool.

JSmooth

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.

– JSmooth's website

JSmooth is open source and has features, but it is very old. The last release was in 2007.

JexePack

JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.

– JexePack's website

JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.

InstallAnywhere

InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.

– InstallAnywhere's website

InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.

Executable JAR files

As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.


For more information

An excellent source of information on this topic is Excelsior's article "Convert Java to EXE – Why, When, When Not and How".

See also the companion article "Best JAR to EXE Conversion Tools, Free and Commercial".

'MOD' is not a recognized built-in function name

In TSQL, the modulo is done with a percent sign.

SELECT 38 % 5 would give you the modulo 3

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

How do you see recent SVN log entries?

I like to use -v for verbose mode.
It'll give you the commit id, comments and all affected files.

svn log -v --limit 4

Example of output:

I added some migrations and deleted a test xml file
------------------------------------------------------------------------
r58687 | mr_x | 2012-04-02 15:31:31 +0200 (Mon, 02 Apr 2012) | 1 line Changed
paths: 
A /trunk/java/App/src/database/support    
A /trunk/java/App/src/database/support/MIGRATE    
A /trunk/java/App/src/database/support/MIGRATE/remove_device.sql
D /trunk/java/App/src/code/test.xml

How to get video duration, dimension and size in PHP?

getID3 supports video formats. See: http://getid3.sourceforge.net/

Edit: So, in code format, that'd be like:

include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");

Note: You must include the getID3 classes before this will work! See the above link.

Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/

API pagination best practices

Pagination is generally a "user" operation and to prevent overload both on computers and the human brain you generally give a subset. However, rather than thinking that we don't get the whole list it may be better to ask does it matter?

If an accurate live scrolling view is needed, REST APIs which are request/response in nature are not well suited for this purpose. For this you should consider WebSockets or HTML5 Server-Sent Events to let your front end know when dealing with changes.

Now if there's a need to get a snapshot of the data, I would just provide an API call that provides all the data in one request with no pagination. Mind you, you would need something that would do streaming of the output without temporarily loading it in memory if you have a large data set.

For my case I implicitly designate some API calls to allow getting the whole information (primarily reference table data). You can also secure these APIs so it won't harm your system.

How to install a specific version of package using Composer?

composer require vendor/package:version

for example:

composer require refinery29/test-util:0.10.2

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

SQL Server: Is it possible to insert into two tables at the same time?

You still need two INSERT statements, but it sounds like you want to get the IDENTITY from the first insert and use it in the second, in which case, you might want to look into OUTPUT or OUTPUT INTO: http://msdn.microsoft.com/en-us/library/ms177564.aspx

jQuery UI - Draggable is not a function?

This issue can also be caused if you include the normal jquery library twice. I had the following line twice, in my body and head.

It never caused any problems until I tried to use jquery UI as well.

Purpose of __repr__ method?

Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.

Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/

Rails 4 Authenticity Token

When you define you own html form then you have to include authentication token string ,that should be sent to controller for security reasons. If you use rails form helper to generate the authenticity token is added to form as follow.

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden" value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
  </div>
    ...
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then compromising security etc.

How to import js-modules into TypeScript file?

In your second statement

import {FriendCard} from './../pages/FriendCard'

you are telling typescript to import the FriendCard class from the file './pages/FriendCard'

Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.

You have two options here. If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file. See https://github.com/Microsoft/TypeScript/issues/3019 for more details. about why you need to add the file.

Option 1

Refactor the Friend card js file to be typed.

export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;

constructor(card) {
    this.webElement = card;
    this.menuButton;
    this.serialNumber;
}



getAsWebElement = function () {
    return this.webElement;
};

clickMenuButton = function () {
    this.menuButton.click();
};

setSerialNumber = function (numberOfElements) {
    this.serialNumber = numberOfElements + 1;
    this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};

deleteFriend = function () {
    element(by.css('[ng-click="deleteFriend(person);"]')).click();
    element(by.css('[ng-click="confirm()"]')).click();
}
};

Option 2

You can import the anonymous function

 import * as FriendCard from module("./FriendCardJs");

There are a few options for a d.ts file definition. This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

Identify duplicates in a List

create a Map<Integer,Integer>, iterate the list, if an element is in the map, increase it's value, otherwise add it to the map with key=1
iterate the map, and add to the lists all elements with key>=2

public static void main(String[] args) {
        List<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        for (Integer x : list) { 
            Integer val = map.get(x);
            if (val == null) { 
                map.put(x,1);
            } else {
                map.remove(x);
                map.put(x,val+1);
            }
        }
        List<Integer> result = new LinkedList<Integer>();
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 1) {
                result.add(entry.getKey());
            }
        }
        for (Integer x : result) { 
            System.out.println(x);
        }

    }

1030 Got error 28 from storage engine

My /var/log/apache2 folder was 35g and some logs in /var/log totaled to be the other 5g of my 40g hard drive. I cleared out all the *.gz logs and after making sure the other logs werent going to do bad things if I messed with them, i just cleared them too.

echo "clear" > access.log

etc.

Purge Kafka Topic

The simplest approach is to set the date of the individual log files to be older than the retention period. Then the broker should clean them up and remove them for you within a few seconds. This offers several advantages:

  1. No need to bring down brokers, it's a runtime operation.
  2. Avoids the possibility of invalid offset exceptions (more on that below).

In my experience with Kafka 0.7.x, removing the log files and restarting the broker could lead to invalid offset exceptions for certain consumers. This would happen because the broker restarts the offsets at zero (in the absence of any existing log files), and a consumer that was previously consuming from the topic would reconnect to request a specific [once valid] offset. If this offset happens to fall outside the bounds of the new topic logs, then no harm and the consumer resumes at either the beginning or the end. But, if the offset falls within the bounds of the new topic logs, the broker attempts to fetch the message set but fails because the offset doesn't align to an actual message.

This could be mitigated by also clearing the consumer offsets in zookeeper for that topic. But if you don't need a virgin topic and just want to remove the existing contents, then simply 'touch'-ing a few topic logs is far easier and more reliable, than stopping brokers, deleting topic logs, and clearing certain zookeeper nodes.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

.NET Events - What are object sender & EventArgs e?

sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

Where is the default log location for SharePoint/MOSS?

For Sharepoint 2007

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

String representation of an Enum

I use a combination of several of the suggestions above, combined with some caching. Now, I got the idea from some code that I found somewhere on the net, but I can neither remember where I got it or find it. So if anyone ever finds something that looks similar please comment with the attribution.

Anyway, the usage involves the type converters, so if you are binding to the UI it 'just works'. You can extended with Jakub's pattern for quick code lookup by initializing from the type converter into the static methods.

The base usage would look like this

[TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
public enum MyEnum
{
    // The custom type converter will use the description attribute
    [Description("A custom description")]
    ValueWithCustomDescription,

   // This will be exposed exactly.
   Exact
}

The code for the custom enum type converter follows:

public class CustomEnumTypeConverter<T> : EnumConverter
    where T : struct
{
    private static readonly Dictionary<T,string> s_toString = 
      new Dictionary<T, string>();

    private static readonly Dictionary<string, T> s_toValue = 
      new Dictionary<string, T>();

    private static bool s_isInitialized;

    static CustomEnumTypeConverter()
    {
        System.Diagnostics.Debug.Assert(typeof(T).IsEnum,
          "The custom enum class must be used with an enum type.");
    }

    public CustomEnumTypeConverter() : base(typeof(T))
    {
        if (!s_isInitialized)
        {
            Initialize();
            s_isInitialized = true;
        }
    }

    protected void Initialize()
    {
        foreach (T item in Enum.GetValues(typeof(T)))
        {
            string description = GetDescription(item);
            s_toString[item] = description;
            s_toValue[description] = item;
        }
    }

    private static string GetDescription(T optionValue)
    {
        var optionDescription = optionValue.ToString();
        var optionInfo = typeof(T).GetField(optionDescription);
        if (Attribute.IsDefined(optionInfo, typeof(DescriptionAttribute)))
        {
            var attribute = 
              (DescriptionAttribute)Attribute.
                 GetCustomAttribute(optionInfo, typeof(DescriptionAttribute));
            return attribute.Description;
        }
        return optionDescription;
    }

    public override object ConvertTo(ITypeDescriptorContext context, 
       System.Globalization.CultureInfo culture, 
       object value, Type destinationType)
    {
        var optionValue = (T)value;

        if (destinationType == typeof(string) && 
            s_toString.ContainsKey(optionValue))
        {
            return s_toString[optionValue];
        }

        return base.ConvertTo(context, culture, value, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, 
       System.Globalization.CultureInfo culture, object value)
    {
        var stringValue = value as string;

        if (!string.IsNullOrEmpty(stringValue) && s_toValue.ContainsKey(stringValue))
        {
            return s_toValue[stringValue];
        }

        return base.ConvertFrom(context, culture, value);
    }
}

}

(grep) Regex to match non-ASCII characters?

I use [^\t\r\n\x20-\x7E]+ and that seems to be working fine.

Difference between RUN and CMD in a Dockerfile

RUN: Can be many, and it is used in build process, e.g. install multiple libraries

CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"], ["node", "app.js"])

R: invalid multibyte string

This happened to me because I had the 'copyright' symbol in one of my strings! Once it was removed, problem solved.

A good rule of thumb, make sure that characters not appearing on your keyboard are removed if you are seeing this error.

C# Set collection?

If you're using .NET 4.0 or later:

In the case where you need sorting then use SortedSet<T>. Otherwise if you don't, then use HashSet<T> since it's O(1) for search and manipulate operations. Whereas SortedSet<T> is O(log n) for search and manipulate operations.

adding css file with jquery

    var css_link = $("<link>", {
        rel: "stylesheet",
        type: "text/css",
        href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
    });
    css_link.appendTo('head');

Remove directory from remote repository after adding them to .gitignore

If you're working from PowerShell, try the following as a single command.

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

Then, git push --force --all.

Documentation: https://git-scm.com/docs/git-filter-branch

Java generics - why is "extends T" allowed but not "implements T"?

There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Find intersection of two nested lists?

You don't need to define intersection. It's already a first-class part of set.

>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

jQuery vs document.querySelectorAll

In terms of code maintainability, there are several reasons to stick with a widely used library.

One of the main ones is that they are well documented, and have communities such as ... say ... stackexchange, where help with the libraries can be found. With a custom coded library, you have the source code, and maybe a how-to document, unless the coder(s) spent more time documenting the code than writing it, which is vanishingly rare.

Writing your own library might work for you , but the intern sitting at the next desk may have an easier time getting up to speed with something like jQuery.

Call it network effect if you like. This isn't to say that the code will be superior in jQuery; just that the concise nature of the code makes it easier to grasp the overall structure for programmers of all skill levels, if only because there's more functional code visible at once in the file you are viewing. In this sense, 5 lines of code is better than 10.

To sum up, I see the main benefits of jQuery as being concise code, and ubiquity.

What is the default access modifier in Java?

It depends on the context.

When it's within a class:

class example1 {

    int a = 10; // This is package-private (visible within package)

    void method1() // This is package-private as well.
    {
        -----
    }
}

When it's within a interface:

interface example2 {

    int b = 10; // This is public and static.
    void method2(); // This is public and abstract
}

How do I put variables inside javascript strings?

I wrote a function which solves the problem precisely.

First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

Other arguments are the parameters respectively for that string.

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

Examples

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

If variable position changes in that string, this function supports it too without changing the function parameters.

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

How to disassemble a memory range with GDB?

fopen() is a C library function and so you won't see any syscall instructions in your code, just a regular function call. At some point, it does call open(2), but it does that via a trampoline. There is simply a jump to the VDSO page, which is provided by the kernel to every process. The VDSO then provides code to make the system call. On modern processors, the SYSCALL or SYSENTER instructions will be used, but you can also use INT 80h on x86 processors.

dplyr change many data types

Or mayby even more simple with convert from hablar:

library(hablar)

dat %>% 
  convert(fct(fac1, fac2, fac3),
          num(dbl1, dbl2, dbl3))

or combines with tidyselect:

dat %>% 
  convert(fct(contains("fac")),
          num(contains("dbl")))

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Getting a directory name from a filename

Just use this: ExtractFilePath(your_path_file_name)

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

How to add screenshot to READMEs in github repository?

I googled a few similar questions and did not see any answers with my problem and its quite simple/easy solution.

Google Cloud Storage - a slightly different approach to images in READMEs

Here goes: like the OP, I wanted an image in my Github README, and, knowing the Markdown syntax for doing so, typed it in:

![My Image](https://storage.cloud.google.com/${MY_BUCKET}/${MY_IMAGE}

You need to complete the actual substitutions above (e.g. MY_IMAGE=image.jpg) for this to work.

But, wait...failure--there's no actual rendered photo! And the link is exactly as given by Google Storage!

screenshot of failed Github image upload

Github camo - Anonymous Images

Github hosts your images anonymously, yay! However, this presents an issue for Google storage assets. You need to get the generated url from your Google Cloud Console.

I'm sure there's a smoother way, however, simply visit your given URL endpoint and copy the long URL. Details:

Instructions

  1. Visit your storage console: https://console.cloud.google.com/storage/browser/${MY_BUCKET}?project=${MY_PROJECT}
  2. Click on the image you'd like to display in Github (this brings up the "Object Details" page)
  3. Copy pasta that URL (the one starting with https not gs) into a new browser tab/window
  4. Copy pasta the new generated URL -- it should be longer -- from your new browser tab/window into your Github README file

Hopefully this helps speed up and clarify this issue for anyone else.

Android webview launches browser when calling loadurl

Answering my question based on the suggestions from Maudicus and Hit.

Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:

myWebView.setWebViewClient(new WebViewClient());

For more advanced processing for the web content, consider the ChromeClient.

Pie chart with jQuery

jqPlot looks pretty good and it is open source.

Here's a link to the most impressive and up-to-date jqPlot examples.

How to install a previous exact version of a NPM package?

You can use the following command to install a previous version of an npm package:

npm install packagename@version

MySQL: Grant **all** privileges on database

To access from remote server to mydb database only

GRANT ALL PRIVILEGES ON mydb.* TO 'root'@'192.168.2.21';

To access from remote server to all databases.

GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.2.21';

How do I import a .sql file in mysql database using PHP?

// Import data 
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);

function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
    $connection = mysqli_connect($host,$uname,$pass)
    or die("Database Connection Failed");
    $selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected"); 

$templine = '';
$lines = file($filename); // Read entire file

foreach ($lines as $line){
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
        continue;

        // Add this line to the current segment
        $templine .= $line;
        // If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';')
        {
            mysqli_query($connection, $templine)
            or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
            $templine = '';
        }
    }
    echo "Tables imported successfully";
}




// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');

function backup_tables($host,$user,$pass,$name,$tables = '*'){
    $link = mysqli_connect($host,$user,$pass);
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_select_db($link,$name);
    //get all of the tables
    if($tables == '*'){
        $tables = array();
        $result = mysqli_query($link,'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }else{
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    foreach($tables as $table)
    {
        $result = mysqli_query($link,'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
        $row2 = mysqli_fetch_row($row_query);
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysqli_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j < $num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n", '\n', $row[$j]);
                    if (isset($row[$j])) { 
                        $return.= '"'.$row[$j].'"' ; 
                    } else { 
                        $return.= '""'; 
                    }
                    if ($j < ($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

How to use linux command line ftp with a @ sign in my username?

As an alternative, if you don't want to create config files, do the unattended upload with curl instead of ftp:

curl -u user:password -T file ftp://server/dir/file

Twitter Bootstrap modal: How to remove Slide down effect

The following CSS works for me - Using Bootstrap 3. You need to add this css after boostrap styles -

.modal.fade .modal-dialog{
    -webkit-transition-property: transform; 
    -webkit-transition-duration:0 ; 
    transition-property: transform; 
    transition-duration:0 ; 
}

.modal.fade {
   transition: none; 
}

500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

What is the right way to write my script 'src' url for a local development environment?

I believe the browser is looking for those assets FROM the root of the webserver. This is difficult because it is easy to start developing on your machine WITHOUT actually using a webserver ( just by loading local files through your browser)

You could start by packaging your html and css/js together?

a directory structure something like:

-yourapp
  - index.html
  - assets
    - css
    - js
      - myPage.js

Then your script tag (from index.html) could look like

<script src="assets/js/myPage.js"></script>

An added benifit of packaging your html and assets in one directory is that you can copy the directory and give it to someone else or put it on another machine and it will work great.

No module named 'openpyxl' - Python 3.4 - Ubuntu

I still was not able to import 'openpyxl' after successfully installing it via both conda and pip. I discovered that it was installed in '/usr/lib/python3/dist-packages', so this https://stackoverflow.com/a/59861933/10794682 worked for me:

import sys 
sys.path.append('/usr/lib/python3/dist-packages')

Hope this might be useful for others.

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

Using 24 hour time in bootstrap timepicker

It looks like you have to set the option for the format with data-date-*. This example works for me with 24h support.

<div class="form-group">
    <div class="input-group date timepicker"
        data-date-format="HH:mm"
        data-date-useseconds="false"
        data-date-pickDate="false">

        <input type="text" name="" />
        <div class="input-group-addon">
            <i class="fa fa-clock-o"></i>
        </div>
    </div>
</div>

Calling a javascript function recursively

I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)

  var fn = (function() {
    var innerFn = function(counter) {
      console.log(counter);

      if(counter > 0) {
        innerFn(counter-1);
      }
    };

    return innerFn;
  })();

  console.log("running fn");
  fn(3);

  var copyFn = fn;

  console.log("running copyFn");
  copyFn(3);

  fn = function() { console.log("done"); };

  console.log("fn after reassignment");
  fn(3);

  console.log("copyFn after reassignment of fn");
  copyFn(3);

How can I convert a Timestamp into either Date or DateTime object?

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}

Possible heap pollution via varargs parameter

@SafeVarargs does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.

http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.

Heap pollution is when you get a ClassCastException when doing an operation on a generic interface and it contains another type than declared.