Programs & Examples On #Ruby 1.9.2

For issues relating to developing in Ruby, version 1.9.2. If your question applies to Ruby in general, use the tag [tag:ruby].

Get list of a class' instance methods

You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.

String length in bytes in JavaScript

Actually, I figured out what's wrong. For the code to work the page <head> should have this tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Or, as suggested in comments, if server sends HTTP Content-Encoding header, it should work as well.

Then results from different browsers are consistent.

Here is an example:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>mini string length test</title>

<script type="text/javascript">
document.write('<div style="font-size:100px">' 
    + (unescape(encodeURIComponent("???! Naïve?")).length) + '</div>'

Note: I suspect that specifying any (accurate) encoding would fix the encoding problem. It is just a coincidence that I need UTF-8.

How to call a Parent Class's method from Child Class in Python?

Python also has super as well:

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.


class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls ''

myB = B()

Receive JSON POST with PHP

If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:

$_POST = json_decode(file_get_contents('php://input'), true);

This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.

Python 3 Float Decimal Points/Precision

The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.

Android offline documentation and sample codes

If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/.

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How to use switch statement inside a React component?

I'm not a big fan of any of the current answers, because they are either too verbose, or require you to jump around the code to understand what is going on.

I prefer doing this in a more react component centred way, by creating a <Switch/>. The job of this component is to take a prop, and only render children whose child prop matches this one. So in the example below I have created a test prop on the switch, and compared it to a value prop on the children, only rendering the ones that match.


const Switch = props => {
  const { test, children } = props
  // filter out only children with a matching prop
  return children.find(child => {
    return child.props.value === test

const Sample = props => {
  const someTest = true
  return (
    <Switch test={someTest}>
      <div value={false}>Will display if someTest is false</div>
      <div value={true}>Will display if someTest is true</div>

<script src=""></script>
<script src=""></script>
<div id="react"></div>

You can make the switch as simple or as complex as you want. Don't forget to perform more robust checking of the children and their value props.

SQL Server 2005 Using DateAdd to add a day to a date

The following query i have used in sql-server 2008, it may be help you.

For add day  DATEADD(DAY,20,GETDATE())

*20 is the day quantity

Wildcard string comparison in Javascript

if(mas[i].indexOf("bird") == 0)
    //there is bird

You.can read about indexOf here:

What is middleware exactly?

I always thought of it as the oldest software I have had to install. The total app used a web server, a database server, and an application server. The web server being the middleware between the data and the app.

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:


It allows filters to be mapped on the particular servlet:


Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

public class Servlet1 extends HttpServlet {

See also:

Convert a hexadecimal string to an integer efficiently in C?

In C you can convert a hexadecimal number to decimal in many ways. One way is to cast the hexadecimal number to an integer. I personally found this to be simple and small.

Here is an sample code for converting a Hexadecimal number to a Decimal number with the help of casting.

#include <stdio.h>

int main(){
    unsigned char Hexadecimal = 0x6D;   //example hex number
    int Decimal = 0;    //decimal number initialized to 0

        Decimal = (int) Hexadecimal;  //conversion

    printf("The decimal number is %d\n", Decimal);  //output
    return 0;

jQuery move to anchor location on page load

Put this right before the closing Body tag at the bottom of the page.

    if (location.hash) {
        location.href = location.hash;

jQuery is actually not required.

ReactJS SyntheticEvent stopPropagation() only works with React events?

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

Working JSFiddle with the fixes from below.

React Stop Propagation on jQuery Event

Use Event.stopImmediatePropagation to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.

stopPropagation: function(e){
  • Caveat: Listeners are called in the order in which they are bound. React must be initialized before other code (jQuery here) for this to work.

jQuery Stop Propagation on React Event

Your jQuery code uses event delegation as well, which means calling stopPropagation in the handler is not stopping anything; the event has already propagated to document, and React's listener will be triggered.

// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){

To prevent propagation beyond the element, the listener must be bound to the element itself:

// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){

Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.

Regular expression to match URLs in Java

Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.

String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

This works too:

String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";


String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <>

WAMP shows error 'MSVCR100.dll' is missing when install

After downloading all the libraries said by ezaoutis, the error message on my windows 10 persisted, reading the wampserver3.1.3 installation requirements, there was a verification tool called check_vcredist.exe , i ran it and it show me all the missing libraries and it's download links, so i finally could install it succesfully.

Below image with check tool marked

When is the finalize() method called in Java?

Check out Effective Java, 2nd edition page 27. Item 7: Avoid finalizers

Finalizers are unpredictable, often dangerous, and generally unnecessary. never do anything time-critical in a finalizer. never depend on a finalizer to update critical persistent state.

To terminate a resource, use try-finally instead:

// try-finally block guarantees execution of termination method
Foo foo = new Foo(...);
try {
    // Do what must be done with foo
} finally {
    foo.terminate(); // Explicit termination method

Python 3.1.1 string to hex

binascii methodes are easier by the way

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
>>> y=str(x,'ascii')
>>> y
>>> x=binascii.unhexlify(x)
>>> x
>>> y=str(x,'ascii')
>>> y

Hope it helps. :)

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

Purpose of "%matplotlib inline"

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.

Best way to do nested case statement logic in SQL Server

You can combine multiple conditions to avoid the situation:

CASE WHEN condition1 = true AND condition2 = true THEN calculation1 
     WHEN condition1 = true AND condition2 = false 
     ELSE 'what so ever' END,

Correct way to pass multiple values for same parameter name in GET request

I am describing a simple method which worked very smoothly in Python (Django Framework).

1. While sending the request, send the request like this


2. Now in my backend, I split the value received with a split function which always creates a list.

id_filter = id.split(',')

Example: So if I send two values in the request,


then the filter on the data is

id_filter = ['a', 'b']

If I send only one value in the request,


then the filter outcome is

id_filter = ['a']

3. To actually filter the data, I simply use the 'in' function

queryset = queryset.filter(model_id__in=id_filter)

which roughly speaking performs the SQL equivalent of

WHERE model_id IN ('a', 'b')

with the first request and,

WHERE model_id IN ('a')

with the second request.

This would work with more than 2 parameter values in the request as well !

How can I get the IP address from NIC in Python?

Building on the answer from @jeremyjjbrown, another version that cleans up after itself as mentioned in the comments to his answer. This version also allows providing a different server address for use on private internal networks, etc..

import socket

def get_my_ip_address(remote_server=""):
    Return the/a network-facing IP number for this system.
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: 
        s.connect((remote_server, 80))
        return s.getsockname()[0]

URLEncoder not able to translate space character

This behaves as expected. The URLEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

From the javadocs:

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

and from the HTML Specification:


Forms submitted with this content type must be encoded as follows:

  1. Control names and values are escaped. Space characters are replaced by `+'

You will have to replace it, e.g.:

System.out.println("Hello World", "UTF-8").replace("+", "%20"));

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

Command for restarting all running docker containers?

For me its now :

docker restart $(docker ps -a -q)

Disabling browser caching for all browsers from ASP.NET

See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you actually want to use _tWinMain() instead of main() make sure your project relevant configuration have

  1. Linker-> System -> SubSystem => Windows(/SUBSYSTEM:WINDOWS)
  2. C/C++ -> Preprocessor -> Preprocessor Definitions => Replace _CONSOLE with _WINDOWS
  3. In the c/cpp file where _tWinMain() is defined, add:

    #include <Windows.h> #include <tchar.h>

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

How to remove td border with html?


<table border="1">
        <td style='border:none;'>one</td>
        <td style='border:none;'>two</td>
        <td style='border:none;'>one</td>
        <td style='border:none;'>two</td>

Second example

<table border="1" cellspacing="0" cellpadding="0">
    <td style='border-left:none;border-top:none'>one</td>
    <td style='border:none;'>two</td>
    <td style='border-left:none;border-bottom:none;border-top:none'>one</td>
    <td style='border:none;'>two</td>

How to display Base64 images in HTML?

If you have PHP on the back-end, you can use this code:

$image = '';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="'.$src.'">';

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);

Is mathematics necessary for programming?

While advanced mathematics may not be required for programming (unless you are programming advanced mathematics capability) the thought process of programming and mathematics are very similar. You begin with a base of known things (axioms, previously proven theories) and try to get to someplace new. You cannot skip steps. If you do skip steps, then you are required to fill in the blanks. It's a critical thought process that makes the two incredibly similar.

Also, mathematicians and programmers both think critically in the abstract. Real world things are represented by objects and variables. The ability to translate from concrete to abstract also links the two fields.

There's a very good chance that if you're good at one, you will probably be good at the other.

Why maven settings.xml file is not there?

By Installing Maven you can not expect the settings.xml in your .m2 folder(If may be hidden folder, to unhide just press Ctrl+h). You need to place the file explicitly at that location. After placing the file maven plugin for eclipse will start using that file too.

Error while sending QUERY packet

You can solve this problem by following few steps:

1) open your terminal window

2) please write following command in your terminal

ssh root@yourIP port

3) Enter root password

4) Now edit your server my.cnf file using below command

nano /etc/my.cnf  

if command is not recognized do this first or try vi then repeat: yum install nano.


  vi /etc/my.cnf 

5) Add the line under the [MYSQLD] section. :

max_allowed_packet=524288000 (obviously adjust size for whatever you need) 
wait_timeout = 100

6) Control + O (save) then ENTER (confirm) then Control + X (exit file)

7) Then restart your mysql server by following command

/etc/init.d/mysql stop
/etc/init.d/mysql start

8) You can verify by going into PHPMyAdmin or opening a SQL command window and executing:

SHOW VARIABLES LIKE 'max_allowed_packet'

This works for me. I hope it should work for you.

Typescript ReferenceError: exports is not defined

npm install @babel/plugin-transform-modules-commonjs

and add to to .babelrc plugins resolved my question.

Set div height equal to screen size

Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.

Use vh instead of %;

Changing the "tick frequency" on x or y axis in matplotlib?

This is an old topic, but I stumble over this every now and then and made this function. It's very convenient:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    Send in an axis and I fix the resolution as desired.

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)

One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then do

gca().set_ylim(top=new_top) # for example

and run the resadjust function again.

Android how to use Environment.getExternalStorageDirectory()

As described in Documentation Environment.getExternalStorageDirectory() :

Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.

This is an example of how to use it reading an image :

String fileName = "stored_image.jpg";
 String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
 String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";

 File f = new File(pathDir + File.separator + fileName);

          Log.d("Application", "The file " + file.getName() + " exists!";
          Log.d("Application", "The file no longer exists!";

How to remove an unpushed outgoing commit in Visual Studio?

Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.

Get all Attributes from a HTML element with Javascript/jQuery

Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:

(function($) {
    $.fn.getAttributes = function () {
        var elem = this, 
            attr = {};

        if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { 
            n = n.nodeName||;
            v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
            if(v != undefined && v !== false) attr[n] = v

        return attr


var attribs = $('#some_id').getAttributes();

Deploying my application at the root in Tomcat

In tomcat 7 with these changes, i'm able to access myAPP at / and ROOT at /ROOT

<Context path="" docBase="myAPP">
     <!-- Default set of monitored resources -->
<Context path="ROOT" docBase="ROOT">
     <!-- Default set of monitored resources -->

Add above to the <Host> section in server.xml

Remote Procedure call failed with sql server 2008 R2

This error appears to happen when .mof files (Managed Object Format (MOF)) don’t get installed and registered correctly during set-up. To resolve this issue, I executed the following mofcomp command in command prompt to re-register the *.mof files:

mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof"

This one worked for me serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
    public virtual string Sound { get; }
    public string Color { get; set; }

public class Dog : Animal
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }

public class Cat : Animal
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
<% end %>

This way you are using the locales for the error messages.

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Assign an initial value to radio button as checked

Im a bit late to the party and I know the OP said html, but if you needed to do this in MVC you can set true in the third param.


    <p>Option One :@Html.RadioButton("options", "option1", true})</p>
    // true will set it checked

     <p>Option Two :@Html.RadioButton("options", "option2"})</p>
     //nothing will leave it unchecked

Parse strings to double with comma and point

Make two static cultures, one for comma and one for point.

    var commaCulture = new CultureInfo("en")
        NumberFormat =
            NumberDecimalSeparator = ","

    var pointCulture = new CultureInfo("en")
        NumberFormat =
            NumberDecimalSeparator = "."

Then use each one respectively, depending on the input (using a function):

    public double ConvertToDouble(string input)
        input = input.Trim();

        if (input == "0") {
            return 0;

        if (input.Contains(",") && input.Split(',').Length == 2)
            return Convert.ToDouble(input, commaCulture);

        if (input.Contains(".") && input.Split('.').Length == 2)
            return Convert.ToDouble(input, pointCulture);

        throw new Exception("Invalid input!");

Then loop through your arrays

    var strings = new List<string> {"0,12", "0.122", "1,23", "00,0", "0.00", "12.5000", "0.002", "0,001"};
    var doubles = new List<double>();

    foreach (var value in strings) {

This should work even though the host environment and culture changes.

Return Result from Select Query in stored procedure to a List

In stored procedure, you just need to write the select query like the below:

    SELECT ID, Name 
    FROM Test

On C# side, you can access using Reader, datatable, adapter.

Using adapter has just explained by Susanna Floora.

Using Reader:

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();

List<Test> TestList = new List<Test>();
Test test = null;

while (reader.Read())
    test = new Test();
    test.ID = int.Parse(reader["ID"].ToString());
    test.Name = reader["Name"].ToString();

gvGrid.DataSource = TestList;

Using dataTable:

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;

DataTable dt = new DataTable();

gvGrid.DataSource = dt;

I hope it will help you. :)

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

No module named _sqlite3

For Python 3.7.8 with Redhat 7 or Centos 7.

  • Install sqlite-devel
$ yum install sqlite-devel
  • Compile and install Python3 with sqllite extensions
$ ./configure --enable-optimizations --enable-loadable-sqlite-extensions
$ make install

HTML Canvas Full Screen

AFAIK, HTML5 does not provide an API which supports full screen.

This question has some view points on making html5 video full screen for example using webkitEnterFullscreen in webkit.
Is there a way to make html5 video fullscreen

Find files and tar them (with spaces)

There could be another way to achieve what you want. Basically,

  1. Use the find command to output path to whatever files you're looking for. Redirect stdout to a filename of your choosing.
  2. Then tar with the -T option which allows it to take a list of file locations (the one you just created with find!)

    find . -name "*.whatever" > yourListOfFiles
    tar -cvf yourfile.tar -T yourListOfFiles

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

From official documentation :

To enable Google to crawl your app content and allow users to enter your app from search results, you must add intent filters for the relevant activities in your app manifest. These intent filters allow deep linking to the content in any of your activities. For example, the user might click on a deep link to view a page within a shopping app that describes a product offering that the user is searching for.

Using this link Enabling Deep Links for App Content you'll see how to use it.

And using this Test Your App Indexing Implementation how to test it.

The following XML snippet shows how you might specify an intent filter in your manifest for deep linking.

    android:label="@string/title_gizmos" >
    <intent-filter android:label="@string/filter_title_viewgizmos">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Accepts URIs that begin with "” -->
        <data android:scheme="http"
              android:pathPrefix="/gizmos" />
        <!-- note that the leading "/" is required for pathPrefix-->
        <!-- Accepts URIs that begin with "example://gizmos” -->
        <data android:scheme="example"
              android:host="gizmos" />


To test via Android Debug Bridge

$ adb shell am start
        -W -a android.intent.action.VIEW
        -d <URI> <PACKAGE>

$ adb shell am start
        -W -a android.intent.action.VIEW
        -d "example://gizmos"

Rails ActiveRecord date between

I ran this code to see if the checked answer worked, and had to try swapping around the dates to get it right. This worked--

Day.where(:reference_date =>
#=> 721

If you're thinking the output should have been 36, consider this, Sir, how many days is 3 days to 3 people?

Spring @Autowired and @Qualifier

@Autowired to autowire(or search) by-type
@Qualifier to autowire(or search) by-name
Other alternate option for @Qualifier is @Primary

public class A{}

public class B{

public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

private A a;


//If you don't want to add the two annotations, we can use @Resource
public class B{

private A a;

//Importing properties is very similar
@Value("${}")  //@Value know how to interpret ${}
private String name;

more about @value

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Creating a new empty branch for a new project

The best solution is to create a new branch with --orphan option as shown below

git checkout --orphan <branch name>

By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.

By default the --orphan option doesn't remove the files in the working directory, so you can delete the working directory files by this:

git rm --cached -r

In details what the --orphan does:

--orphan <new_branch>
Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.

This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.

If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.

WPF popup window

You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:

MyWindow popup = new MyWindow();

You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null), you can set the window's DialogResult property before closing it and then check for it (it is the value returned by ShowDialog()).

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

Seaborn plots not showing up

This worked for me

import matplotlib.pyplot as plt
import seaborn as sns

How to target only IE (any version) within a stylesheet?

Another working solution for IE specific styling is

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

And then your selector

html[data-useragent*='MSIE 10.0'] body .my-class{
        margin-left: -0.4em;

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

I found the solution!

Follow these steps:

Flutter Firebase and Android issue - unable to Initialise. Cannot find google-services.json with latest migration instructions executed

After that, execute:

flutter build apk --debug
flutter build apk --profile
flutter build apk --release

and then, run app! it works for me!

how to read a text file using scanner in Java?

If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.

This is according to Core Java Volume I, section 3.7.3.

If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use

Scanner in = new Scanner(Paths.get("myfile.txt"));

But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key

Indexing get and sets the individual bytes

>>> key[0]
>>> key[1]=0xff
>>> key

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)

How can I change the image of an ImageView?

Have a look at the ImageView API. There are several setImage* methods. Which one to use depends on the image you provide. If you have the image as resource (e.g. file res/drawable/my_image.png)

ImageView img = new ImageView(this);  // or (ImageView) findViewById(;

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Try this:

 function GetDateFormat(controlName) {
        if ($('#' + controlName).val() != "") {      
            var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
            if (d1 == null) {
                alert('Date Invalid.');
                $('#' + controlName).val("");
                var array = d1.toString('dd-MMM-yyyy');
                $('#' + controlName).val(array);

The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.

Rmi connection refused with localhost

One difference we can note in Windows is:

If you use Runtime.getRuntime().exec("rmiregistry 1024");

you can see rmiregistry.exe process will run in your Task Manager

whereas if you use Registry registry = LocateRegistry.createRegistry(1024);

you can not see the process running in Task Manager,

I think Java handles it in a different way.

and this is my server.policy file

Before running the the application, make sure that you killed all your existing javaw.exe and rmiregistry.exe corresponds to your rmi programs which are already running.

The following code works for me by using Registry.LocateRegistry() or


// Standard extensions get all permissions by default

grant {

VM argument



package server;    

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class HelloServer 
  public static void main (String[] argv) 
    try {

            System.setSecurityManager(new RMISecurityManager());

 Runtime.getRuntime().exec("rmiregistry 1024");

 //     Registry registry = LocateRegistry.createRegistry(1024);
   //   registry.rebind ("Hello", new Hello ("Hello,From pvt ltd!"));
   //Process process = Runtime.getRuntime().exec("C:\\Users\\Durai\\workspace\\RMI\\src\\server\\rmi_registry_start.bat");

        Naming.rebind ("//localhost:1024/Hello",new Hello ("Hello,From pvt ltd!")); 
      System.out.println ("Server is connected and ready for operation.");
    catch (Exception e) {
      System.out.println ("Server not connected: " + e);

Can't Load URL: The domain of this URL isn't included in the app's domains

Adding my localhost on Valid OAuth redirect URIs at solved the problem!

And pay attention for one detail here:

In this case http://localhost:3000 is not the same of or

Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...

enter image description here

Setting background colour of Android layout element

4 possible ways, use one you need.

1. Kotlin

val ll = findViewById<LinearLayout>(
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))

2. Data Binding


OR more useful statement-


3. XML



4. Java

LinearLayout ll = (LinearLayout) findViewById(;
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

Storing sex (gender) in database

CREATE TABLE Admission (
    Name VARCHAR(25) NOT NULL,
    Gender ENUM('M','F'),
    Boolean_Valu boolean,
    Dob Date,
    Fees numeric(7,2) NOT NULL

insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;

enter link description here

Remove empty lines in a text file via grep

Perl might be overkill, but it works just as well.

Removes all lines which are completely blank:

perl -ne 'print if /./' file

Removes all lines which are completely blank, or only contain whitespace:

perl -ne 'print if ! /^\s*$/' file

Variation which edits the original and makes a .bak file:

perl -i.bak -ne 'print if ! /^\s*$/' file

Create a folder inside documents folder in iOS apps

I do that the following way:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Android Google Maps v2 - set zoom level for myLocation

You can use

    CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);

Best way to check if a character array is empty

Given this code:

char text[50];
if(strlen(text) == 0) {}

Followed by a question about this code:

 memset(text, 0, sizeof(text));
 if(strlen(text) == 0) {}

I smell confusion. Specifically, in this case:

char text[50];
if(strlen(text) == 0) {}

... the contents of text[] will be uninitialized and undefined. Thus, strlen(text) will return an undefined result.

The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.

char text[50];
text[0] = 0;

From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

How do I use the CONCAT function in SQL Server 2008 R2?

CONCAT, as stated, is not supported prior to SQL Server 2012. However you can concatenate simply using the + operator as suggested. But beware, this operator will throw an error if the first operand is a number since it thinks will be adding and not concatenating. To resolve this issue just add '' in front. For example

someNumber + 'someString' + .... + lastVariableToConcatenate

will raise an error BUT '' + someNumber + 'someString' + ...... will work just fine.

Also, if there are two numbers to be concatenated make sure you add a '' between them, like so

.... + someNumber + '' + someOtherNumber + .....

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

In more simple terms:

Technically, the -u flag adds a tracking reference to the upstream server you are pushing to.

What is important here is that this lets you do a git pull without supplying any more arguments. For example, once you do a git push -u origin master, you can later call git pull and git will know that you actually meant git pull origin master.

Otherwise, you'd have to type in the whole command.

Differences between time complexity and space complexity?

Sometimes yes they are related, and sometimes no they are not related, actually we sometimes use more space to get faster algorithms as in dynamic programming dynamic programming uses memoization or bottom-up, the first technique use the memory to remember the repeated solutions so the algorithm needs not to recompute it rather just get them from a list of solutions. and the bottom-up approach start with the small solutions and build upon to reach the final solution. Here two simple examples, one shows relation between time and space, and the other show no relation: suppose we want to find the summation of all integers from 1 to a given n integer: code1:

for i=1 to n
print sum

This code used only 6 bytes from memory i=>2,n=>2 and sum=>2 bytes therefore time complexity is O(n), while space complexity is O(1) code2:

array a[n]
for i=2 to n
print a[n]

This code used at least n*2 bytes from the memory for the array therefore space complexity is O(n) and time complexity is also O(n)

How to import image (.svg, .png ) in a React Component

You can also try:

var imageName = require('relative_path_of_image_from_component_file');

class XYZ extends Component {
            <img src={imageName.default} alt="something"/>

Note: Make sure Image is not outside the project root folder.

Does Python have a package/module management system?

There are at least two, easy_install and its successor pip.

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

How do I auto-hide placeholder text upon focus using css or jquery?

To further refine Wallace Sidhrée's code sample:

        input = $(this);'place-holder-text', input.attr('placeholder'))
        input.attr('placeholder', '');

          input = $(this);

This ensures that each input stores the correct placeholder text in the data attribute.

See a working example here in jsFiddle.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How do I find out what version of WordPress is running?

On the Admin Panel Dashboard, you can find a box called "Right Now". There you can see the version of the WordPress installation. I have seen this result in WordPress 3.2.1. You can also see this in version 3.7.1

WordPress Version 3.7.1


In WP Version 3.8.3

WordPress Version 3.8.3

In WP Version 3.9.1 Admin Side, You can see the version by clicking the WP logo which is located at the left-top position.

WordPress Version 3.9.1

You can use yoursitename/readme.html

In the WordPress Admin Footer at the Right side, you will see the version info(Version 3.9.1).

In WP 4

You can get the WordPress version using the following code:

<?php bloginfo('version'); ?>

The below file is having all version details


Update for WP 4.1.5

In WP 4.1.5, If it was the latest WP version in the footer right part, it will show the version as it is. If not, it will show the latest WP version with the link to update.

Check the below screenshot.

WP 4.1.5

How do I create a Linked List Data Structure in Java?

Use java.util.LinkedList. Like this:

list = new java.util.LinkedList()

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

How to run a function in jquery

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

Remove First and Last Character C++

Well, you could erase() the first character too (note that erase() modifies the string):

m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);

But in this case, a simpler way is to take a substring:

m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);

Be careful to validate that the string actually has at least two characters in it first...

Remove Primary Key in MySQL

ALTER TABLE `user_customer_permission` MODIFY `id` INT;
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY;

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);


SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';


Android Google Maps API V2 Zoom to Current Location

    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);


Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:


For maven-javadoc-plugin 3.0.0+: Replace




What I can do to resolve "1 commit behind master"?

If the branch is behind master, then delete the remote branch. Then go to local branch and run :

git pull origin master --rebase

Then, again push the branch to origin:

git push -u origin <branch-name>

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());

Java switch statement: Constant expression required, but it IS constant

In my case, I was getting this exception because

switch (tipoWebServ) {
                            case VariablesKmDialog.OBTENER_KM:
                            case var.MODIFICAR_KM:

in the second case I was calling the constant from the instance var.MODIFICAR_KM: but I should use VariablesKmDialog.OBTENER_KM directly from the class.

Boxplot in R showing the mean

Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:

zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)

(See this post for more details)

If you would like to add points to horizontal box plots, please see this post.

SQL Server Management Studio missing

Current version:

SQL Server Management Studio

Direct link:

Version Information

This release of SSMS uses the Visual Studio 2015 Isolated shell. The release number: 16.4.1 The build number for this release: 13.0.15900.1 Supported SQL Server versions This version of SSMS works with all supported versions of SQL Server (SQL Server 2008 - SQL Server 2016), and provides the greatest level of support for working with the latest cloud features in Azure SQL Database. There is no explicit block for SQL Server 2000 or SQL Server 2005, but some features may not work properly. Additionally, one SSMS 16.x release or SSMS 2016 can be installed side by side with previous versions of SSMS 2014 and earlier.

Older version of the answer for 2012

Installation steps:

  1. Download file "SQLEXPRWT_x64_ENU.exe" for your version aprox 1Gb
  2. Execute following command (note that installation need access to internet to download about 140Mb and you will need to interact with installer)


original answer was: Now posted:

github: server certificate verification failed

Make sure first that you have certificates installed on your Debian in /etc/ssl/certs.

If not, reinstall them:

sudo apt-get install --reinstall ca-certificates

Since that package does not include root certificates, add:

sudo mkdir /usr/local/share/ca-certificates/
sudo wget -P /usr/local/share/ca-certificates/
sudo update-ca-certificates

Make sure your git does reference those CA:

git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt

Jason C mentions another potential cause (in the comments):

It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.

Certificates are time sensitive.

Programmatically find the number of cores on a machine

On Linux, you can read the /proc/cpuinfo file and count the cores.

Formatting Decimal places in R

Looks to me like to would be something like

format(1.128347132904321674821, 2)

Per a little online help.

How do I sort a VARCHAR column in SQL server that contains numbers?

One possible solution is to pad the numeric values with a character in front so that all are of the same string length.

Here is an example using that approach:

select MyColumn
from MyTable
order by 
    case IsNumeric(MyColumn) 
        when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
        else MyColumn

The 100 should be replaced with the actual length of that column.

How to go to a URL using jQuery?

window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it

$("<a href='your url'></a>").click(); 

Is there a JSON equivalent of XQuery/XPath?

Other alternatives I am aware of are

  1. JSONiq specification, which specifies two subtypes of languages: one that hides XML details and provides JS-like syntax, and one that enriches XQuery syntax with JSON constructors and such. Zorba implements JSONiq.
  2. Corona, which builds on top of MarkLogic provides a REST interface for storing, managing, and searching XML, JSON, Text and Binary content.
  3. MarkLogic 6 and later provide a similar REST interface as Corona out of the box.
  4. MarkLogic 8 and later support JSON natively in both their XQuery and Server-side JavaScript environment. You can apply XPath on it.


How to redirect 'print' output to a file using python?

Changing the value of sys.stdout does change the destination of all calls to print. If you use an alternative way to change the destination of print, you will get the same result.

Your bug is somewhere else:

  • it could be in the code you removed for your question (where does filename come from for the call to open?)
  • it could also be that you are not waiting for data to be flushed: if you print on a terminal, data is flushed after every new line, but if you print to a file, it's only flushed when the stdout buffer is full (4096 bytes on most systems).

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How can I make space between two buttons in same div?

you should use bootstrap v.4

<div class="form-group row">
    <div class="col-md-6">
        <input type="button" class="btn form-control" id="btn1">
    <div class="col-md-6">
        <input type="button" class="btn form-control" id="btn2">

Android Device Chooser -- device not showing up

If you select Android Application in the Debug As dialog, you should be able to attach the debugger to the device directly. Make sure you run adb devices on your shell and see your device listed. If not, you will need to re-install the driver for the device. You can uninstall the drivers you have using USBdeview and then download and re-install the drivers until you see the serial number for the device listed when you run adb devices. - Arunabh Das

Find an element by class name, from a known parent element

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.


Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

Maximum on http header values?

I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs

tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

Auto reloading python Flask app upon code changes

Use this method:

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

def index():
   return "Hello World"

if __name__ == '__main__':

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.

How to remove commits from a pull request

People wouldn't like to see a wrong commit and a revert commit to undo changes of the wrong commit. This pollutes commit history.

Here is a simple way for removing the wrong commit instead of undoing changes with a revert commit.

  1. git checkout my-pull-request-branch

  2. git rebase -i HEAD~n // where n is the number of last commits you want to include in interactive rebase.

  3. Replace pick with drop for commits you want to discard.
  4. Save and exit.
  5. git push --force

What is the purpose of a question mark after a type (for example: int? myVariable)?

Nullable Types

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a [Nullable<Int32>], pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A [Nullable<bool>] can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I got that error when I was deleting some rows in the DB (in the loop), and the adding the new ones in the same table.

The solutions for me was, to dynamicaly create a new context in each loop iteration

What does 'URI has an authority component' mean?

After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Try this

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

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to display loading message when an iFrame is loading?

If it's only a placeholder you are trying to achieve: a crazy approach is to inject text as an svg-background. It allows for some flexbility, and from what I've read the browser support should be fairly decent (haven't tested it though):

  • Chrome >= 27
  • FireFox >= 30
  • Internet Explorer >= 9
  • Safari >= 5.1


<iframe class="iframe-placeholder" src=""></iframe>


   background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="" width="100%" height="100%" viewBox="0 0 100% 100%"><text fill="%23FF0000" x="50%" y="50%" font-family="\'Lucida Grande\', sans-serif" font-size="24" text-anchor="middle">PLACEHOLDER</text></svg>') 0px 0px no-repeat;

What can you change?

Inside the background-value:

  • font size: look for font-size="" and change the value to anything you want

  • font color: look for fill="". Don't forget to replace the # with %23 if you're using hexadecimal color notation. %23 stands for a # in URL encoding which is necessary for the svg-string to be able to be parsed in FireFox.

  • font family: look for font-family="" remember to escape the single quotes if you have a font that consists of multiple words (like with \'Lucida Grande\')

  • text: look for the element value of the text-element where you see the PLACEHOLDER string. You can replace the PLACEHOLDER string with anything that is url-compliant (special characters need to be converted to percent notation)

Example on fiddle


  • No extra HTML-elements
  • No js
  • Text can easily (...) be adjusted without the need of an external program
  • It's SVG, so you can easily put any SVG you want in there.


  • Browser support
  • It's complex
  • It's hacky
  • If the iframe-src doesn't have a background set, the placeholder will shine through (which is not inherent to this method, but just standard behaviour when you use a bg on the iframe)

I would only recommend this only if it's absolutely necessary to show text as a placeholder in an iframe which requires a little bit of flexbility (multiple languages, ...). Just take a moment and reflect on it: is all this really necessary? If I had a choice, I'd go for @Christina's method

How to place the ~/.composer/vendor/bin directory in your PATH?

Open the Mac Terminal:

vi ~/.bashrc

If you haven't used vi, it may look a little funny at first, so enter the following code carefully, in order:

export PATH="$PATH:$HOME/.composer/vendor/bin"






Now you should have returned to the normal terminal view.

Check that composer now has the correct path:

cd ~/.composer
echo $PATH

If you see the path including your file directory, (e.g. /Users/JeffStrongman/.composer/vendor/bin), you're good to go.


Then run your installation. I ran into this problem, while configuring my Mac to use Laravel Valet.

Example (optional)

valet install

Javascript: how to validate dates in format MM-DD-YYYY?

How about validating dates in "ANY" date format? I've been using the DateJS library and adding it to existing forms to ensure that I get valid dates & times formatted the way that I want. The user can even enter things like "now" and "tomorrow" and it will be converted into a valid date.

Here's the dateJS library:

and here's a jQuery tip that I wrote:

How to use ADB in Android Studio to view an SQLite DB

Depending on devices you might not find sqlite3 command in adb shell. In that case you might want to follow this :

adb shell

$ run-as
$ cd ./databases/
$ ls -l #Find the current permissions - r=4, w=2, x=1
$ chmod 666 ./dbname.db
$ exit
$ exit
adb pull /data/data/ ~/Desktop/
adb push ~/Desktop/dbname.db /data/data/
adb shell
$ run-as
$ chmod 660 ./databases/dbname.db #Restore original permissions
$ exit
$ exit

for reference go to

There might be cases when you get "remote object not found" after following above procedure. Then change permission of your database folder to 755 in adb shell.

$ chmod 755 databases/

But please mind that it'll work only on android version < 21.

In an array of objects, fastest way to find the index of an object whose attributes match a search

I like this method because it's easy to compare to any value in the object no matter how deep it's nested.

 while(i<myArray.length && myArray[i].data.value!==value){
// i now hows the index value for the match. 
 console.log("Index ->",i );

How to execute raw queries with Laravel 5.1?

    DB::statement("your query")

I used it for add index to column in migration

How to get current timestamp in string format in Java? ""

Use modern java.time classes if you use java 8 or newer.

String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(;

Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat.

How to stretch div height to fill parent div - CSS

Suppose you have

  <div id="root" />

With normal CSS, you can do the following. See a working app

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;

With flexbox, you can

html, body {
  height: 100%
body {
  display: flex;
  align-items: stretch;

#root {
  width: 100%

JUnit 4 compare Sets

I like the solution of Hans-Peter Störr... But I think it is not quite correct. Sadly containsInAnyOrder does not accept a Collection of objetcs to compare to. So it has to be a Collection of Matchers:

assertThat(set1, containsInAnyOrder(

The import are:

import static;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

How many threads can a Java VM support?

After playing around with Charlie's DieLikeACode class, it looks like the Java thread stack size is a huge part of how many threads you can create.

-Xss set java thread stack size

For example

java -Xss100k DieLikeADog

But, Java has the Executor interface. I would use that, you will be able to submit thousands of Runnable tasks, and have the Executor process those tasks with a fixed number of threads.

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
    : nChr === 47 ?


function base64DecToArr (sBase64, nBlocksSize) {

    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      nUint24 = 0;


  return taBytes;

How to sort a list of objects based on an attribute of the objects?

If the attribute you want to sort by is a property, then you can avoid importing operator.attrgetter and use the property's fget method instead.

For example, for a class Circle with a property radius we could sort a list of circles by radii as follows:

result = sorted(circles, key=Circle.radius.fget)

This is not the most well-known feature but often saves me a line with the import.

How to convert CSV file to multiline JSON?

import csv
import json

file = 'csv_file_name.csv'
json_file = 'output_file_name.json'

#Read CSV File
def read_CSV(file, json_file):
    csv_rows = []
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        field = reader.fieldnames
        for row in reader:
            csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
        convert_write_json(csv_rows, json_file)

#Convert csv data into json
def convert_write_json(data, json_file):
    with open(json_file, "w") as f:
        f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #for pretty


Documentation of json.dumps()

Replacing all non-alphanumeric characters with empty strings

Using Guava you can easily combine different type of criteria. For your specific solution you can use:

value = CharMatcher.inRange('0', '9')
        .or(CharMatcher.inRange('a', 'z')
        .or(CharMatcher.inRange('A', 'Z'))).retainFrom(value)

How can I cast int to enum?

I am using this piece of code to cast int to my enum:

if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }

I find it the best solution.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

You should put your component between an enclosing tag, Which means:


return (  
    <Comp1 />
    <Comp2 />


// Correct

return (
       <Comp1 />
       <Comp2 />

Edit: Per Joe Clay's comment about the Fragments API

// More Correct

return (
       <Comp1 />
       <Comp2 />

// Short syntax

return (
       <Comp1 />
       <Comp2 />

Pandas sort by group aggregate and column

Here's a more concise approach...

df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)

The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.


    A       B           C
5   baz     -2.301539   True
2   baz     -0.528172   False
1   bar     -0.611756   True
4   bar      0.865408   False
3   foo     -1.072969   True
0   foo      1.624345   False

NOTE: sort is deprecated, use sort_values instead

Why do we have to specify FromBody and FromUri?

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Please go through the website for more details:

An URL to a Windows shared folder

I think there are two issues:

  1. You need to escape the slashes.
  2. Browser security.


  1. I checked one of mine, I have the pattern:

    <a href="file://///server01\fshare\dir1\dir2\dir3">useful link </a>

    Please note that we ended up with 5 slashes after the protocol (file:)

  2. Firefox will try to prevent cross site scripting. My solution was to modify prefs.js in the profile directory. You will add two lines:

    user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
    user_pref("capability.policy.localfilelinks.sites", "");

CSS Circular Cropping of Rectangle Image

The object-fit property provides a non-hackish way for doing this (with image centered). It has been supported in major browsers for a few years now (Chrome/Safari since 2013, Firefox since 2015, and Edge since 2015) with the exception of Internet Explorer.

img.rounded {_x000D_
  object-fit: cover;_x000D_
  border-radius: 50%;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
<img src="" class="rounded">

Good NumericUpDown equivalent in WPF?

A control that is missing from the original set of WPF controls, but much used, is the NumericUpDown control. It is a neat way to get users to select a number from a fixed range, in a small area. A slider could be used, but for compact forms with little horizontal real-estate, the NumericUpDown is essential.

Solution A (via WindowsFormsHost)

You can use the Windows Forms NumericUpDown control in WPF by hosting it in a WindowsFormsHost. Pay attention that you have to include a reference to System.Windows.Forms.dll assembly.

<Window x:Class="WpfApplication61.MainWindow"
        Title="MainWindow" Height="350" Width="525">

Solution B (custom)

There are several commercial and codeplex versions around, but both involve installing 3rd party dlls and overheads to your project. Far simpler to build your own, and a aimple way to do that is with the ScrollBar.

A vertical ScrollBar with no Thumb (just the repeater buttons) is in fact just what we want. It inherits rom RangeBase, so it has all the properties we need, like Min, Max, and SmallChange (set to 1, to restrict it to Integer values)

So we change the ScrollBar ControlTemplate. First we remove the Thumb and Horizontal trigger actions. Then we group the remains into a grid and add a TextBlock for the number:

<Grid Margin="2">
        <ColumnDefinition />
    <TextBlock VerticalAlignment="Center" FontSize="20" MinWidth="25" Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"/>
    <Grid Grid.Column="1" x:Name="GridRoot" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Background="{TemplateBinding Background}">
            <RowDefinition MaxHeight="18"/>
            <RowDefinition Height="0.00001*"/>
            <RowDefinition MaxHeight="18"/>
        <RepeatButton x:Name="DecreaseRepeat" Command="ScrollBar.LineDownCommand" Focusable="False">
                <Path x:Name="DecreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 4 L 8 4 L 4 0 Z"/>
        <RepeatButton Grid.Row="2" x:Name="IncreaseRepeat" Command="ScrollBar.LineUpCommand" Focusable="False">
                <Path x:Name="IncreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 0 L 4 4 L 8 0 Z"/>


"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Just made this in a few minutes:

using System;
using System.Management;

namespace WindowsFormsApplication_CS
  class NetworkManagement
    public void setIP(string ip_address, string subnet_mask)
      ManagementClass objMC =
        new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
        if ((bool)objMO["IPEnabled"])
          ManagementBaseObject setIP;
          ManagementBaseObject newIP =

          newIP["IPAddress"] = new string[] { ip_address };
          newIP["SubnetMask"] = new string[] { subnet_mask };

          setIP = objMO.InvokeMethod("EnableStatic", newIP, null);

    public void setGateway(string gateway)
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
        if ((bool)objMO["IPEnabled"])
          ManagementBaseObject setGateway;
          ManagementBaseObject newGateway =

          newGateway["DefaultIPGateway"] = new string[] { gateway };
          newGateway["GatewayCostMetric"] = new int[] { 1 };

          setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);

    public void setDNS(string NIC, string DNS)
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
        if ((bool)objMO["IPEnabled"])
          // if you are using the System.Net.NetworkInformation.NetworkInterface
          // you'll need to change this line to
          // if (objMO["Caption"].ToString().Contains(NIC))
          // and pass in the Description property instead of the name 
          if (objMO["Caption"].Equals(NIC))
            ManagementBaseObject newDNS =
            newDNS["DNSServerSearchOrder"] = DNS.Split(',');
            ManagementBaseObject setDNS =
              objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);

    public void setWINS(string NIC, string priWINS, string secWINS)
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
        if ((bool)objMO["IPEnabled"])
          if (objMO["Caption"].Equals(NIC))
            ManagementBaseObject setWINS;
            ManagementBaseObject wins =
            wins.SetPropertyValue("WINSPrimaryServer", priWINS);
            wins.SetPropertyValue("WINSSecondaryServer", secWINS);

            setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);

css label width not taking effect

Use display: inline-block;


The label is an inline element, meaning it is only as big as it needs to be.

Set the display property to either inline-block or block in order for the width property to take effect.


#report-upload-form {_x000D_
    background-color: #316091;_x000D_
    color: #ddeff1;_x000D_
    font-weight: bold;_x000D_
    margin: 23px auto 0 auto;_x000D_
    border-radius: 10px;_x000D_
    width: 650px;_x000D_
    box-shadow: 0 0 2px 2px #d9d9d9;_x000D_
#report-upload-form label {_x000D_
    padding-left: 26px;_x000D_
    width: 125px;_x000D_
    text-transform: uppercase;_x000D_
    display: inline-block;_x000D_
#report-upload-form input[type=text], _x000D_
#report-upload-form input[type=file],_x000D_
#report-upload-form textarea {_x000D_
    width: 305px;_x000D_
<form id="report-upload-form" method="POST" action="" enctype="multipart/form-data">_x000D_
    <p><label for="id_title">Title:</label> <input id="id_title" type="text" class="input-text" name="title"></p>_x000D_
    <p><label for="id_description">Description:</label> <textarea id="id_description" rows="10" cols="40" name="description"></textarea></p>_x000D_
    <p><label for="id_report">Upload Report:</label> <input id="id_report" type="file" class="input-file" name="report"></p>_x000D_

Java 8: Difference between two LocalDateTime in multiple units


Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

How can the default node version be set using NVM?

change the default node version with nvm alias default 10.15.3 *

(replace mine version with your default version number)

you can check your default lists with nvm list

JS strings "+" vs concat method

  • We can't concatenate a string variable to an integer variable using concat() function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.
  • As we know, functions are pretty slower than operators. functions needs to pass values to the predefined functions and need to gather the results of the functions. which is slower than doing operations using operators because operators performs operations in-line but, functions used to jump to appropriate memory locations... So, As mentioned in previous answers the other difference is obviously the speed of operation.

<!DOCTYPE html>_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

How to change font size in a textbox in html

Here are some ways to edit the text and the size of the box:



<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter 
Text Here</textarea>

Simple way to calculate median with MySQL

In MariaDB / MySQL:

SELECT AVG(dd.val) as median_val
SELECT d.val, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum
  FROM data d, (SELECT @rownum:=0) r
  WHERE d.val is NOT NULL
  -- put some where clause here
  ORDER BY d.val
) as dd
WHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows+2)/2) );

Steve Cohen points out, that after the first pass, @rownum will contain the total number of rows. This can be used to determine the median, so no second pass or join is needed.

Also AVG(dd.val) and dd.row_number IN(...) is used to correctly produce a median when there are an even number of records. Reasoning:

SELECT FLOOR((3+1)/2),FLOOR((3+2)/2); -- when total_rows is 3, avg rows 2 and 2
SELECT FLOOR((4+1)/2),FLOOR((4+2)/2); -- when total_rows is 4, avg rows 2 and 3

Finally, MariaDB 10.3.3+ contains a MEDIAN function

Saving to CSV in Excel loses regional date format

Change the date and time settings for your computer in the "short date" format under calendar settings. This will change the format for everything yyyy-mm-dd or however you want it to display; but remember it will look like that even for files saved on your computer.

At least it works.

Linq style "For Each"

The Array and List<T> classes already have ForEach methods, though only this specific implementation. (Note that the former is static, by the way).

Not sure it really offers a great advantage over a foreach statement, but you could write an extension method to do the job for all IEnumerable<T> objects.

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    foreach (var item in source)

This would allow the exact code you posted in your question to work just as you want.

difference between throw and throw new Exception()

Throwing a new Exception blows away the current stack trace.

throw; will retain the original stack trace and is almost always more useful. The exception to that rule is when you want to wrap the Exception in a custom Exception of your own. You should then do:

catch(Exception e)
    throw new CustomException(customMessage, e);

php stdClass to array

Please use following php function to convert php stdClass to array


How to verify CuDNN installation?

I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h, so

cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2

did the trick.

How can I convert radians to degrees with Python?

radian can also be converted to degree by using numpy


if needed to roundoff ( I did with 6 digits after decimal below), then

print(np.round(np.rad2deg(1), 6)


Download multiple files with a single action

You can create a temporary set of hidden iframes, initiate download by GET or POST inside of them, wait for downloads to start and remove iframes:

  <button id="download">Download</button> 

  <script type="text/javascript" src=""></script>
  <script type="text/javascript">

     $('#download').click(function() {

     var download = function() {
       for(var i=0; i<arguments.length; i++) {
         var iframe = $('<iframe style="visibility: collapse;"></iframe>');
         var content = iframe[0].contentDocument;
         var form = '<form action="' + arguments[i] + '" method="GET"></form>';
         $('form', content).submit();
         setTimeout((function(iframe) {
           return function() { 
         })(iframe), 2000);


Or, without jQuery:

 function download(...urls) {
    urls.forEach(url => {
      let iframe = document.createElement('iframe'); = 'collapse';

        `<form action="${url.replace(/\"/g, '"')}" method="GET"></form>`

      setTimeout(() => iframe.remove(), 2000);

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

Sum one number to every element in a list (or array) in Python

using List Comprehension:

>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]

which roughly translates to using a for loop:

>>> newL = []
>>> for x in L:
...     newL+=[x+1]
>>> newL
[2, 2, 2, 2, 2]

or using map:

>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle:

Floating point inaccuracy examples

In python:

>>> 1.0 / 10

Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.

Using python's eval() vs. ast.literal_eval()?

If all you need is a user provided dictionary, possible better solution is json.loads. The main limitation is that json dicts requires string keys. Also you can only provide literal data, but that is also the case for literal_eval.

add controls vertically instead of horizontally using flow layout

As I stated in comment i would use a box layout for this.

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout());

JButton button = new JButton("Button1");

button = new JButton("Button2");

button = new JButton("Button3");


Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):


Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

How do I get the path of the current executed file in Python?

Simply add the following:

from sys import *
path_to_current_file = sys.argv[0]


from sys import *

How can I read a text file from the SD card in Android?

BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 

How to preventDefault on anchor tags?

You can pass the $event object to your method, and call $event.preventDefault() on it, so that the default processing will not occur:

<a href="#" ng-click="do($event)">Click</a>

// then in your$event) method

Is there a method that tells my program to quit?

The actual way to end a program, is to call

raise SystemExit

It's what sys.exit does, anyway.

A plain SystemExit, or with None as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")) prints the exception value to sys.stderr and sets the exit code to 1. An integer value sets the process' exit code to the value:

$ python -c "raise SystemExit(4)"; echo $?

How should I choose an authentication library for CodeIgniter?

Ion_Auth beats tank_auth mainly for two reasons, user roles and documentation, these two are missing from tank_auth.

grep a file, but show several surrounding lines?

Grep has an option called Context Line Control, you can use the --context in that, simply,

| grep -C 5


| grep -5

Should do the trick

Failed to resolve:

  1. Add this in build.gradle(Project:projectname)

    allprojects {
      repositories {
        maven { url "" }
  2. Add this in build.gradle(Module:app)

    dependencies {
      compile ''

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));


Character: 1
Character: 49

iOS: Multi-line UILabel in Auto Layout

Expand your label set number of lines to 0 and also more importantly for auto layout set height to >= x. Auto layout will do the rest. You may also contain your other elements based on previous element to correctly position then.

auto layout

Eliminate space before \begin{itemize}

Use \vspace{-\topsep} before \begin{itemize}.

Use \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} after \begin{itemize}.

And for the space after the list, use \vspace{-\topsep} after \end{itemize}.

  \setlength{\itemsep}{0pt plus 1pt}
  \item ...
  \item ...

Youtube iframe wmode issue

&wmode=opaque didn't work for me (chrome 10) but &amp;wmode=transparent cleared the issue right up.

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here

And then use it like this:

Thread t = new Thread(new MyRunnableTask());

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here

This is similar to the above, only you don't create another named class.

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)


If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I had same problem. In "Edit Configurations.." -> "Tomcat Server" I changed JRE from "Default" to my current version with SDK directory address (like C:\Program Files\Java\jdk1.8.0_121\jre)

My Tomcat version is 8.5.31

How can I store the result of a system command in a Perl variable?

Also for eg. you can use IPC::Run:

use IPC::Run qw(run);

my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
    '|', sub { print grep { /myprocess/ } <STDIN> },
    '|', [qw(wc -l)],
    '>', \my $out;

print $out;
  • processes are running without bash subprocess
  • can be piped to perl subs
  • very similar to shell

bash: pip: command not found

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008


SET @y = REPLICATE(@y,92681);




I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory


select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid



so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.


I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/

SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/

DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3

What are Unwind segues for and how do you use them?

Unwind segues are used to "go back" to some view controller from which, through a number of segues, you got to the "current" view controller.

Imagine you have something a MyNavController with A as its root view controller. Now you use a push segue to B. Now the navigation controller has A and B in its viewControllers array, and B is visible. Now you present C modally.

With unwind segues, you could now unwind "back" from C to B (i.e. dismissing the modally presented view controller), basically "undoing" the modal segue. You could even unwind all the way back to the root view controller A, undoing both the modal segue and the push segue.

Unwind segues make it easy to backtrack. For example, before iOS 6, the best practice for dismissing presented view controllers was to set the presenting view controller as the presented view controller’s delegate, then call your custom delegate method, which then dismisses the presentedViewController. Sound cumbersome and complicated? It was. That’s why unwind segues are nice.

What's the use of "enum" in Java?

an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Java Array, Finding Duplicates

To check for duplicates you need to compare distinct pairs.

C++11 thread-safe queue

Adding to the accepted answer, I would say that implementing a correct multi producers / multi consumers queue is difficult (easier since C++11, though)

I would suggest you to try the (very good) lock free boost library, the "queue" structure will do what you want, with wait-free/lock-free guarantees and without the need for a C++11 compiler.

I am adding this answer now because the lock-free library is quite new to boost (since 1.53 I believe)

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
node { 
    stage('Prepare Mib'){

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

If you have your backend and database started on docker

Instead of putting localhost or as DB_HOST put the name of the registered service that indicates your database service in the docker-compose file.

In my case for example I replaced with db because in my docker-compose file I had defined the name of the service for the database as db

My docker-compose looks something like that

    db: <------ This is the name of the DB_HOST
      container_name: admin_db

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Why can't I see the "Report Data" window when creating reports?

I was also same problem in Visual Studio 2013, Then Suddenly got an Idea.. Click on Report to make focus on it. Simple Press Alt+Ctrl+D

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:


The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)