Programs & Examples On #Jquery ui button

The Button widget that forms part of the jQuery.UI library

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

What's the difference between %s and %d in Python string formatting?

%s is used as a placeholder for string values you want to inject into a formatted string.

%d is used as a placeholder for numeric or decimal values.

For example (for python 3)

print ('%s is %d years old' % ('Joe', 42))

Would output

Joe is 42 years old

How to get annotations of a member variable?

If you need know if a annotation specific is present. You can do so:

    Field[] fieldList = obj.getClass().getDeclaredFields();

        boolean isAnnotationNotNull, isAnnotationSize, isAnnotationNotEmpty;

        for (Field field : fieldList) {

            //Return the boolean value
            isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
            isAnnotationSize = field.isAnnotationPresent(Size.class);
            isAnnotationNotEmpty = field.isAnnotationPresent(NotEmpty.class);


And so on for the other annotations...

I hope help someone.

How to randomize two ArrayLists in the same fashion?

Instead of having two arrays of Strings, have one array of a custom class which contains your two strings.

How can I install a CPAN module into a local directory?

Other answers already on Stackoverflow:

From perlfaq8:

How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your configuration so modules automatically install in your private library directory when you use the shell:

% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

perl Build.PL --install_base /mydir/perl

You can configure to automatically use this option too:

% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

The "backspace" escape character '\b': unexpected behavior?

Use a single backspace after each character printf("hello wor\bl\bd\n");

How to embed a PDF?

This works perfectly and this is official html5.

<object data="https://link-to-pdf"></object>

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    public void onLocationChanged(final Location location) {
        //your code here

Then get the LocationManager and ask for location updates

protected void onCreate(Bundle savedInstanceState) {

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

how to set auto increment column with sql developer

If you want to make your PK auto increment, you need to set the ID column property for that primary key.

  1. Right click on the table and select "Edit".
  2. In "Edit" Table window, select "columns", and then select your PK column.
  3. Go to ID Column tab and select Column Sequence as Type. This will create a trigger and a sequence, and associate the sequence to primary key.

See the picture below for better understanding.

enter image description here

// My source is:

Switch statement fallthrough in C#?

A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.

-- C# switch() documentation

How can I exclude all "permission denied" messages from "find"?

While above approaches do not address the case for Mac OS X because Mac Os X does not support -readable switch this is how you can avoid 'Permission denied' errors in your output. This might help someone.

find / -type f -name "your_pattern" 2>/dev/null.

If you're using some other command with find, for example, to find the size of files of certain pattern in a directory 2>/dev/null would still work as shown below.

find . -type f -name "your_pattern" -exec du -ch {} + 2>/dev/null | grep total$.

This will return the total size of the files of a given pattern. Note the 2>/dev/null at the end of find command.

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

if its on a live server try this

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

then also make sure that the php version in your composer.json is the same as that of your server.

Check your php version in your terminal using php -v

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

Javascript: Unicode string to hex

A more up to date solution, for encoding:

// This is the same for all of the below, and
// you probably won't need it except for debugging
// in most cases.
function bytesToHex(bytes) {
  return Array.from(
    byte => byte.toString(16).padStart(2, "0")

// You almost certainly want UTF-8, which is
// now natively supported:
function stringToUTF8Bytes(string) {
  return new TextEncoder().encode(string);

// But you might want UTF-16 for some reason.
// .charCodeAt(index) will return the underlying
// UTF-16 code-units (not code-points!), so you
// just need to format them in whichever endian order you want.
function stringToUTF16Bytes(string, littleEndian) {
  const bytes = new Uint8Array(string.length * 2);
  // Using DataView is the only way to get a specific
  // endianness.
  const view = new DataView(bytes.buffer);
  for (let i = 0; i != string.length; i++) {
    view.setUint16(i, string.charCodeAt(i), littleEndian);
  return bytes;

// And you might want UTF-32 in even weirder cases.
// Fortunately, iterating a string gives the code
// points, which are identical to the UTF-32 encoding,
// though you still have the endianess issue.
function stringToUTF32Bytes(string, littleEndian) {
  const codepoints = Array.from(string, c => c.codePointAt(0));
  const bytes = new Uint8Array(codepoints.length * 4);
  // Using DataView is the only way to get a specific
  // endianness.
  const view = new DataView(bytes.buffer);
  for (let i = 0; i != codepoints.length; i++) {
    view.setUint32(i, codepoints[i], littleEndian);
  return bytes;


bytesToHex(stringToUTF8Bytes("hello ?? "))
// "68656c6c6f20e6bca2e5ad9720f09f918d"
bytesToHex(stringToUTF16Bytes("hello ?? ", false))
// "00680065006c006c006f00206f225b570020d83ddc4d"
bytesToHex(stringToUTF16Bytes("hello ?? ", true))
// "680065006c006c006f002000226f575b20003dd84ddc"
bytesToHex(stringToUTF32Bytes("hello ?? ", false))
// "00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"
bytesToHex(stringToUTF32Bytes("hello ?? ", true))
// "68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"

For decoding, it's generally a lot simpler, you just need:

function hexToBytes(hex) {
    const bytes = new Uint8Array(hex.length / 2);
    for (let i = 0; i !== bytes.length; i++) {
        bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
    return bytes;

then use the encoding parameter of TextDecoder:

// UTF-8 is default
new TextDecoder().decode(hexToBytes("68656c6c6f20e6bca2e5ad9720f09f918d"));
// but you can also use:
new TextDecoder("UTF-16LE").decode(hexToBytes("680065006c006c006f002000226f575b20003dd84ddc"))
new TextDecoder("UTF-16BE").decode(hexToBytes("00680065006c006c006f00206f225b570020d83ddc4d"));
// "hello ?? "

Here's the list of allowed encoding names:

You might notice UTF-32 is not on that list, which is a pain, so:

function bytesToStringUTF32(bytes, littleEndian) {
  const view = new DataView(bytes.buffer);
  const codepoints = new Uint32Array(view.byteLength / 4);
  for (let i = 0; i !== codepoints.length; i++) {
    codepoints[i] = view.getUint32(i * 4, littleEndian);
  return String.fromCodePoint(...codepoints);


bytesToStringUTF32(hexToBytes("00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"), false)
bytesToStringUTF32(hexToBytes("68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"), true)
// "hello ?? "

How to use LINQ Distinct() with multiple fields

Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };

List<Employee> lstEmployee = new List<Employee>();


var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();

Adding a dictionary to another

The most obvious way is:

foreach(var kvp in NewAnimals)
   Animals.Add(kvp.Key, kvp.Value); 
  //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue

Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;

foreach(var kvp in NewAnimals)

It's a pity the class doesn't have anAddRangemethod likeList<T> does.

Obtain smallest value from array in Javascript?

Here is code that will detect the lowest value in an array of numbers.

//function for finding smallest value in an array
function arrayMin(array){
    var min = array[0];
    for(var i = 0; i < array.length; i++){
        if(min < array[i]){
            min = min;
        }else if (min > array[i]){
            min = array[i + 1];
        }else if (min == array[i]){
            min = min;
    return min;

call it in this way:

var fooArray = [1,10,5,2];
var foo = arrayMin(fooArray);

(Just change the second else if result from: min = min to min = array[i] if you want numbers which reach the smallest value to replace the original number.)

How to check whether a Storage item is set?


localStorage.infiniteScrollEnabled = 1;




if (localStorage[""infiniteScrollEnabled""]) {

Find a row in dataGridView based on column and value

This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.

public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
        int rowIndex = -1;
        bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;

        dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
        if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
            DataGridViewRow row = dgv.Rows
                .FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));

            rowIndex = row.Index;
        dgv.AllowUserToAddRows = tempAllowUserToAddRows;
        return rowIndex;

Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.

private void UndeleteSectionInGrid(string sectionLetter)
        int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
        dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;

How do I trap ctrl-c (SIGINT) in a C# console app

Here is a complete working example. paste into empty C# console project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC {
    public class Program {
        static bool exitSystem = false;

        #region Trap application termination
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
            exitSystem = true;

            //shutdown right away so there are no lingering threads

            return true;

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();

            //hold the console so it doesn’t run off the end
            while (!exitSystem) {

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");

post checkbox value

You should use

<input type="submit" value="submit" />

inside your form.

and add action into your form tag for example:

<form action="booking.php" method="post">

It's post your form into action which you choose.

From php you can get this value by


Differences between ConstraintLayout and RelativeLayout

Relative Layout and Constraint Layout equivalent properties

Relative Layout and Constraint Layout equivalent properties

(1) Relative Layout:


(1) Constraint Layout equivalent :


(2) Relative Layout:


(2) Constraint Layout equivalent:


(3) Relative Layout:


(3) Constraint Layout equivalent:


(4) Relative Layout:


(4) Constraint Layout equivalent:


(5) Relative Layout:


(5) Constraint Layout equivalent:


(6) Relative Layout:


(6) Constraint Layout equivalent:


(7) Relative Layout:


(7) Constraint Layout equivalent:


(8) Relative Layout:


(8) Constraint Layout equivalent:


(9) Relative Layout:


(9) Constraint Layout equivalent:


(10) Relative Layout:


(10) Constraint Layout equivalent:


(11) Relative Layout:


(11) Constraint Layout equivalent:


(12) Relative Layout:


(12) Constraint Layout equivalent:


(13) Relative Layout:


(13) Constraint Layout equivalent:


(14) Relative Layout:


(14) Constraint Layout equivalent:


(15) Relative Layout:


(15) Constraint Layout equivalent:


(16) Relative Layout:


(16) Constraint Layout equivalent:


(17) Relative Layout:


(17) Constraint Layout equivalent:


(18) Relative Layout:


(18) Constraint Layout equivalent:


(19) Relative Layout:


(19) Constraint Layout equivalent:


(20) Relative Layout:


(20) Constraint Layout equivalent:


(21) Relative Layout:


(21) Constraint Layout equivalent:


(22) Relative Layout:


(22) Constraint Layout equivalent:


Remove last specific character in a string c#

When you have spaces at the end. you can use beliow.

ProcessStr = ProcessStr.Replace(" ", "");
Emails     = ProcessStr.TrimEnd(';');

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

Targeting only Firefox with CSS

The only way to do this is via various CSS hacks, which will make your page much more likely to fail on the next browser updates. If anything, it will be LESS safe than using a js-browser sniffer.

How can I filter a date of a DateTimeField in Django?

Model.objects.filter(datetime__year=2011, datetime__month=2, datetime__day=30)

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

error (Cannot resolve the collation conflict between .... ) usually occurs while comparing data from multiple databases.

since you cannot change the collation of databases now, use COLLATE DATABASE_DEFAULT.


List submodules in a Git repository

To return just the names of the registered submodules, you can use this command:

grep path .gitmodules | sed 's/.*= //'

Think of it as git submodule --list which doesn't exist.

Add a border outside of a UIView (instead of inside)

Swift 5

extension UIView {
    fileprivate struct Constants {
        static let externalBorderName = "externalBorder"

    func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) -> CALayer {
        let externalBorder = CALayer()
        externalBorder.frame = CGRect(x: -borderWidth, y: -borderWidth, width: frame.size.width + 2 * borderWidth, height: frame.size.height + 2 * borderWidth)
        externalBorder.borderColor = borderColor.cgColor
        externalBorder.borderWidth = borderWidth = Constants.ExternalBorderName

        layer.insertSublayer(externalBorder, at: 0)
        layer.masksToBounds = false

        return externalBorder

    func removeExternalBorders() {
        layer.sublayers?.filter() { $ == Constants.externalBorderName }.forEach() {

    func removeExternalBorder(externalBorder: CALayer) {
        guard == Constants.externalBorderName else { return }


The documentation for START_STICKY and START_NOT_STICKY is quite straightforward.


If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Example: Local Service Sample


If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.


anaconda - path environment variable in windows

In windows 10 you can find it here:


Hibernate Union alternatives

A view is a better approach but since hql typically returns a List or Set... you can do list_1.addAll(list_2). Totally sucks compared to a union but should work.

Django Template Variables and Javascript

For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.

How to colorize diff on the command line?

diff --color option was added to GNU diffutils 3.4 (2016-08-08)

This is the default diff implementation on most distros, which will soon be getting it.

Ubuntu 18.04 has diffutils 3.6 and therefore has it.

On 3.5 it looks like this:

enter image description here

Tested with:

diff --color -u \
  <(seq 6 | sed 's/$/ a/') \
  <(seq 8 | grep -Ev '^(2|3)$' | sed 's/$/ a/')

Apparently added in commit c0fa19fe92da71404f809aafb5f51cfd99b1bee2 (Mar 2015).

Word-level diff

Like diff-highlight. Not possible it seems, feature request:

Related threads:

ydiff does it though, see below.

ydiff side-by-side word level diff

Is this Nirvana?

python3 -m pip install --user ydiff
diff -u a b | ydiff -s


enter image description here

If the lines are too narrow (default 80 columns), fit to screen with:

diff -u a b | ydiff -w 0 -s

Contents of the test files:


5 the original line the original line the original line the original line
15 the original line the original line the original line the original line


5 the original line teh original line the original line the original line
15 the original line the original line the original line the origlnal line

ydiff Git integration

ydiff integrates with Git without any configuration required.

From inside a git repository, instead of git diff, you can do just:

ydiff -s

and instead of git log:

ydiff -ls

See also: How can I get a side-by-side diff when I do "git diff"?

Tested on Ubuntu 16.04, git 2.18.0, ydiff 1.1.

Understanding implicit in Scala

I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).

There are two common use cases in Scala using implicit.

  • Using it on a variable
  • Using it on a function

Examples are as follows

Using it on a variable. As you can see, if the implicit keyword is used in the last parameter list, then the closest variable will be used.

// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")

// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
  case Person(name: String) if name != "" => s"$name, $words"
    case _ => "$words"

greeting("Good morning") // Charles, Good moring

val charles: Person = Person("")
greeting("Good morning") // Good moring

Using it on a function. As you can see, if the implicit is used on the function, then the closest type conversion method will be used.

val num = 10 // num: Int (of course)

// Here I define a implicit function
implicit def intToString(num: Int) = s"$num -- I am a String now!"

val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int

// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!

Hope this can help.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B

Installing Oracle Instant Client

I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.

Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)

Oracle Instant Client

  • Unzip Oracle Instant Client - Basic
  • Put contents in folder like "C:\instantclient"
  • Edit PATH evironment variable, add path to Instant Client folder to the Variable Value.
  • Add new Variable called "TNS_ADMIN" point to same folder as Instant Client.
  • I had to create a "tnsnames.ora" file because it doesn't come with one. Put it in same folder as the client.
  • reboot or use Task Manager to kill "explorer.exe" and restart it to refresh the PATH environment variables.

ODBC Drivers

  • Unzip ODBC drivers
  • Copy all files into same folder as client "C:\instantclient"
  • Use command prompt to run "odbc_install.exe" (should say it was successful)

Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.

After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences


Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:


This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:


Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

How can I convert a comma-separated string to an array?

You can try the following snippet:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

How can I convert integer into float in Java?

You just need to cast at least one of the operands to a float:

float z = (float) x / y;


float z = x / (float) y;

or (unnecessary)

float z = (float) x / (float) y;

Formatting a number with exactly two decimals in JavaScript

Put the following in some global scope:

Number.prototype.getDecimals = function ( decDigCount ) {
   return this.toFixed(decDigCount);

and then try:

var a = 56.23232323;
a.getDecimals(2); // will return 56.23


Note that toFixed() can only work for the number of decimals between 0-20 i.e. a.getDecimals(25) may generate a javascript error, so to accomodate that you may add some additional check i.e.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);

Is Constructor Overriding Possible?

method overriding in java is used to improve the recent code performance written previously .

some code like shows that here we are creating reference of base class and creating phyisical instance of the derived class. in constructors overloading is possible.

InputStream fis=new FileInputStream("a.txt");
int size=fis.available();

size will return the total number of bytes possible in a.txt so

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

Stop setInterval call in JavaScript

Why not use a simpler approach? Add a class!

Simply add a class that tells the interval not to do anything. For example: on hover.

var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
}, 500);_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
  },function() { //mouse leave_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src=""></script>_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause</button></p>

I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

Get the new record primary key ID from MySQL insert query?

From the LAST_INSERT_ID() documentation:

The ID that was generated is maintained in the server on a per-connection basis

That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

Options (Query Results/SQL Server/Results to Grid Page)

To change the options for the current queries, click Query Options on the Query menu, or right-click in the SQL Server Query window and select Query Options.


Maximum Characters Retrieved
Enter a number from 1 through 65535 to specify the maximum number of characters that will be displayed in each cell.

Maximum is, as you see, 64k. The default is much smaller.

BTW Results to Text has even more drastic limitation:

Maximum number of characters displayed in each column
This value defaults to 256. Increase this value to display larger result sets without truncation. The maximum value is 8,192.

malloc an array of struct pointers

I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.

The code uses the ms visual studio leak detector so you can experiment with the potential leaks.

#include "stdafx.h"

#include <string.h>
#include "msc-lzw.h"

#include <stdlib.h>
#include <crtdbg.h> 

// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
    return (key + try_num) % max;  // the hash fun returns a number bounded by the number of slots.

// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
    int key; // use this field as the key
    char *pValue;  // use this field to store a variable length string

struct hash_table {
    int max;
    int number_of_elements;
    struct key_value_pair **elements;  // This is an array of pointers to mystruct objects

int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {

    int try_num, hash;
    int max_number_of_retries = hash_table->max;

    if (hash_table->number_of_elements >= hash_table->max) {
        return 0; // FULL

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(data->key, try_num, hash_table->max);

        if (NULL == hash_table->elements[hash]) { // an unallocated slot
            hash_table->elements[hash] = data;
            return RC_OK;
    return RC_ERROR;

// returns the corresponding key value pair struct
// If a value is not found, it returns null
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {

    unsigned int try_num, hash;
    unsigned int max_number_of_retries = hash_table->max;

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(key, try_num, hash_table->max);

        if (hash_table->elements[hash] == 0) {
            return NULL; // Nothing found

        if (hash_table->elements[hash]->key == key) {
            return hash_table->elements[hash];
    return NULL;

// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter.  It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {

    int num_keys = 0;

    *ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );

    for (int i = 0; i < pHashTable->max; i++) {
        if (NULL != pHashTable->elements[i]) {
            (*ppKeys)[num_keys] = pHashTable->elements[i]->key;
    return num_keys;

// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {

    // Allocate the hash table slots
    pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair));  // allocate max number of key_value_pair entries
    for (int i = 0; i < pHashTable->max; i++) {
        pHashTable->elements[i] = NULL;

    // alloc all the slots
    //struct key_value_pair *pa_slot;
    //for (int i = 0; i < pHashTable->max; i++) {
    //  // all that he could see was babylon
    //  pa_slot = (struct key_value_pair *)  malloc(sizeof(struct key_value_pair));
    //  if (NULL == pa_slot) {
    //      printf("alloc of slot failed\n");
    //      while (1);
    //  }
    //  pHashTable->elements[i] = pa_slot;
    //  pHashTable->elements[i]->key = 0;

    return RC_OK;

// This will make a dictionary entry where
//   o  key is an int
//   o  value is a character buffer
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {

    // determine the len of the buffer assuming it is a string
    int len = strlen(buffer);

    // alloc the buffer to hold the string
    pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
    if (NULL == pMyStruct->pValue) {
        printf("Failed to allocate the buffer for the dictionary string value.");
        return RC_ERROR;
    strcpy(pMyStruct->pValue, buffer);
    pMyStruct->key = a_key;

    return RC_OK;

// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {

    int rc;
    struct key_value_pair *pKeyValuePair;

    if (NULL == pHashTable) {
        printf("Hash table is null.\n");
        return RC_ERROR;

    // Allocate the dictionary key value pair struct
    pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
    if (NULL == pKeyValuePair) {
        printf("Failed to allocate key value pair struct.\n");
        return RC_ERROR;

    rc = make_dict_entry(key, pBuff, pKeyValuePair);  // a_hash_table[1221] = "abba"
    if (RC_ERROR == rc) {
        printf("Failed to add buff to key value pair struct.\n");
        return RC_ERROR;

    rc = hash_insert(pKeyValuePair, pHashTable);
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;

    return RC_OK;

void dump_hash_table(struct hash_table *pHashTable) {

    // Iterate the dictionary by keys
    char * pValue;
    struct key_value_pair *pMyStruct;
    int *pKeyList;
    int num_keys;

    num_keys = keys(pHashTable, &pKeyList);
    for (int i = 0; i < num_keys; i++) {
        pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
        pValue = pMyStruct->pValue;
        printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);

    // Free the key list


int main(int argc, char *argv[]) {

    int rc;
    int i;

    struct hash_table a_hash_table;
    a_hash_table.max = 20;   // The dictionary can hold at most 20 entries.
    a_hash_table.number_of_elements = 0;  // The intial dictionary has 0 entries.

    rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;

    // Iterate the dictionary by keys

    // Free the individual slots
    for (i = 0; i < a_hash_table.max; i++) {
        // all that he could see was babylon
        if (NULL != a_hash_table.elements[i]) {
            free(a_hash_table.elements[i]->pValue);  // free the buffer in the struct
            free(a_hash_table.elements[i]);  // free the key_value_pair entry
            a_hash_table.elements[i] = NULL;

    // Free the overall dictionary

    return 0;

What does it mean to write to stdout in C?

@K Scott Piel wrote a great answer here, but I want to add one important point.

Note that the stdout stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf statement with a \n


printf("hello world\n");


printf("hello world"); 

or similar, OR you must call fflush(stdout); after your printf call.


printf("hello world"); 

Read more here: Why does printf not flush after the call unless a newline is in the format string?

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

I had this same error in an MVC 4 application using Razor. In an attempt to clean up the web.config files, I removed the two webpages: configuration values:

  <add key="webpages:Version" value="" />
  <add key="webpages:Enabled" value="false" />

Once I restored these configuration values, the pages would compile correctly and the errors regarding the .Partial() extension method disappeared.

Internal vs. Private Access Modifiers

internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)

private is for class scope (i.e. accessible only from code in the same class).

Any tools to generate an XSD schema from an XML instance document?

if you are working in the java world - intelliJ idea has also extensive xml support, including xsd generation and samle xml from xsd generation, and with plugins you can get xslt debuggers. - especially nice if you plan to use tools such as jaxb afterwards.

How to prevent column break within an element?

This answer might only apply to certain circumstances; If you set a height to your elements, this will be obeyed by the column styling. There-by keeping anything that is contained within that height to a row.

I had a list, like the op, but it contained two elements, items and buttons to act upon those items. I treated it like a table <ul> - table, <li> - table-row, <div> - table-cell put the UL in a 4 column layout. The columns were sometimes being split between the item and it's buttons. The trick I used was to give the Div elements a line height to cover the buttons.

Found shared references to a collection org.hibernate.HibernateException

I faced similar exception in my application. After looking into the stacktrace it was clear that exception was thrown within a FlushEntityEventListener class.

In Hibernate 4.3.7 the MSLocalSessionFactory bean no longer supports the eventListeners property. Hence, one has to explicitly fetch the service registry from individual Hibernate session beans and then set the required custom event listeners.

In the process of adding custom event listeners we need to make sure the corresponding default event listeners are removed from the respective Hibernate session.

If the default event listener is not removed then the case arises of two event listeners registered against same event. In this case while iterating over these listeners, against first listeners any collections in the session will be flagged as reached and while processing the same collection against second listener would throw this Hibernate exception.

So, make sure that when registering custom listeners corresponding default listeners are removed from registry.

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

enum MyEnum

int main()
 printf("My enum Value : %d\n", (int)C_ENUM_VALUE);
 return 0;

You have just to cast enum to int !
Output : My enum Value : 2

Rounded corner for textview in android

Simply using an rounded corner image as the background of that view

And don't forget to have your custom image in drawable folder


Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>


// authentication servlet class

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {


        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
            } catch (ClassNotFoundException e) {

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while ( {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");

            } catch (SQLException e) {



A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

It requires GNU Octave, which is highly compatible with MATLAB.

Django gives Bad Request (400) when DEBUG = False

For me, I got this error by not setting USE_X_FORWARDED_HOST to true. From the docs:

This should only be enabled if a proxy which sets this header is in use.

My hosting service wrote explicitly in their documentation that this setting must be used, and I get this 400 error if I forget it.

Getting started with OpenCV 2.4 and MinGW on Windows 7

As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.

HTML Display Current date

This helped me:

<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.


<div id="header">
<div id="content">
<div id="footer">


#header {
    height: 30px;
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
body {
    height: 100%;
    margin-bottom: 30px;

Try it on jsfiddle:

Which HTTP methods match up to which CRUD methods?

It depends on the concrete situation.. but in general:

PUT = update or change a concrete resource with a concrete URI of the resource.

POST = create a new resource under the source of the given URI.


Edit a blog post:

PUT: /blog/entry/1

Create a new one:

POST: /blog/entry

PUT may create a new resource in some circumstances where the URI of the new ressource is clear before the request. POST can be used to implement several other use cases, too, which are not covered by the others (GET, PUT, DELETE, HEAD, OPTIONS)

The general understanding for CRUD systems is GET = request, POST = create, Put = update, DELETE = delete

No resource found that matches the given name '@style/Theme.AppCompat.Light'

If you are looking for the solution in Android Studio :

  1. Right click on your app
  2. Open Module Settings
  3. Select Dependencies tab
  4. Click on green + symbol which is on the right side
  5. Select Library Dependency
  6. Choose appcompat-v7 from list

When creating a service with sc.exe how to pass in context parameters?

I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

{sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

I was getting this same warning everytime I was doing 'maven clean'. I found the solution :

Step - 1 Right click on your project in Eclipse

Step - 2 Click Properties

Step - 3 Select Maven in the left hand side list.

Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.

Below is the screen shot :

Properties dialog box

Hope this helps. :)

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Using = causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:

HELLO = world

# This echoes "world world!"

HELLO = hello

# This echoes "hello world!"

Using := is similar to using =. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:

HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"

HELLO = hello

# Still echoes "world world!"

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"

Using ?= assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=), it is still considered set I think. Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=, it is expanded I think. The resulting value is expanded when it is used I think. For example:

HELLO_WORLD += world!

# This echoes "hello world!"

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

Add swipe to delete UITableViewCell

Swift 4 -- @available(iOS 11.0, *)

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let edit = UIContextualAction(style: .normal, title: "") { (action, view, nil) in
        let refreshAlert = UIAlertController(title: "Deletion", message: "Are you sure you want to remove this item from cart? ", preferredStyle: .alert)

        refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in


        refreshAlert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismiss(animated: true, completion: nil)

        self.present(refreshAlert, animated: true, completion: nil)
    edit.backgroundColor = #colorLiteral(red: 0.3215686275, green: 0.5960784314, blue: 0.2470588235, alpha: 1)
    edit.image = #imageLiteral(resourceName: "storyDelete")
    let config = UISwipeActionsConfiguration(actions: [edit])
    config.performsFirstActionWithFullSwipe = false
    return config

How can I set the current working directory to the directory of the script in Bash?

I take this and it works.

cd "$(dirname "$0")"

How To Show And Hide Input Fields Based On Radio Button Selection

Replace all instances of visibility style to display

display:none //to hide
display:block //to show

Here's updated jsfiddle:

You can do it using Mootools or jQuery functions to slide up/down but if you don't need animation effect it's probably too much for what you need.

CSS display is a faster and simpler approach.

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I fixed the problem with deleting .vs folder on project folder.

  • Close VS projects.
  • Delete .vs folder on project folder that includes applicationhost.config file.

VS will generate new config for this project.

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I recommend setting an alternative location for your npm modules.

npm config set prefix C:\Dev\npm-repository\npm --global 
npm config set cache C:\Dev\npm-repository\npm-cache --global  

Of course you can set the location to wherever best suits.

This has worked well for me and gets around any permissions issues that you may encounter.

RichTextBox (WPF) does not have string property "Text"

Using two extension methods, this becomes very easy:

public static class Ext
    public static void SetText(this RichTextBox richTextBox, string text)
        richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));

    public static string GetText(this RichTextBox richTextBox)
        return new TextRange(richTextBox.Document.ContentStart,

How to set opacity in parent div and not affect in child div?

As mentioned by Tom, background-color: rgba(229,229,229, 0.85) can do the trick. Place that on the style of the parent element and child wont be affected.

How do you validate a URL with a regular expression in Python?

The regex provided should match any url of the form; and does when tested in the python interpreter.

What format have the URLs you've been having trouble parsing had?

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.

Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Spring Boot - Handle to Hibernate SessionFactory

It works with Spring Boot 2.1.0 and Hibernate 5

private EntityManager entityManager;

Then you can create new Session by using entityManager.unwrap(Session.class)

Session session = null;
if (entityManager == null
    || (session = entityManager.unwrap(Session.class)) == null) {

    throw new NullPointerException();

example create query:

session.createQuery("FROM Student");

spring.datasource.password=admin spring.jpa.hibernate.ddl-auto=create-drop

How to change the Spyder editor background to dark?

I want to add that you can change the theme of Spyder 3 to a dark on Linux by using:


Install Qtmodern with pip3

pip3 install --user qtmodern

Open the file:


Import modern style


# Qt imports


import qtmodern.styles

Theme the app

Find method:

def run_spyder(


#wrapper for custom theme

Theme the window


Replace it with:

##wrapper for dark window theme
mw =

Creating a very simple linked list

A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.

This chain will continue up to any node doesn't have a reference point to the next node.

Please find the source code from my tech blog -

package info.algonuts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class LLNode {
    int nodeValue;
    LLNode childNode;

    public LLNode(int nodeValue) {
        this.nodeValue = nodeValue;
        this.childNode = null;

class LLCompute {
    private static LLNode temp;
    private static LLNode previousNode;
    private static LLNode newNode;
    private static LLNode headNode;

    public static void add(int nodeValue) {
        newNode = new LLNode(nodeValue);
        temp = headNode;
        previousNode = temp;
        if(temp != null)
        {   compute();  }
        {   headNode = newNode; }   //Set headNode

    private static void compute() {
        if(newNode.nodeValue < temp.nodeValue) {    //Sorting - Ascending Order
            newNode.childNode = temp;
            if(temp == headNode) 
            {   headNode = newNode; }
            else if(previousNode != null) 
            {   previousNode.childNode = newNode;   }
            if(temp.childNode == null)
            {   temp.childNode = newNode;   }
                previousNode = temp;
                temp = temp.childNode;

    public static void display() {
        temp = headNode;
        while(temp != null) {
            System.out.print(temp.nodeValue+" ");
            temp = temp.childNode;

public class LinkedList {
    //Entry Point
    public static void main(String[] args) {
        //First Set Input Values
        List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));   
        Iterator<Integer> ptr  = firstIntList.iterator();
        {   LLCompute.add(;  }
        System.out.println("Sort with first Set Values");

        //Second Set Input Values
        List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));   
        ptr  = secondIntList.iterator();
        {   LLCompute.add(;  }
        System.out.println("Sort with first & Second Set Values");

Convert a python dict to a string and back

Use the pickle module to save it to disk and load later on.

CSS content property: is it possible to insert HTML instead of Text?

In CSS3 paged media this is possible using position: running() and content: element().

Example from the CSS Generated Content for Paged Media Module draft:

@top-center {
  content: element(heading); 

.runner { 
  position: running(heading);

.runner can be any element and heading is an arbitrary name for the slot.

EDIT: to clarify, there is basically no browser support so this was mostly meant to be for future reference/in addition to the 'practical answers' given already.

Node.js project naming conventions for files & folders

Most people use camelCase in JS. If you want to open-source anything, I suggest you to use this one :-)

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

Default value of function parameter

Default arguments must be specified with the first occurrence of the function name—typically, in the function prototype. If the function prototype is omitted because the function definition also serves as the prototype, then the default arguments should be specified in the function header.

Select elements by attribute in CSS

You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href based on their values with CSS only..

Attributes selectors allows you play around some extra with id and class attributes

Here is an awesome read on Attribute Selectors


a[href=""][title="Aamir"] {_x000D_
  color: green;_x000D_
  text-decoration: none;_x000D_
a[id*="google"] {_x000D_
  color: red;_x000D_
a[class*="stack"] {_x000D_
  color: yellow;_x000D_
<a href="" title="Aamir">Aamir</a>_x000D_
<a href="" id="google-link" title="Google">Google</a>_x000D_
<a href="" class="stack-link" title="stack">stack</a>

Browser support:
IE6+, Chrome, Firefox & Safari

You can check detail here.

Git commit date

The show command may be what you want. Try

git show -s --format=%ci <commit>

Other formats for the date string are available as well. Check the manual page for details.

Requested registry access is not allowed

This issue has to do with granting the necessary authorization to the user account the application runs on. To read a similar situation and a detailed response for the correct solution, as documented by Microsoft, feel free to visit this post:

clear table jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();

Get the list of stored procedures created and / or modified on a particular date?

SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

MS SQL Date Only Without Time

If you're using SQL Server 2008 it has this built in now, see this in books online


get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

How to check if an Object is a Collection Type in Java?

Test if the object implements either java.util.Collection or java.util.Map. (Map has to be tested separately because it isn't a sub-interface of Collection.)

Eclipse reports rendering library more recent than ADT plug-in

Change android version while rendering layout.

enter image description here

Change in API version 18 to 17 work for me.

Edit: Solution worked for Android Studio too.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

enter image description here

Demo: enter image description here

How do I add slashes to a string in Javascript?

Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

function addslashes(string) {
    return string.replace(/\\/g, '\\\\').
        replace(/\u0008/g, '\\b').
        replace(/\t/g, '\\t').
        replace(/\n/g, '\\n').
        replace(/\f/g, '\\f').
        replace(/\r/g, '\\r').
        replace(/'/g, '\\\'').
        replace(/"/g, '\\"');

windows batch file rename

as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "


ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps

CSS - Syntax to select a class within an id

.navigationLevel2 li { color: #aa0000 }

move a virtual machine from one vCenter to another vCenter

Copying the VM files onto an external HDD and then bringing it in to the destination will take a lot longer and requires multiple steps. Using vCenter Converter Standalone Client will do everything for you and is much faster. No external HDD required. Not sure where you got the cloning part from. vCenter Converter Standalone Client is simply copying the VM files by importing and exporting from source to destination, shutdown the source VM, then register the VM at destination and power on. All in one step. Takes about 1 min to set that up vCenter Converter Standalone Client.

Redirect in Spring MVC

Try this, it should work if you have configured your view resolver properly

 return "redirect:/index.html";

Why do we need to use flatMap?

When I started to have a look at Rxjs I also stumbled on that stone. What helped me is the following:

  • documentation from . For instance, for flatMap:
  • documentation from rxmarbles : You will not find flatMap there, you must look at mergeMap instead (another name).
  • the introduction to Rx that you have been missing: It addresses a very similar example. In particular it addresses the fact that a promise is akin to an observable emitting only one value.
  • finally looking at the type information from RxJava. Javascript not being typed does not help here. Basically if Observable<T> denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable<T> as its argument, and returns Observable<T>. map takes a function of type T' -> T and returns Observable<T>.

    Going back to your example, you have a function which produces promises from an url string. So T' : string, and T : promise. And from what we said before promise : Observable<T''>, so T : Observable<T''>, with T'' : html. If you put that promise producing function in map, you get Observable<Observable<T''>> when what you want is Observable<T''>: you want the observable to emit the html values. flatMap is called like that because it flattens (removes an observable layer) the result from map. Depending on your background, this might be chinese to you, but everything became crystal clear to me with typing info and the drawing from here:

Timing a command's execution in PowerShell

Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.


'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".

Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.

As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.

The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!

Let presume that you dot-source your . .\Dosomething.ps1 command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command):

$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}

(Measure-Command {
    $PowerShell = $Data.Where{$_.Index -eq 12345}

(Measure-Command {
    $Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})

The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...

Let's display the results:

PS C:\> $PowerShell

Index  Property
-----  --------
12345 104123841

PS C:\> $Linq

Index  Property
-----  --------
12345 104123841

As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq results then the $PowerShell results.
Let's specifically measure that by just retrieving a property of the resulted object:

PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds

It took about a factor 90 longer to retrieve a property of the $Linq object then the $PowerShell object and that was just a single object!

Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.

Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.

(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle

Is not required for packages in Python 3.3+

I would say that one should omit the only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the even in Python 3.

GoogleTest: How to skip a test?

For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

#include <gtest/gtest.h>

const bool skip_some_test = true;

bool some_test_was_run = false;

void someTest() {
   some_test_was_run = true;

TEST(BasicTest, Sanity) {
   EXPECT_EQ(1, 1);
   if(!skip_some_test) {

This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

For windows you can do it like

"scripts": {
    "start:prod" : "SET NODE_ENV=production & nodemon app.js",
    "start:dev" : "SET NODE_ENV=development & nodemon app.js"

Laravel stylesheets and javascript don't load for non-base routes

If you're using Laravel 3 and your CSS/JS files inside public folder like this


then you can call them using in Blade templates like this

{{ HTML::style('css/style.css'); }}
{{ HTML::script('js/jquery-1.8.2.min.js'); }}

Apply formula to the entire column

It looks like some of the other answers have become outdated, but for me this worked:

  1. Click on the cell with the text/formula to copy
  2. Shift+Click on the last cell to copy to
  3. Ctrl + Enter

(Note that this replaces text if the destination cells aren't empty)

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

Safest way to get last record ID from a table

I think this one will also work:


Stop a gif animation onload, on mouseover start the activation

Related answer, you can specify the number of playbacks on a gif. The below gif has 3 playbacks associated with it (10 second timer, 30 second playback total). After 30 seconds have passed since page load, it stops at "0:01".

Refresh the page to restart all 3 playbacks

You have to modify the gif itself. An easy tool is found here for modifying GIF playbacks

To see an example of a single-loop playback gif in action on a landing page, checkout this site using a single playback gif

enter image description here

Accessing Redux state in an action creator?

I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.

In the reducer do something like:

const state = this.state;
const apple = this.state.apples;

If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.

Please correct me if I'm wrong!!!

Getting all selected checkboxes in an array

here is my code for the same problem someone can also try this. jquery

var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3


It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.


console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
.as-console-wrapper {max-height: 100% !important;top: 0;}

What is boilerplate code?

In practical terms, boilerplate code is the stuff you cut-n-paste all over the place. Often it'll be things like a module header, plus some standard/required declarations (every module must declare a logger, every module must declare variables for its name and revision, etc.) On my current project, we're writing message handlers and they all have the same structure (read a message, validate it, process it) and to eliminate dependencies among the handlers we didn't want to have them all inherit from a base class, so we came up with a boilerplate skeleton. It declared all the routine variables, the standard methods, exception handling framework — all a developer had to do was add the code specific to the message being handled. It would have been quick & easy to use, but then we found out we were getting our message definitions in a spreadsheet (which used a boilerplate format), so we wound up just writing a code generator to emit 90% of the code (including the unit tests).

Missing maven .m2 folder

If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,

mvn help:evaluate -Dexpression=settings.localRepository

The above command will scan for projects and run some tasks. Final outcome will be like below

enter image description here

As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository

_csv.Error: field larger than field limit (131072)

.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):

Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.

It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:

>>> import csv
>>> limit0 = csv.field_size_limit()
>>> limit0
>>> "0x{0:016X}".format(limit0)

However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).

Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:

  • Nix: 64
  • Win: 32

When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):

>>> import sys, ctypes as ct
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('win32', 9223372036854775807, 64, 32)
>>> csv.field_size_limit(sys.maxsize)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.

>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
>>> limit1 = csv.field_size_limit()
>>> limit1
>>> "0x{0:016X}".format(limit1)

64bit Python on a Nix like OS:

>>> import sys, csv, ctypes as ct
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('linux', 9223372036854775807, 64, 64)
>>> csv.field_size_limit()
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
>>> limit1 = csv.field_size_limit()
>>> limit1
>>> "0x{0:016X}".format(limit1)

For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.

Check the following resources for more details on:

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

Finding the id of a parent div using Jquery

This can be easily done by doing:


You attach this to any object inside a table and it will return you the id of that table.

Allowing Untrusted SSL Certificates with HttpClient

I found an example online which seems to work well:

First you create a new ICertificatePolicy

using System.Security.Cryptography.X509Certificates;
using System.Net;

public class MyPolicy : ICertificatePolicy
  public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, 
int certificateProblem)
    //Return True to force the certificate to be accepted.
    return true;

Then just use this prior to sending your http request like so:

System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 ( or and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do


...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:


Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    constructor(...args) {
        this.state = {data: null};
    componentDidMount() {
        if (! {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
    render() {
        return (
                { ? <em>Loading...</em> :}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    constructor(...args) {
        this.state = {data: null};
    componentDidMount() {
        if (! {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
    render() {
        return (
                { ? <em>Loading...</em> :}

Https to http redirect using htaccess

You can use the following rule to redirect from https to http :

 RewriteEngine On

RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$$1 [NC,L,R]

Explanation :

RewriteCond %{HTTPS} ^on$

Checks if the HTTPS is on (Request is made using https)


RewriteRule ^(.*)$$1 [NC,L,R]

Redirect any request ( to .

  • $1 is part of the regex in RewriteRule pattern, it contains whatever value was captured in (.+) , in this case ,it captures the full request_uri everything after the domain name.

  • [NC,L,R] are the flags, NC makes the uri case senstive, you can use both uppercase or lowercase letters in the request.

L flag tells the server to stop proccessing other rules if the currunt rule has matched, it is important to use the L flag to avoid rule confliction when you have more then on rules in a block.

R flag is used to make an external redirection.

Calling a particular PHP function on form submit

An alternative, and perhaps a not so good procedural coding one, is to send the "function name" to a script that then executes the function. For instance, with a login form, there is typically the login, forgotusername, forgotpassword, signin activities that are presented on the form as buttons or anchors. All of these can be directed to/as, say,


And then a switch statement on the receiving page does any prep work and then dispatches or runs the (next) specified function.

Cross Browser Flash Detection in Javascript

View the source at (lines 14-120).

Here is the abstracted cross browser code on jsbin for flash detection only, works on: FF/IE/Safari/Opera/Chrome.

How to solve a timeout error in Laravel 5

Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page

otherwise in htaccess php_value max_execution_time 360

PostgreSQL - max number of parameters in "IN" clause?

This is not really an answer to the present question, however it might help others too.

At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.

This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:

Caused by: Tried to send an out-of-range integer as a 2-byte value: 100000
    at org.postgresql.core.PGStream.SendInteger2(

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Based on different answers but mainly on this, this works for what I need:

UIImage *image1 = ...; // The image from where you want a pixel data
int pixelX = ...; // The X coordinate of the pixel you want to retrieve
int pixelY = ...; // The Y coordinate of the pixel you want to retrieve

uint32_t pixel1; // Where the pixel data is to be stored
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(image1.CGImage), CGImageGetHeight(image1.CGImage)), image1.CGImage);

As a result of this lines, you will have a pixel in AARRGGBB format with alpha always set to FF in the 4 byte unsigned integer pixel1.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.


Try this


Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Drawable image on a canvas

You need to load your image as bitmap:

 Resources res = getResources();
 Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);

Then make the bitmap mutable and create a canvas over it:

Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));

You then can draw on the canvas.

How to read and write excel file

String path="C:\\Book2.xlsx";
try {

        File f = new File( path );
        Workbook wb = WorkbookFactory.create(f);
        Sheet mySheet = wb.getSheetAt(0);
        Iterator<Row> rowIter = mySheet.rowIterator();
        for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
            for (  Iterator<Cell> cellIterator = ((Row) ; cellIterator.hasNext() ;  ) 
                System.out.println ( ( (Cell) ).toString() );
            System.out.println( " **************************************************************** ");
    } catch ( Exception e )
        System.out.println( "exception" );

and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project

Searching for file in directories recursively

I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.

    private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
            filePathCollector = filePathCollector ?? new LinkedList<string>();

            var matchingFilePaths = Directory.GetFiles(path, pattern);

            foreach(var matchingFile in matchingFilePaths)

            var subDirectories = Directory.EnumerateDirectories(path);

            foreach (var subDirectory in subDirectories)
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);

            return filePathCollector;
        catch (Exception error)
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;

            if (isIgnorableError)
                return Enumerable.Empty<string>();

            throw error;

CertificateException: No name matching found

It looks like the certificate of the server you are trying to connect to doesn't match its hostname.

When an HTTPS client connects to a server, it verifies that the hostname in the certificate matches the hostname of the server. It's not enough for a certificate to be trusted, it has to match the server you want to talk to too. (As an analogy, even if you trust a passport to be legitimate, you still have to check that it's the one for the person you want to talk to, not just any passport you would trust to be legitimate.)

In HTTP, this is done by checking that:

  • the certificate contains a DNS subject alternative name (this is a standard extension) entry matching the hostname;

  • failing that, the last CN of your subject distinguished name (this is the main name if you want) matches the hostname. (See RFC 2818.)

It's hard to tell what the subject alternative name is without having the certificate (although, if you connect with your browser and check its content in more details, you should be able to see it.) The subject distinguished name seems to be:

[email protected], CN=plesk, OU=Plesk, O=Parallels, L=Herndon, ST=Virginia, C=US

(It would thus need to be instead of CN=plesk, if you don't have a subject alternative name with already; my guess is that you don't.)

You may be able to bypass the hostname verification using HttpsURLConnection.setHostnameVerifier(..). It shouldn't be too hard to write a custom HostnameVerifier that bybasses the verification, although I would suggest doing it only when the certificate its the one concerned here specifically. You should be able to get that using the SSLSession argument and its getPeerCertificates() method.

(In addition, you don't need to set the* properties the way you've done it, since you're using the default values anyway.)

Alternatively, if you have control over the server you're connecting to and its certificate, you can create a certificate of it that matches the naming rules above (CN should be sufficient, although subject alternative name is an improvement). If a self-signed certificate is good enough for what you name, make sure its common name (CN) is the host name you're trying to talk to (no the full URL, just the hostname).

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:


i get:

$ nc -l 9999
GET / HTTP/1.1
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Date format Mapping to JSON Jackson

Building on @miklov-kriven's very helpful answer, I hope these two additional points of consideration prove helpful to someone:

(1) I find it a nice idea to include serializer and de-serializer as static inner classes in the same class. NB, using ThreadLocal for thread safety of SimpleDateFormat.

public class DateConverter {

    private static final ThreadLocal<SimpleDateFormat> sdf = 
                () -> {return new SimpleDateFormat("yyyy-MM-dd HH:mm a z");});

    public static class Serialize extends JsonSerializer<Date> {
        public void serialize(Date value, JsonGenerator jgen SerializerProvider provider) throws Exception {
            if (value == null) {
            else {

    public static class Deserialize extends JsonDeserializer<Date> {
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws Exception {
            String dateAsString = jp.getText();
            try {
                if (Strings.isNullOrEmpty(dateAsString)) {
                    return null;
                else {
                    return new Date(sdf.get().parse(dateAsString).getTime());
            catch (ParseException pe) {
                throw new RuntimeException(pe);

(2) As an alternative to using @JsonSerialize and @JsonDeserialize annotations on each individual class member you could also consider overriding Jackson's default serialization by applying the custom serialization at an application level, that is all class members of type Date will be serialized by Jackson using this custom serialization without explicit annotation on each field. If you are using Spring Boot for example one way to do this would as follows:

public class Application {
    public static void main(String[] args) {, args);

    public Module customModule() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Date.class, new DateConverter.Serialize());
        module.addDeserializer(Date.class, new Dateconverter.Deserialize());
        return module;

When to use throws in a Java method declaration?

The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.

Something like:

public void method() throws Exception{
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   }catch(IOException e){


public void method(){
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   }catch(IOException e){
           System.out.println("Catching IOException");
   }catch(Exception e){
           System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");


Get the real width and height of an image with JavaScript? (in Safari/Chrome)

I've done some workaround utility function, using imagesLoaded jquery plugin:

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
          , w, h, this.img);
                },{img: img, func: func, ctx: ctx}));

You can use this by passing url, function and its context. Function is performed after image is loaded and return created image, its width and height.

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)

HTML Button Close Window

Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.

This was addressed here by rvighne in a similar question on the subject.

How to use Spring Boot with MySQL database and JPA?

Your code is in the default package, i.e. you have source all files in src/main/java with no custom package. I strongly suggest u to create package n then place your source file in it.


I hope it will resolve your problem.

Determine a string's encoding in C#

The code below has the following features:

  1. Detection or attempted detection of UTF-7, UTF-8/16/32 (bom, no bom, little & big endian)
  2. Falls back to the local default codepage if no Unicode encoding was found.
  3. Detects (with high probability) unicode files with the BOM/signature missing
  4. Searches for charset=xyz and encoding=xyz inside file to help determine encoding.
  5. To save processing, you can 'taste' the file (definable number of bytes).
  6. The encoding and decoded text file is returned.
  7. Purely byte-based solution for efficiency

As others have said, no solution can be perfect (and certainly one can't easily differentiate between the various 8-bit extended ASCII encodings in use worldwide), but we can get 'good enough' especially if the developer also presents to the user a list of alternative encodings as shown here: What is the most common encoding of each language?

A full list of Encodings can be found using Encoding.GetEncodings();

// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little
// & big endian), and local default codepage, and potentially other codepages.
// 'taster' = number of bytes to check of the file (to save processing). Higher
// value is slower, but more reliable (especially UTF-8 with special characters
// later on may appear to be ASCII initially). If taster = 0, then taster
// becomes the length of the file (for maximum reliability). 'text' is simply
// the string with the discovered encoding applied to the file.
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000)
    byte[] b = File.ReadAllBytes(filename);

    //////////////// First check the low hanging fruit by checking if a
    //////////////// BOM/signature exists (sourced from
    if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); }  // UTF-32, big-endian 
    else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; }    // UTF-32, little-endian
    else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; }     // UTF-16, big-endian
    else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; }              // UTF-16, little-endian
    else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8
    else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7

    //////////// If the code reaches here, no BOM/signature was found, so now
    //////////// we need to 'taste' the file to see if can manually discover
    //////////// the encoding. A high taster value is desired for UTF-8
    if (taster == 0 || taster > b.Length) taster = b.Length;    // Taster size can't be bigger than the filesize obviously.

    // Some text files are encoded in UTF8, but have no BOM/signature. Hence
    // the below manually checks for a UTF8 pattern. This code is based off
    // the top answer at:
    // For our purposes, an unnecessarily strict (and terser/slower)
    // implementation is shown at:
    // For the below, false positives should be exceedingly rare (and would
    // be either slightly malformed UTF-8 (which would suit our purposes
    // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot).
    int i = 0;
    bool utf8 = false;
    while (i < taster - 4)
        if (b[i] <= 0x7F) { i += 1; continue; }     // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks.
        if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; }
        if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; }
        if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; }
        utf8 = false; break;
    if (utf8 == true) {
        text = Encoding.UTF8.GetString(b);
        return Encoding.UTF8;

    // The next check is a heuristic attempt to detect UTF-16 without a BOM.
    // We simply look for zeroes in odd or even byte places, and if a certain
    // threshold is reached, the code is 'probably' UF-16.          
    double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10%
    int count = 0;
    for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; }
    count = 0;
    for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian)

    // Finally, a long shot - let's see if we can find "charset=xyz" or
    // "encoding=xyz" to identify the encoding:
    for (int n = 0; n < taster-9; n++)
        if (
            ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) ||
            ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '='))
            if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9;
            if (b[n] == '"' || b[n] == '\'') n++;
            int oldn = n;
            while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z')))
            { n++; }
            byte[] nb = new byte[n-oldn];
            Array.Copy(b, oldn, nb, 0, n-oldn);
            try {
                string internalEnc = Encoding.ASCII.GetString(nb);
                text = Encoding.GetEncoding(internalEnc).GetString(b);
                return Encoding.GetEncoding(internalEnc);
            catch { break; }    // If C# doesn't recognize the name of the encoding, break.

    // If all else fails, the encoding is probably (though certainly not
    // definitely) the user's local codepage! One might present to the user a
    // list of alternative encodings as shown here:
    // A full list can be found using Encoding.GetEncodings();
    text = Encoding.Default.GetString(b);
    return Encoding.Default;

How do I get the XML root node with C#?

Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.

Here's a simplified version, using XmlReader and MoveToContent().

using (XmlReader xmlReader = XmlReader.Create(p_fileName))
  if (xmlReader.MoveToContent() == XmlNodeType.Element)
    rootNodeName = xmlReader.Name;

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

Python non-greedy regexes

To start with, I do not suggest using "*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the + sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the {x, y} syntax to specifically specify the desired length.

However, if you really do need non-greedy repetition, I suggest consulting the all-powerful ?. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible.

That being said, I would be very careful with the ? as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify ((1) (note the lack of a second rparen) as a match.

Array initialization syntax when not in a declaration

I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.

If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.

In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.

I would say that (and if someone knows better, please correct me) the first example

AClass[] array = {object1, object2}

actually means

AClass[] array = new AClass[]{object1, object2};

but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.

The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

DTO pattern: Best way to copy properties between two objects

You can have a look at dozer which is a

Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Another better link...

Remove all occurrences of char from string

I like using RegEx in this occasion:

str = str.replace(/X/g, '');

where g means global so it will go through your whole string and replace all X with ''; if you want to replace both X and x, you simply say:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

What's the difference between Docker Compose vs. Dockerfile

In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.

Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db and no longer by its IP.

How to get a Static property with Reflection

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _

Replace part of a string in Python?

Use the replace() method on string:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )

Collection was modified; enumeration operation may not execute in ArrayList

I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.

That said, the comments I appreciated are:

  • "unless you are using .NET 1.0 or 1.1, use List<T> instead of ArrayList. "

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.


private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

public List<string> ParseList(List<string> checkList)
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)

    return verifiedList;

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.


See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

implementing merge sort in C++

This would be easy to understand:

#include <iostream>

using namespace std;

void Merge(int *a, int *L, int *R, int p, int q)
    int i, j=0, k=0;
    for(i=0; i<p+q; i++)
        if(j==p)                       //When array L is empty
            *(a+i) = *(R+k);
        else if(k==q)                  //When array R is empty
            *(a+i) = *(L+j);
        else if(*(L+j) < *(R+k))  //When element in L is smaller than element in R
            *(a+i) = *(L+j);
        else   //When element in R is smaller or equal to element in L
            *(a+i) = *(R+k);

void MergeSort(int *a, int len)
    int i, j;
    if(len > 1)
        int p = len/2 + len%2;      //length of first array
        int q = len/2;              //length of second array
        int L[p];                   //first array
        int R[q];                   //second array
        for(i=0; i<p; i++)
            L[i] = *(a+i);      //inserting elements in first array
        for(i=0; i<q; i++)
            R[i] = *(a+p+i);    //inserting elements in second array
        MergeSort(&L[0], p);
        MergeSort(&R[0], q);
        Merge(a, &L[0], &R[0], p, q);   //Merge arrays L and R into A
        return;        //if array only have one element just return

int main()
    int i, n;
    int a[100000];
    cout<<"Enter numbers to sort. When you are done, enter -1\n";
            a[i] = n;
    int len = i;
    MergeSort(&a[0], len);
    for(i=0; i<len; i++)
        cout<<a[i]<<" ";

    return 0;

Creating a file only if it doesn't exist in Node.js

With async / await and Typescript I would do:

import * as fs from 'fs'

async function upsertFile(name: string) {
  try {
    // try to read file
    await fs.promises.readFile(name)
  } catch (error) {
    // create empty file, because it wasn't found
    await fs.promises.writeFile(name, '')

Create a directly-executable cross-platform GUI app using Python

I'm not sure that this is the best way to do it, but when I'm deploying Ruby GUI apps (not Python, but has the same "problem" as far as .exe's are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.

Java - Best way to print 2D array?

Simple and clean way to print a 2D array.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

Java 8 Streams FlatMap method example

Am I the only one who finds unwinding lists boring? ;-)

Let's try with objects. Real world example by the way.

Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start and repeat every repeatPeriod repeatUnit(e.g. 5 HOURS) and there will be repeatCount reminders in total(including starting one).

Goal: achieve a list of task copies, one for each task reminder invocation.

List<Task> tasks =
                    new Task(
                            false,//completed sign
                            "My important task",//task name (text)
                  , ChronoUnit.DAYS),//first reminder(start)
                            true,//is task repetitive?
                            1,//reminder interval
                            ChronoUnit.DAYS,//interval unit
                            5//total number of reminders
        x -> LongStream.iterate(
                p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
        .map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))


Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}

P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.

UPDATE: @RBz asked for detailed explanation so here it is. Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate... creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount() instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC) and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds(). boxed() returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!

jQuery: count number of rows in a table

try this one if there is tbody

Without Header

$("#myTable > tbody").children.length

If there is header then

$("#myTable > tbody").children.length -1


Simplest way to do grouped barplot

with ggplot2:

Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

How to calculate number of days between two given dates?

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

This assumes, of course, that you've already verified that your dates are in the format r'\d+/\d+/\d+'.

what's the easiest way to put space between 2 side-by-side buttons in

Add a space &nbsp; between them (or more depending on your preference)

    <div style="text-align: center">         
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
        <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:

How to get the background color code of an element in hex?

In fact, if there is no definition of background-color under some element, Chrome will output its background-color as rgba(0, 0, 0, 0), while Firefox outputs is transparent.

Remove Item in Dictionary based on Value

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())

reducing number of plot ticks

To solve the issue of customisation and appearance of the ticks, see the Tick Locators guide on the matplotlib website


Would set the total number of ticks in the x-axis to 3, and evenly distribute it across the axis.

There is also a nice tutorial about this

Environment variables in Mac OS X

I think what the OP is looking for is a simple, windows-like solution.

here ya go:

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from:

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

wp-admin shows blank page, how to fix it?

After dozens of times trying to fix this problem reading forums and posts, reinstalling WordPress, removing white spaces, putting lines of code in wp-config.php, index.php, admin.php, I fixed the issue just by renaming the plugins folder to "pluginss" in FTP. So wordpress asked me to update the database. I updated and I could enter at /wp-admin. A plugin was causing some conflict, so when I rename the plugins folder, all plugins automatically has been disabled.

As I was inside the /wp-admin dashboard, I could rename the "pluginss" folder to the regular name and start to activate all the plugins one by one and see what plugin was broken.

Now is 100% fine.

Safe Area of Xcode 9

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

From the property's documentation:

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

(emphasis mine)

If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}

How to send data with angularjs $http.delete() request?

You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.

Otherwise I guess you can just pass the user id as part of the query params? Something like

$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...

In angular $http service, How can I catch the "status" of error?

From the official angular documentation

// Simple GET request example :
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.

As you can see first parameter for error callback is data an status is second.

How to avoid reverse engineering of an APK file?

APK signature scheme v2 in Android N

The PackageManager class now supports verifying apps using the APK signature scheme v2. The APK signature scheme v2 is a whole-file signature scheme that significantly improves verification speed and strengthens integrity guarantees by detecting any unauthorized changes to APK files.

To maintain backward-compatibility, an APK must be signed with the v1 signature scheme (JAR signature scheme) before being signed with the v2 signature scheme. With the v2 signature scheme, verification fails if you sign the APK with an additional certificate after signing with the v2 scheme.

APK signature scheme v2 support will be available later in the N Developer Preview.

How to get a context in a recycler view adapter

You can define:

Context ctx; 

And on onCreate initialise ctx to:


Note: Parent is a ViewGroup.

C# refresh DataGridView when updating or inserted on another form

For datagridview in C#, use this code

MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from dailyprice";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);

DataTable table = new DataTable();

BindingSource bSource = new BindingSource();
bSource.DataSource = table;

dataGridView1.DataSource = bSource;

It works for show new records in the datagridview.

Regex matching beginning AND end strings

Scanner scanner = new Scanner(;
String part = scanner.nextLine();
String line = scanner.nextLine();

String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());

System.out.println(matcher.find() ? "YES":"NO");

If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything

How to calculate the CPU usage of a process by PID in Linux from C?

Use strace found the CPU usage need to be calculated by a time period:

# top -b -n 1 -p 3889
top - 16:46:37 up  1:04,  3 users,  load average: 0.00, 0.01, 0.02
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  5594496 total,  5158284 free,   232132 used,   204080 buff/cache
KiB Swap:  3309564 total,  3309564 free,        0 used.  5113756 avail Mem 

 3889 root      20   0  162016   2220   1544 S   0.0  0.0   0:05.77 top
# strace top -b -n 1 -p 3889
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342

nanosleep({0, 150000000}, NULL)         = 0
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I'm running the very latest Laravel 5 dev release, and if you've changed the namespace you'll need to call your seed class like this:


Obviously you'll need to replace todoparrot with your designated namespace. Otherwise I receive the same error indicated in the original question.

How to stop java process gracefully?

Ok, after all the possibilities I have chosen to work with "Java Monitoring and Management"
Overview is here
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a script to stop controlled application gracefully before killing it.

Here is the simplified code:

Controlled application:
run it with the folowing VM parameters:

public interface ThreadMonitorMBean
String getName();
void start();
void stop();
boolean isRunning();

public class ThreadMonitor implements ThreadMonitorMBean
private Thread m_thrd = null;

public ThreadMonitor(Thread thrd)
    m_thrd = thrd;

public String getName()
    return "JMX Controlled App";

public void start()
    // TODO: start application here
    System.out.println("remote start called");

public void stop()
    // TODO: stop application here
    System.out.println("remote stop called");


public boolean isRunning()
    return Thread.currentThread().isAlive();

public static void main(String[] args)
        System.out.println("JMX started");

        ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());

        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        ObjectName name = new ObjectName("com.example:type=ThreadMonitor");

        server.registerMBean(monitor, name);

            // loop until interrupted
            catch(InterruptedException ex) 
    catch(Exception e)
        // TODO: some final clean up could be here also
        System.out.println("JMX stopped");

Controlling application:
run it with the stop or start as the command line argument

public class ThreadMonitorConsole

public static void main(String[] args)
        // connecting to JMX
        System.out.println("Connect to JMX service.");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // Construct proxy for the the MBean object
        ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor");
        ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);

        System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running");

        // parse command line arguments
            System.out.println("Invoke \"start\" method");
        else if(args[0].equalsIgnoreCase("stop"))
            System.out.println("Invoke \"stop\" method");

        // clean up and exit
    catch(Exception e)
        // TODO Auto-generated catch block

That's it. :-)

Grab a segment of an array in Java without creating a new array on heap

Disclaimer: This answer does not conform to the constraints of the question:

I don't want to have to create a new byte array in the heap memory just to do that.

(Honestly, I feel my answer is worthy of deletion. The answer by @unique72 is correct. Imma let this edit sit for a bit and then I shall delete this answer.)

I don't know of a way to do this directly with arrays without additional heap allocation, but the other answers using a sub-list wrapper have additional allocation for the wrapper only – but not the array – which would be useful in the case of a large array.

That said, if one is looking for brevity, the utility method Arrays.copyOfRange() was introduced in Java 6 (late 2006?):

byte [] a = new byte [] {0, 1, 2, 3, 4, 5, 6, 7};

// get a[4], a[5]

byte [] subArray = Arrays.copyOfRange(a, 4, 6);

Send message to specific client with and node.js

Also you can keep clients refferences. But this makes your memmory busy.

Create an empty object and set your clients into it.

const myClientList = {};

  server.on("connection", (socket) => {`Client connected [id=${}]`);
     myClientList[] = socket;   
  socket.on("disconnect", (socket) => {
    delete myClientList[];

then call your specific client by id from the object


ASP.NET MVC Html.ValidationSummary(true) does not display model errors

Maybe like that:

public ActionResult Register(Member member)
       if (!ModelState.IsValid)
          ModelState.AddModelError("keyName", "Form is not valid");
          return View();
    catch (Exception ex)
       ModelState.AddModelError("keyName", ex.Message);
       return View(member);

And in display add:

<div class="alert alert-danger">


<div class="alert alert-danger">

Add vertical scroll bar to panel

Add to your panel's style code something like this:

<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>

Changing image sizes proportionally using CSS?

To make images adjustable/flexible you could use this:

/* fit images to container */
.container img {
    max-width: 100%;
    height: auto;

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.


How to load all modules in a folder?

Just import them by importlib and add them to __all__ (add action is optional) in recurse in the of package.


import os
import importlib
pyfile_extes = ['py', ]
__all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
del os, importlib, pyfile_extes

How do I define global variables in CoffeeScript?

I think what you are trying to achieve can simply be done like this :

While you are compiling the coffeescript, use the "-b" parameter.

-b / --bare Compile the JavaScript without the top-level function safety wrapper.

So something like this : coffee -b --compile whatever.js

This will output your code just like in the site.

Get SSID when WIFI is connected

I listen for WifiManager.NETWORK_STATE_CHANGED_ACTION in a broadcast receiver

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
        NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
        if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {

I check for netInfo.isConnected (). Then I am able to use

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid  = info.getSSID();


From android 8.0 onwards we wont be getting SSID of the connected network unless GPS is turned on.

Easiest way to flip a boolean value?

Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:


bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;