Programs & Examples On #Gateway

Get gateway ip address in android

On Android 7 works it:

 ip route get

output will be: via gateway...

Angular @ViewChild() error: Expected 2 arguments, but got 1

Angular 8

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component : Component

You can read more about it here and here

Angular 9 & Angular 10

In Angular 9 default value is static: false, so doesn't need to provide param unless you want to use {static: true}

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

How to change default timezone for Active Record in Rails?

If you want local time to set, add the following text in application.rb

config.time_zone = 'Chennai'

# WARNING: This changes the way times are stored in the database (not recommended)
config.active_record.default_timezone = :local

Then restart your server

PHP "php://input" vs $_POST

php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

Here's a function to do just that:

   * Returns the JSON encoded POST data, if any, as an object.
   * @return Object|null
  private function retrieveJsonPostData()
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);

The $_POST array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see for details).

How to convert a string to ASCII

You can do it by using LINQ-expression.

  public static List<int> StringToAscii(string value)
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Value cannot be null or empty.", nameof(value));

        return value.Select(System.Convert.ToInt32).ToList();

How do I reverse a C++ vector?

There's a function std::reverse in the algorithm header for this purpose.

#include <vector>
#include <algorithm>

int main() {
  std::vector<int> a;
  std::reverse(a.begin(), a.end());
  return 0;

How to remove element from an array in JavaScript?

Others answers are great, I just wanted to add an alternative solution with ES6 Array function : filter.

filter() creates a new array with elements that fall under a given criteria from an existing array.

So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.

Some examples :

Remove first element :

// Not very useful but it works
function removeFirst(element, index) {
  return index > 0;
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]

Remove second element :

function removeSecond(element, index) {
  return index != 1;
var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]

Remove odd element :

function removeOdd(element, index) {
  return !(element % 2);
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]

Remove items not in stock

const inventory = [
  {name: 'Apple', qty: 2},
  {name: 'Banana', qty: 0},
  {name: 'Orange', qty: 5}

const res = inventory.find( product => product.qty > 0);

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )

OTP (token) should be automatically read from the message


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

        android:text="Hello World!"
        app:layout_constraintTop_toTopOf="parent" />


import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver broadcastReceiver;
    protected void onCreate(Bundle savedInstanceState) {
        broadcastReceiver =new MyBroadcastReceiver();

    protected void onStart()
    IntentFilter intentFilter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    protected void onStop()



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

 * Created by mukundwn on 12/02/18.

public class MyBroadcastReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"hello received an sms",Toast.LENGTH_SHORT).show();


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

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
        <receiver android:name=".MyBroadcastReceiver">
            <action android:name="android.provider.Telephony.SMS_RECEIVE"></action>


Live search through table rows

Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.

See live demo and source code here.

Create a search box, may be an input field like this.

<input type="text" id="search" autocomplete="off">

Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.

Suppose we have the html like this. We have an input field and a list to display the results.

 <div class="icon"></div>
 <input type="text" id="search" autocomplete="off">
 <ul id="results"></ul>

We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.

Here is the JQuery.

$(document).ready(function() {  

    // Icon Click Focus

    //Listen for the event
    $("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $(this).data('timer', setTimeout(search, 100));

// Live Search
// On Search Submit and Get Results
function search() {
    var query_value = $('input#search').val();
    if(query_value !== ''){
            type: "POST",
            url: "search_st.php",
            data: { query: query_value },
            cache: false,
            success: function(html){

    }return false;    

}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.

Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.

// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);

$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = "SELECT *
        FROM animals
        WHERE type REGEXP '^".$search_string."'
        FROM birf
        WHERE type REGEXP '^".$search_string."'"

$result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
        $display_url = ''.urlencode($result['type']).'&ie=utf-8&oe=utf-8';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Description
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);

            // Output

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

How to set a ripple effect on textview or imageview on Android?

Using libraries. This is one of them. Just add its dependency and put below code in xml before each elements that needs ripple effect:


error LNK2005, already defined?

Why this error?

You broke the one definition rule and hence the linking error.

Suggested Solutions:

If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.

    int k;

If you need to share the same variable across multiple files then you need to use extern.


extern int k;


#include "A.h"
int k = 0;


#include "A.h"

//Use `k` anywhere in the file 

How to get GET (query string) variables in Express.js on Node.js?

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);

    }).on("error", (err) => {
        console.log("GET Error: " + err);

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured domains and ssl. so these two lines would change:

https = require("https");
https.get(url.format(requestUrl), (resp) => { ......

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

Skype is usually the culprit because it uses port 80 by default. Just close it or uncheck "Use port 80 and 443 as alternatives for incoming connections" under tools > options... > advanced > connection and then restart Skype.

download and install visual studio 2008

For Microsoft Visual C++ 2008, not the general Visual Studio (

Google Visual Studio 2008 Express instead of just Visual Studio 2008. Click to the first link that appears which is a download link from Microsoft mentioned above.

Prevent direct access to a php include file

The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.

How to determine if object is in array

i know this is an old post, but i wanted to provide a JQuery plugin version and my code.

// Find the first occurrence of object in list, Similar to $.grep, but stops searching 
function findFirst(a,b){
var i; for (i = 0; i < a.length; ++i) { if (b(a[i], i)) return a[i]; } return undefined;


var product = $.findFirst(arrProducts, function(p) { return == 10 });

In Maven how to exclude resources from the generated jar?

This calls exactly for the using the Maven JAR Plugin

For example, if you want to exclude everything under src/test/resources/ from the final jar, put this:


            <!-- configure JAR build -->


Files under src/test/resources/ will still be available on class-path, they just won't be in resulting JAR.

excel delete row if column contains value from to-remove-list

Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.

  • -Put Original List in Column A -Put To Remove list in Column B -Select both columns, then "Conditional Formatting"
    -Select "Hightlight Cells Rules" --> "Duplicate Values"
    -The duplicates should be hightlighted in both columns
    -Then select Column A and then "Sort & Filter" ---> "Custom Sort"
    -In the dialog box that appears, select the middle option "Sort On" and pick "Cell Color"
    -Then select the next option "Sort Order" and choose "No Cell Color" "On bottom"
    -All the highlighted cells should be at the top of the list. -Select all the highlighted cells by scrolling down the list, then click delete.

Default SecurityProtocol in .NET 4.5

The default System.Net.ServicePointManager.SecurityProtocol in both .NET 4.0/4.5 is SecurityProtocolType.Tls|SecurityProtocolType.Ssl3.

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

However, an application targeting .NET 4.0 can still support up to TLS 1.2 if .NET 4.5 is installed in the same environment. .NET 4.5 installs on top of .NET 4.0, replacing System.dll.

I've verified this by observing the correct security protocol set in traffic with fiddler4 and by manually setting the enumerated values in a .NET 4.0 project:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;


namespace System.Net
    public enum SecurityProtocolType
       Ssl3 = 48,
       Tls = 192,
       Tls11 = 768,
       Tls12 = 3072,

If you attempt the hack on an environment with ONLY .NET 4.0 installed, you will get the exception:

Unhandled Exception: System.NotSupportedException: The requested security protocol is not supported. at System.Net.ServicePointManager.set_SecurityProtocol(SecurityProtocolType v alue)

However, I wouldn't recommend this "hack" since a future patch, etc. may break it.*

Therefore, I've decided the best route to remove support for SSLv3 is to:

  1. Upgrade all applications to .NET 4.5
  2. Add the following to boostrapping code to override the default and future proof it:

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

*Someone correct me if this hack is wrong, but initial tests I see it works

How to name and retrieve a stash by name in git?

This is one way to accomplish this using PowerShell:

Restores (applies) a previously saved stash based on full or partial stash name.

Restores (applies) a previously saved stash based on full or partial stash name and then optionally drops the stash. Can be used regardless of whether "git stash save" was done or just "git stash". If no stash matches a message is given. If multiple stashes match a message is given along with matching stash info.

.PARAMETER message
A full or partial stash message name (see right side output of "git stash list"). Can also be "@stash{N}" where N is 0 based stash index.

If -drop is specified, the matching stash is dropped after being applied.

Restore-Stash "Readme change"
Apply-Stash MyStashName
Apply-Stash MyStashName -drop
Apply-Stash "stash@{0}"
function Restore-Stash  {
    PARAM (
        [Parameter(Mandatory=$true)] $message,         

    $stashId = $null

    if ($message -match "stash@{") {
        $stashId = $message

    if (!$stashId) {
        $matches = git stash list | Where-Object { $_ -match $message }

        if (!$matches) {
            Write-Warning "No stashes found with message matching '$message' - check git stash list"

        if ($matches.Count -gt 1) {
            Write-Warning "Found $($matches.Count) matches for '$message'. Refine message or pass 'stash{@N}' to this function or git stash apply"
            return $matches

        $parts = $matches -split ':'
        $stashId = $parts[0]

    git stash apply ''$stashId''

    if ($drop) {
        git stash drop ''$stashId''

More details here

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

Programmatically find the number of cores on a machine

OS X alternative: The solution described earlier based on [[NSProcessInfo processInfo] processorCount] is only available on OS X 10.5.0, according to the docs. For earlier versions of OS X, use the Carbon function MPProcessors().

If you're a Cocoa programmer, don't be freaked out by the fact that this is Carbon. You just need to need to add the Carbon framework to your Xcode project and MPProcessors() will be available.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How do I pass multiple ints into a vector at once?

using vector::insert (const_iterator position, initializer_list il);

#include <iostream>
#include <vector>

int main() {
  std::vector<int> vec;
  return 0;

How to achieve pagination/table layout with Angular.js?

I would use table and implement the pagination in the controller to control how much is shown and buttons to move to the next page. This Fiddle might help you.

example of the pagination

 <table class="table table-striped table-condensed table-hover">
                        <th class="id">Id&nbsp;<a ng-click="sort_by('id')"><i class="icon-sort"></i></a></th>
                        <th class="name">Name&nbsp;<a ng-click="sort_by('name')"><i class="icon-sort"></i></a></th>
                        <th class="description">Description&nbsp;<a ng-click="sort_by('description')"><i class="icon-sort"></i></a></th>
                        <th class="field3">Field 3&nbsp;<a ng-click="sort_by('field3')"><i class="icon-sort"></i></a></th>
                        <th class="field4">Field 4&nbsp;<a ng-click="sort_by('field4')"><i class="icon-sort"></i></a></th>
                        <th class="field5">Field 5&nbsp;<a ng-click="sort_by('field5')"><i class="icon-sort"></i></a></th>
                    <td colspan="6">
                        <div class="pagination pull-right">
                                <li ng-class="{disabled: currentPage == 0}">
                                    <a href ng-click="prevPage()">« Prev</a>
                                <li ng-repeat="n in range(pagedItems.length)"
                                    ng-class="{active: n == currentPage}"
                                    <a href ng-bind="n + 1">1</a>
                                <li ng-class="{disabled: currentPage == pagedItems.length - 1}">
                                    <a href ng-click="nextPage()">Next »</a>
                    <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">

the $scope.range in the fiddle example should be:

$scope.range = function (size,start, end) {
    var ret = [];        
    console.log(size,start, end);

       if (size < end) {
        end = size;
             start = 0;
             start = size-$;

    for (var i = start; i < end; i++) {
    return ret;

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I got the error when building an R package (using roxygen2)

The cause in my case was that I had saved data/mydata.RData with saveRDS() rather than save(). E.g. save(iris, file="data/iris.RData")

This fixed the issue for me. I found this info here

Also note that with save() / load() the object is loaded in with the same name it is initially saved with (i.e you can't rename it until it's already loaded into the R environment under the name it had when you initially saved it).

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

What are the differences in die() and exit() in PHP?

As all the other correct answers says, die and exit are identical/aliases.

Although I have a personal convention that when I want to end the execution of a script when it is expected and desired, I use exit;. And when I need to end the execution due to some problems (couldn't connect to db, can't write to file etc.), I use die("Something went wrong."); to "kill" the script.

When I use exit:

header( "Location:" ); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit; // I would like to end now.

When I use die:

$data = file_get_contents( "file.txt" );
if( $data === false ) {
    die( "Failure." ); // I don't want to end, but I can't continue. Die, script! Die!
do_something_important( $data );

This way, when I see exit at some point in my code, I know that at this point I want to exit because the logic ends here. When I see die, I know that I'd like to continue execution, but I can't or shouldn't due to error in previous execution.

Of course this only works when working on a project alone. When there is more people nobody will prevent them to use die or exit where it does not fit my conventions...

How to execute mongo commands through shell scripts?

Create a script file; write commands:

mongo < file.js

In file.js write your mongo query:


No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Why the error is raised:

JavaScript code is limited by the same-origin policy, meaning, from a page at, you can only make (AJAX) requests to services located at exactly the same domain, in that case, exactly (not - without the www - or

In your case, your Ajax code is trying to reach a service in from a page located at

Although very similar, they are not the same domain. And when they are not on the same domain, the request will only be successful if the target's respose contains a Access-Control-Allow-Origin header in it.

As your page/service at was never configured to present such header, that error message is shown.


As said, the origin (where the page with JavaScript is at) and the target (where the JavaScript is trying to reach) domains must be the exact same.

Your case seems like a typo. Looks like and are actually the same server/domain. So to fix, type the target and the origin equally: make you Ajax code request pages/services to not (Maybe place the target URL relatively, like '/login.php', without the domain).

On a more general note:

If the problem is not a typo like the one of this question seems to be, the solution would be to add the Access-Control-Allow-Origin to the target domain. To add it, depends, of course, of the server/language behind that address. Sometimes a configuration variable in the tool will do the trick. Other times you'll have to add the headers through code yourself.

How to pass multiple parameters in thread in VB

Just create a class or structure that has two members, one List(Of OneItem) and the other Integer and send in an instance of that class.

Edit: Sorry, missed that you had problems with one parameter as well. Just look at Thread Constructor (ParameterizedThreadStart) and that page includes a simple sample.

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

# Copying columns in pandas without slice warning
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

# creates new column 'E' with values -99
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

# creates new column 'F' with values -99
# Copy command only overwrites values which meet criteria 'B'>0
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

git add, commit and push commands in one?

When you want svn-like behavior of git commit, use this in your git aliases in your .gitconfig

commit = "!f() { git commit \"$@\" && git push; };f"

iOS - UIImageView - how to handle UIImage image orientation

extension UIImage {
    func fixImageOrientation() -> UIImage {
        self.draw(at: .zero)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        return newImage ?? self
  1. Create extension like top example.
  2. Call it: imageView.image?.fixImageOrientation() or UIImage(named: "someImage").fixImageOrientation()

  3. Good luck all!

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]


list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"



Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

TypeError: window.initMap is not a function

Could be your initMap function is in a $(document).ready function. If it is then it won't work, it has to be outside of any other functions.

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="" async defer></script>

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?


By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.


08034448845 won't work

but +2348034448845 will

python: How do I know what type of exception occurred?

Here's how I'm handling my exceptions. The idea is to do try solving the issue if that's easy, and later add a more desirable solution if possible. Don't solve the issue in the code that generates the exception, or that code loses track of the original algorithm, which should be written to-the-point. However, pass what data is needed to solve the issue, and return a lambda just in case you can't solve the problem outside of the code that generates it.

path = 'app.p'

def load():
    if os.path.exists(path):
            with open(path, 'rb') as file:
                data =
                inst = pickle.load(data)
        except Exception as e:
            inst = solve(e, 'load app data', easy=lambda: App(), path=path)()
        inst = App()

# e.g. A solver could search for app data if desc='load app data'
def solve(e, during, easy, **kwargs):
    class_name = e.__class__.__name__
    print(class_name + ': ' + str(e))
    print('\t during: ' + during)
    return easy

For now, since I don't want to think tangentially to my app's purpose, I haven't added any complicated solutions. But in the future, when I know more about possible solutions (since the app is designed more), I could add in a dictionary of solutions indexed by during.

In the example shown, one solution might be to look for app data stored somewhere else, say if the 'app.p' file got deleted by mistake.

For now, since writing the exception handler is not a smart idea (we don't know the best ways to solve it yet, because the app design will evolve), we simply return the easy fix which is to act like we're running the app for the first time (in this case).

Current user in Magento?

You can get current login customer name from session in following way :

$customer = Mage::getSingleton('customer/session')->getCustomer();

This will return the customer details of current login customer.

Now you can get customer name by using getName()

echo $customer->getName();

Git push failed, "Non-fast forward updates were rejected"

I encountered the same error, just add "--force" to the command, it works

git push origin master --force

In Bootstrap 3,How to change the distance between rows in vertical?

Use <br> tags

<div class="container">   
    <div class="row" id="a">
        <img src="">

    <br><br> <!--insert one, two, or more here-->

    <div class="row" id="b">

JavaScript operator similar to SQL "like"

No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.

EDIT: This has been answered before:

Emulating SQL LIKE in JavaScript

How to add a “readonly” attribute to an <input>?

I think "disabled" excludes the input from being sent on the POST

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

How can I do an OrderBy with a dynamic string parameter?

If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.

The OrderBy() clause accepts a Func<TSource, TKey> that gets a sort key from a source element. You can define the function outside the OrderBy() clause:

Func<Item, Object> orderByFunc = null;

You can then assign it to different values depending on the sort criteria:

if (sortOrder == SortOrder.SortByName)
  orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
  orderByFunc = item => item.Rank;

Then you can sort:

var sortedItems = items.OrderBy(orderByFunc);

This example assumes that the source type is Item that have properties Name and Rank.

Note that in this example TKey is Object to not constrain the property types that can be sorted on. If the func returns a value type (like Int32) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey to a specific value type you can work around this problem.

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

Adding close button in div to close the box

it's easy with the id of the div container : (I didn't put the close button inside the <a> because that's does work properly on all browser.

<div id="myDiv">
<button class="close" onclick="document.getElementById('myDiv').style.display='none'" >Close</button>
<a class="fragment" href="">
    <img src ="" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 

What is the 'new' keyword in JavaScript?

so it's probably not for creating instances of object

It's used exactly for that. You define a function constructor like so:

function Person(name) { = name;

var john = new Person('John');

However the extra benefit that ECMAScript has is you can extend with the .prototype property, so we can do something like...

Person.prototype.getName = function() { return; }

All objects created from this constructor will now have a getName because of the prototype chain that they have access to.

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)


data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Understanding React-Redux and mapStateToProps()

I would like to re-structure the statement that you mentioned which is:

This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store

You can say that the state consumed by your target component has a small portion of the state that is stored on the redux store. In other words, the state consumed by your component would be the sub-set of the state of the redux store.

As far as understanding the connect() method is concerned, it's fairly simple! connect() method has the power to add new props to your component and even override existing props. It is through this connect method that we can access the state of the redux store as well which is thrown to us by the Provider. A combination of which works in your favor and you get to add the state of your redux store to the props of your component.

Above is some theory and I would suggest you look at this video once to understand the syntax better.

Calling a function from a string in C#

This code works in my console .Net application
class Program
    static void Main(string[] args)
        string method = args[0]; // get name method
    public static void CallMethod(string method)
            Type type = typeof(Program);
            MethodInfo methodInfo = type.GetMethod(method);
            methodInfo.Invoke(method, null);
        catch(Exception ex)
            Console.WriteLine("Error: " + ex.Message);
    public static void Hello()
        string a = "hello world!";

How to detect scroll position of page using jQuery

$(window).scroll( function() { 
 var scrolled_val = $(document).scrollTop().valueOf();
 alert(scrolled_val+ ' = scroll value');

This is another way of getting the value of scroll.

How do I set the icon for my application in visual studio 2008?

I don't know if in VS 2008 is any different, but none of the above worked for me. Double-clicking My Project in Solution Explorer brings up the window seen below. Select Application on the left, then browse for your icon using the combobox. After you build, it should show up on your exe file.

enter image description here

How do you run a .bat file from PHP?

 pclose(popen("start /B test.bat", "r")); die();

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="">
<head id="Head1"><title></title></head>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
   = 'red';
    <!-- Note this part -->

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="">
<head id="Head1"><title></title></head>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
   = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:

For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 

How to access Anaconda command prompt in Windows 10 (64-bit)

How to add anaconda installation directory to your PATH variables

1. open environmental variables window

Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).

Then click on environment variables

If you struggle with this step read this explanation.

2. Edit Path in the user environmental variables section and add three new entries:

  • D:\path\to\anaconda3
  • D:\path\to\anaconda3\Scripts
  • D:\path\to\anaconda3\Library\bin

D:\path\to\anaconda3 should be the folder where you have installed anaconda

Click [OK] on all opened windows.

If you did everything correctly, you can test a conda command by opening a new powershell window.

conda --version

This should output something like: conda 4.8.2

How to run a program automatically as admin on Windows 7 at startup?

This is not possible.
However, you can create a service that runs under an administrative user.

The service can run automatically at startup and communicate with your existing application.
When the application needs to do something as an administrator, it can ask the service to do it for it.

Remember that multiple users can be logged on at once.

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

Radio/checkbox alignment in HTML/CSS

I found the best and easiest way to do it is this one because you don't need to add labels, divs or whatsoever.

input { vertical-align: middle; margin-top: -1px;}

pow (x,y) in Java

^ is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow.

Changing every value in a hash in Ruby

The best way to modify a Hash's values in place is

hash.update(hash){ |_,v| "%#{v}%" }

Less code and clear intent. Also faster because no new objects are allocated beyond the values that must be changed.

Check string for nil & empty

This is a general solution for all types that conform to the Collection protocol, which includes String:

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        self?.isEmpty ?? true

How to use LocalBroadcastManager?

When you'll play enough with LocalBroadcastReceiver I'll suggest you to give Green Robot's EventBus a try - you will definitely realize the difference and usefulness of it compared to LBR. Less code, customizable about receiver's thread (UI/Bg), checking receivers availability, sticky events, events could be used as data delivery etc.

Allow 2 decimal places in <input type="number">

Try this for allowing only 2 decimal in input type

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);

How to enable PHP's openssl extension to install Composer?

I faced the same problem, but when i was lokking for php.ini and php.exe i found php.exe at C:\UwAmp\bin\php\php-5.4.15 when php.ini at C:\UwAmp\bin\apache. I just copy php.ini at C:\UwAmp\bin\php\php-5.4.15 and Uncomment the line extension=php_openssl.dll and it fixed.

How can I use Helvetica Neue Condensed Bold in CSS?

You would have to turn your font into a web font as shown in these SO questions:

However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.

One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.

One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.

Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.

How do I compute the intersection point of two lines?

img And You can use this kode

class Nokta:
def __init__(self,x,y):
class Dogru:
def __init__(self,a,b):

def Kesisim(self,Dogru_b):
    x1= self.a.x
    y1= self.a.y
    #Notlardaki denklemleri kullandim
    pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))      
    pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
    payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))        

    if pay1==0 and pay2==0 and payda==0:

    elif payda==0:               
        print("DOGRULAR BIRBIRNE PARALELDIR")        
        ua=pay1/payda if payda else 0                   
        ub=pay2/payda  if payda else 0  
        #x ve y buldum 
        print("DOGRULAR {},{} NOKTASINDA KESISTI".format(x,y))

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Setting DEBUG = False causes 500 Error

I have the similar issue, in my case it was caused by having a Commented script inside the body tag.

<!--<script>  </script>-->

AngularJs event to call after content is loaded

If you want certain element to completely loaded, Use ng-init on that element .

e.g. <div class="modal fade" id="modalFacultyInfo" role="dialog" ng-init="initModalFacultyInfo()"> ..</div>

the initModalFacultyInfo() function should exist in the controller.

How to get package name from anywhere?

Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -

public class MyApplicationName extends Application {

    private final String PACKAGE_NAME = "com.mysite.myAppPackageName";

    public String getPackageName() { return PACKAGE_NAME; }

Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.

Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -


Then, to obtain the package name from any other module, enter

MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();

Using an application module also gives you a context for modules that need but don't have a context.

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

Your pizza can have exactly three topping types:

  • one type of cheese
  • one type of meat
  • one type of vegetable

So we order two pizzas and choose the following toppings:

Pizza    Topping     Topping Type
-------- ----------  -------------
1        mozzarella  cheese
1        pepperoni   meat
1        olives      vegetable
2        mozzarella  meat
2        sausage     cheese
2        peppers     vegetable

Wait a second, mozzarella can't be both a cheese and a meat! And sausage isn't a cheese!

We need to prevent these sorts of mistakes, to make mozzarella always be cheese. We should use a separate table for this, so we write down that fact in only one place.

Pizza    Topping
-------- ----------
1        mozzarella
1        pepperoni
1        olives
2        mozzarella 
2        sausage
2        peppers

Topping     Topping Type
----------  -------------
mozzarella  cheese
pepperoni   meat
olives      vegetable
sausage     meat
peppers     vegetable

That was the explanation that an 8 year-old might understand. Here is the more technical version.

BCNF acts differently from 3NF only when there are multiple overlapping candidate keys.

The reason is that the functional dependency X -> Y is of course true if Y is a subset of X. So in any table that has only one candidate key and is in 3NF, it is already in BCNF because there is no column (either key or non-key) that is functionally dependent on anything besides that key.

Because each pizza must have exactly one of each topping type, we know that (Pizza, Topping Type) is a candidate key. We also know intuitively that a given topping cannot belong to different types simultaneously. So (Pizza, Topping) must be unique and therefore is also a candidate key. So we have two overlapping candidate keys.

I showed an anomaly where we marked mozarella as the wrong topping type. We know this is wrong, but the rule that makes it wrong is a dependency Topping -> Topping Type which is not a valid dependency for BCNF for this table. It's a dependency on something other than a whole candidate key.

So to solve this, we take Topping Type out of the Pizzas table and make it a non-key attribute in a Toppings table.

get dictionary key by value

I was in a situation where Linq binding was not available and had to expand lambda explicitly. It resulted in a simple function:

public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
    T key = default;
    foreach (KeyValuePair<T, W> pair in dict)
        if (EqualityComparer<W>.Default.Equals(pair.Value, val))
            key = pair.Key;
    return key;

Call it like follows:

public static void Main()
    Dictionary<string, string> dict = new Dictionary<string, string>()
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}

    string key = KeyByValue(dict, "two");       
    Console.WriteLine("Key: " + key);

Works on .NET 2.0 and in other limited environments.

How to "grep" out specific line ranges of a file

Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:

sed "/First Line of Text/,/Last Line of Text/d" filename

which deletes all lines from the first matched line to the last match, including those lines.

Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.

How to zip a whole folder using PHP

For anyone reading this post and looking for a why to zip the files using addFile instead of addFromString, that does not zip the files with their absolute path (just zips the files and nothing else), see my question and answer here

Function to close the window in Tkinter

def quit(self):

Add parentheses after destroy to call the method.

When you use command=self.root.destroy you pass the method to Tkinter.Button without the parentheses because you want Tkinter.Button to store the method for future calling, not to call it immediately when the button is created.

But when you define the quit method, you need to call self.root.destroy() in the body of the method because by then the method has been called.

Laravel Eloquent where field is X or null

It sounds like you need to make use of advanced where clauses.

Given that search in field1 and field2 is constant we will leave them as is, but we are going to adjust your search in datefield a little.

Try this:

$query = Model::where('field1', 1)
    ->where(function ($query) {
        $query->where('datefield', '<', $date)

If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql() to the end of your eloquent query to generate the SQL.

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));

    foreach (T entity in item)
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
            values[i] = properties[i].GetValue(entity);

    return dataTable;

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
$ service docker status
status: unknown job: docker
$ exit
$ su -
$ service docker status
docker start/running, process 2342

How to convert JSON string to array

    "action" : "create",
    "record" : {
                "type": "$product",
                "fields": {
                           "name": "Bread",
                           "price": "2.11"
                "namespaces": { "my.demo": "n" }
echo $str;
echo "<br>";
$jsonstr = json_decode($str, true);


i think this should Work, its just that the Keys should also be in double quotes if they are not numerals.

How to read request body in an core webapi controller?

To be able to rewind the request body, @Jean's answer helped me come up with a solution that seems to work well. I currently use this for Global Exception Handler Middleware but the principle is the same.

I created a middleware that basically enables the rewind on the request body (instead of a decorator).

using Microsoft.AspNetCore.Http.Internal;
public class EnableRequestRewindMiddleware
    private readonly RequestDelegate _next;

    public EnableRequestRewindMiddleware(RequestDelegate next)
        _next = next;

    public async Task Invoke(HttpContext context)
        await _next(context);

public static class EnableRequestRewindExtension
    public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder)
        return builder.UseMiddleware<EnableRequestRewindMiddleware>();

This can then be used in your Startup.cs like so:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

Using this approach, I have been able to rewind the request body stream successfully.

ls command: how can I get a recursive full-path listing, one line per file?

Using no external commands other than ls:

ls -R1 /path | 
  while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done

How to change the name of a Django app?

Why not just use the option Find and Replace. (every code editor has it)?

For example Visual Studio Code (under Edit option):

Visual Studio Code option: 'Replace in files'

You just type in old name and new name and replace everyhting in the project with one click.

NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/ rename it to templates/my_app_new_name/

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:


df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.


Including external jar-files in a new jar-file build with Ant

You can use a bit of functionality that is already built in to the ant jar task.

If you go to The documentation for the ant jar task and scroll down to the "merging archives" section there's a snippet for including the all the *.class files from all the jars in you "lib/main" directory:

<jar destfile="build/main/checksites.jar">
    <fileset dir="build/main/classes"/>
        <name name="**/*.class"/>
                <fileset dir="lib/main" includes="**/*.jar"/>
      <attribute name="Main-Class" value="com.acme.checksites.Main"/>

This Creates an executable jar file with a main class "com.acme.checksites.Main", and embeds all the classes from all the jars in lib/main.

It won't do anything clever in case of namespace conflicts, duplicates and things like that. Also, it will include all class files, also the ones that you don't use, so the combined jar file will be full size.

If you need more advanced things like that, take a look at like one-jar and jar jar links

python: after installing anaconda, how to import pandas

  1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

  2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

  3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

How to get current time and date in Android

You can use the code:

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());


2014-11-11 00:47:55

You also get some more formatting options for SimpleDateFormat from here.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

failed to open stream: HTTP wrapper does not support writeable connections

you could use fopen() function.

some example:

$url = '';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';

    $newfname = $destination_folder .'myfile.mp4'; //set your file ext

    $file = fopen ($url, "rb");

    if ($file) {
      $newf = fopen ($newfname, "a"); // to overwrite existing file

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );


    if ($file) {

    if ($newf) {

Is it possible to put a ConstraintLayout inside a ScrollView?


I had a problem with ConstraintLayout and ScrollView when i wanted to include it in another layout.


The solution to my problem was to use dataBinding.

dataBinding (layout)

How to collapse blocks of code in Eclipse?

In CFEclipse: Preferences > CFEclipse > Editor > Code Folding > Initially Collapse column, you can uncheck to see all expanded when opening, or check all boxes to close all when opening a file.

ClassCastException, casting Integer to Double

Integer x=10;
Double y = x.doubleValue();

Search text in stored procedure in SQL Server

Select distinct OBJECT_NAME(id) from syscomments where text like '%string%' AND OBJECTPROPERTY(id, 'IsProcedure') = 1 

Value Change Listener to JTextField

it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.

  // Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
  public void removeUpdate(DocumentEvent e) {
  public void insertUpdate(DocumentEvent e) {

  public void warn() {
     if (textField.getText().length()>0){
          "Error: Please enter number bigger than 0", "Error Massage",

Programmatically register a broadcast receiver

According to Listening For and Broadcasting Global Messages, and Setting Alarms in Common Tasks and How to Do Them in Android:

If the receiving class is not registered using in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver().

Take a look at registerReceiver (BroadcastReceiver receiver, IntentFilter filter) for more info.

C# Clear Session

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

What is the difference between Session.Abandon() and Session.Clear()

Clear - Removes all keys and values from the session-state collection.

Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out. It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.


Generally, in most cases you need to use Session.Clear. You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  • Abandon raises Session_End request.
  • Clear removes items immediately, Abandon does not.
  • Abandon releases the SessionState object and its items so it can garbage collected.
  • Clear keeps SessionState and resources associated with it.

Session.Clear() or Session.Abandon() ?

You use Session.Clear() when you don't want to end the session but rather just clear all the keys in the session and reinitialize the session.

Session.Clear() will not cause the Session_End eventhandler in your Global.asax file to execute.

But on the other hand Session.Abandon() will remove the session altogether and will execute Session_End eventhandler.

Session.Clear() is like removing books from the bookshelf

Session.Abandon() is like throwing the bookshelf itself.


I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?


If you want the user to login again, use Session.Abandon.

How to convert object array to string array in Java

I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.

First, let's see what Oracle has to say

 * <p>The returned array will be "safe" in that no references to it are
 * maintained by this list.  (In other words, this method must
 * allocate a new array even if this list is backed by an array).
 * The caller is thus free to modify the returned array.

It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?

List<String> tList = new ArrayList<String>();
String tArray[] = (String[]) tList.toArray();   

Probably, many of you would think that this code is doing the same, but it does not.

Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;

When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!

Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;   

So tList.toArray is instantiating a Objects and not Strings...

Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following

String tArray[] = tList.toArray(new String[0]);

Hope it is clear enough.

How to load image files with webpack file-loader

I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.

I used the following settings in the webpack:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.

Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.

I updated my webpack with the following settings

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

I then used the following command to import the images

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />

How to Convert the value in DataTable into a string array in c#

Very easy:

var stringArr = dataTable.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();

Where DataRow.ItemArray property is an array of objects containing the values of the row for each columns of the data table.

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

I had the exact same problem in a project. The issue is that even though the fetch size might be small enough, the JDBCTemplate reads all the result of your query and maps it out in a huge list which might blow your memory. I ended up extending NamedParameterJdbcTemplate to create a function which returns a Stream of Object. That Stream is based on the ResultSet normally returned by JDBC but will pull data from the ResultSet only as the Stream requires it. This will work if you don't keep a reference of all the Object this Stream spits. I did inspire myself a lot on the implementation of org.springframework.jdbc.core.JdbcTemplate#execute(org.springframework.jdbc.core.ConnectionCallback). The only real difference has to do with what to do with the ResultSet. I ended up writing this function to wrap up the ResultSet:

private <T> Stream<T> wrapIntoStream(ResultSet rs, RowMapper<T> mapper) {
    CustomSpliterator<T> spliterator = new CustomSpliterator<T>(rs, mapper, Long.MAX_VALUE, NON-NULL | IMMUTABLE | ORDERED);
    Stream<T> stream =, false);
    return stream;
private static class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
    // won't put code for constructor or properties here
    // the idea is to pull for the ResultSet and set into the Stream
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            // you can add some logic to close the stream/Resultset automatically
            if( {
                T mapped = mapper.mapRow(rs, rowNumber++);
                return true;
            } else {
                return false;
        } catch (SQLException) {
            // do something with this Exception

you can add some logic to make that Stream "auto closable", otherwise don't forget to close it when you are done.

CSS: transition opacity on mouse-out?

You're applying transitions only to the :hover pseudo-class, and not to the element itself.

.item {   
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;

.item:hover {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;


If you don't want the transition to affect the mouse-over event, but only mouse-out, you can turn transitions off for the :hover state :

.item:hover {
  -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;


Saving image from PHP URL

Here you go, the example saves the remote image to image.jpg.

function save_image($inPath,$outPath)
{ //Download images from remote server
    $in=    fopen($inPath, "rb");
    $out=   fopen($outPath, "wb");
    while ($chunk = fread($in,8192))
        fwrite($out, $chunk, 8192);


Get File Path (ends with folder)

In the VBA Editor's Tools menu, click References... scroll down to "Microsoft Shell Controls And Automation" and choose it.

Sub FolderSelection()
    Dim MyPath As String
    MyPath = SelectFolder("Select Folder", "")
    If Len(MyPath) Then
        MsgBox MyPath
        MsgBox "Cancel was pressed"
    End If
End Sub

'Both arguements are optional. The first is the dialog caption and
'the second is is to specify the top-most visible folder in the
'hierarchy. The default is "My Computer."

Function SelectFolder(Optional Title As String, Optional TopFolder _
                         As String) As String
    Dim objShell As New Shell32.Shell
    Dim objFolder As Shell32.Folder

'If you use 16384 instead of 1 on the next line,
'files are also displayed
    Set objFolder = objShell.BrowseForFolder _
                            (0, Title, 1, TopFolder)
    If Not objFolder Is Nothing Then
        SelectFolder = objFolder.Items.Item.Path
    End If
End Function

Source Link.

What are the most common naming conventions in C?

There could be many, mainly IDEs dictate some trends and C++ conventions are also pushing. For C commonly:

  • UNDERSCORED_UPPER_CASE (macro definitions, constants, enum members)
  • underscored_lower_case (variables, functions)
  • CamelCase (custom types: structs, enums, unions)
  • uncappedCamelCase (oppa Java style)
  • UnderScored_CamelCase (variables, functions under kind of namespaces)

Hungarian notation for globals are fine but not for types. And even for trivial names, please use at least two characters.

MySql export schema without data

You Can Use MYSQL Administrator Tool its free

you'll find many options to export ur MYSQL DataBase

python capitalize first letter only

Only because no one else has mentioned it:

>>> 'bob'.title()
>>> 'sandy'.title()
>>> '1bob'.title()
>>> '1sandy'.title()

However, this would also give

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()

i.e. it doesn't just capitalize the first alphabetic character. But then .capitalize() has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob', so meh.

Implementing Singleton with an Enum (in Java)

Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.

I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum.

Maximum Length of Command Line String

In Windows 10, it's still 8191 least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

The Get-ChildItem cmdlet has an -Exclude parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:

function GetFiles($path = $pwd, [string[]]$exclude) 
    foreach ($item in Get-ChildItem $path)
        if ($exclude | Where {$item -like $_}) { continue }

        if (Test-Path $item.FullName -PathType Container) 
            GetFiles $item.FullName $exclude

HTML/Javascript Button Click Counter

After looking at the code you're having typos, here is the updated code

var clicks = 0; // should be var not int
    function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit


Note: Don't use in-built handlers, as .click() is javascript function try giving different name like clickME()

Changing EditText bottom line color with appcompat v7

The accepted answer is a bit more per style basis thing, but the most efficient thing to do is to add the colorAccent attribute in your AppTheme style like this:

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:editTextStyle">@style/EditTextStyle</item>

<style name="EditTextStyle" parent="Widget.AppCompat.EditText"/>

The colorAccent attribute is used for widget tinting throughout the app and thus should be used for consistency

TypeScript function overloading

When you overload in TypeScript, you only have one implementation with multiple signatures.

class Foo {
    myMethod(a: string);
    myMethod(a: number);
    myMethod(a: number, b: string);
    myMethod(a: any, b?: string) {

Only the three overloads are recognized by TypeScript as possible signatures for a method call, not the actual implementation.

In your case, I would personally use two methods with different names as there isn't enough commonality in the parameters, which makes it likely the method body will need to have lots of "ifs" to decide what to do.

TypeScript 1.4

As of TypeScript 1.4, you can typically remove the need for an overload using a union type. The above example can be better expressed using:

myMethod(a: string | number, b?: string) {

The type of a is "either string or number".

Controlling Maven final name of jar artifact

At the package stage, the plugin allows configuration of the imported file names via file mapping:



If you have configured your version to be 'testing' via a profile or something, this would work for a war package:



IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

Pretty straight forward, IIS doesn't have access to your web.config. I'd start by taking the site out of your documents folder. Verify it has r/w permissions then as well.

How to replace a char in string with an Empty character in C#.NET

string val = "123-12-1234";

val = val.Replace("-", ""); // result: 123121234

How to handle click event in Button Column in Datagridview?

You will add button column like this in your dataGridView

        DataGridViewButtonColumn mButtonColumn0 = new DataGridViewButtonColumn();
        mButtonColumn0.Name = "ColumnA";
        mButtonColumn0.Text = "ColumnA";

        if (dataGridView.Columns["ColumnA"] == null)
            dataGridView.Columns.Insert(2, mButtonColumn0);

Then you can add some actions inside cell click event. I found this is easiest way of doing it.

    private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)

        int rowIndex = e.RowIndex;
        int columnIndex = e.ColumnIndex;

        if (dataGridView.Rows[rowIndex].Cells[columnIndex].Selected == true && dataGridView.Columns[columnIndex].Name == "ColumnA")
               //.... do any thing here.


I found that Cell Click event is automatically subscribed often. So I did not need this code below. However, if your cell click event is not subscribed, then add this line of code for your dataGridView.

     this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick);

sh: 0: getcwd() failed: No such file or directory on cited drive

In my case nothing above has worked. After banging my head against the wall for a while I've found out, that I've destroyed the /etc/passwd entries by running a custom-made-linux-server-setup-bash-script which worked well previously, but this time the regex within the "sed" command erased all the existing entries :D After copy pasting the default entries from another working linux server I could finally restart sshd.

So don't forget to backup the original /etc/passwd file before applying any regex replacements on it :)

take(1) vs first()

It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo')), it will emit an error if the stream completes before a value that passes the predicate is emitted.

take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:

const subject$ = new Subject();

// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));

// never does anything


Another example, using a predicate:

const observable$ = of(1, 2, 3);

// logs "no elements in sequence" when the observable completes
 .first((value) => value > 5)
 .subscribe(null, (err) => console.log(err.message));

// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
 .filter((value) => value > 5);

As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:

Throws an error if defaultValue was not provided and a matching element is not found.

The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy lifecycle hook:

class MyComponent implements OnInit, OnDestroy {
  private stream$: Subject = someDelayedStream();
  private destroy$ = new Subject();

  ngOnInit() {$

  ngOnDestroy() {

The code looks harmless at first, but problems arise when the component in destroyed before stream$ can emit a value. Because I'm using first(), an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1) in almost all places where I would have previously used first().

filter(fn).take(1) is a bit more verbose than first(fn), but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.

Also important to note: The same applies for last() and takeLast(1).


add Shadow on UIView using swift 3

loginView.layer.shadowOpacity = 1.0

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

Passing enum or object through an intent (the best solution)

about Oderik's post:

You can make your enum implement Parcelable which is quite easy for enums:

public enum MyEnum implements Parcelable { ... } You can than use Intent.putExtra(String, Parcelable).

If you define a MyEnum variable myEnum, then do intent.putExtra("Parcelable1", myEnum), you will get a "The method putExtra(String, Parcelable) is ambiguous for the type Intent" error message. because there is also a Intent.putExtra(String, Parcelable) method, and original 'Enum' type itself implements the Serializable interface, so compiler does not know choose which method(intent.putExtra(String, Parcelable/or Serializable)).

Suggest that remove the Parcelable interface from MyEnum, and move the core code into wrap class' Parcelable implementation, like this(Father2 is a Parcelable and contain an enum field):

public class Father2 implements Parcelable {

AnotherEnum mAnotherEnum;
int mField;

public Father2(AnotherEnum myEnum, int field) {
    mAnotherEnum = myEnum;
    mField = field;

private Father2(Parcel in) {
    mField = in.readInt();
    mAnotherEnum = AnotherEnum.values()[in.readInt()];

public static final Parcelable.Creator<Father2> CREATOR = new Parcelable.Creator<Father2>() {

    public Father2 createFromParcel(Parcel in) {
        return new Father2(in);

    public Father2[] newArray(int size) {
        return new Father2[size];


public int describeContents() {
    return 0;

public void writeToParcel(Parcel dest, int flags) {


then we can do:

AnotherEnum anotherEnum = AnotherEnum.Z;
intent.putExtra("Serializable2", AnotherEnum.X);   
intent.putExtra("Parcelable2", new Father2(AnotherEnum.X, 7));

Android: how to make keyboard enter button say "Search" and handle its click?

In the layout set your input method options to search.

    android:inputType="text" />

In the java add the editor action listener.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            return true;
        return false;

Error:Unknown host You may need to adjust the proxy settings in Gradle

The problem is you are not able to download gradle from the host specified in gradle/wrapper/

In my case this happened after I refactored the code using Idea. To get this working: 1. Be sure you can download the zip file at URL in the file mentioned above 2. If you can you may wanna check your proxy configuration or env vars

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:


   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:


Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource. Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/ security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security

Issue is that it is failed to decrypt 256 bits of encryption.

Check whether specific radio button is checked


use this and here ClientID fetch random id created by .net.

How to change the time format (12/24 hours) of an <input>?

It depends on the time format of the user's operating system when the web browser was launched.


  • If your computer's system prefs are set to use a 24-hour clock, the browser will render the <input type="time"> element as --:-- (time range: 00:00–23:59).
  • If you change your computer's syst prefs to use 12-hour, the output won't change until you quit and relaunch the browser. Then it will change to --:-- -- (time range: 12:00 AM – 11:59 PM).

And (as of this writing), browser support is only about 75% (caniuse). Yay: Edge, Chrome, Opera, Android. Boo: IE, Firefox, Safari).

Can I open a dropdownlist using jQuery

It is not possible for javascript to "click" on an element (u can trigger the attached onclick event, but you can't literally click it)

To view all the items in the list, make the list a multiple list and increase its size, like such:

<select id="countries" multiple="multiple" size="10">
<option value="1">Country</option>

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I just saw this blog entry: Money vs. Decimal in SQL Server.

Which basically says that money has a precision issue...

declare @m money
declare @d decimal(9,2)

set @m = 19.34
set @d = 19.34

select (@m/1000)*1000
select (@d/1000)*1000

For the money type, you will get 19.30 instead of 19.34. I am not sure if there is an application scenario that divides money into 1000 parts for calculation, but this example does expose some limitations.

Difference between "and" and && in Ruby?

The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:

foo = :foo
bar = nil

a = foo and bar
# => nil
# => :foo

a = foo && bar
# => nil
# => nil

a = (foo and bar)
# => nil
# => nil

(a = foo) && bar
# => nil
# => :foo

The same thing works for || and or.

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)

Get month name from date in Oracle

In Oracle (atleast 11g) database :

If you hit

select to_char(SYSDATE,'Month') from dual;

It gives unformatted month name, with spaces, for e.g. May would be given as 'May '. The string May will have spaces.

In order to format month name, i.e to trim spaces, you need

select to_char(SYSDATE,'fmMonth') from dual;

This would return 'May'.

git: patch does not apply

When all else fails, try git apply's --3way option.

git apply --3way patchFile.patch

When the patch does not apply cleanly, fall back on 3-way merge if the patch records the identity of blobs it is supposed to apply to, and we have those blobs available locally, possibly leaving the conflict markers in the files in the working tree for the user to resolve. This option implies the --index option, and is incompatible with the --reject and the --cached options.

Typical fail case applies as much of the patch as it can, and leaves you with conflicts to work out in git however you normally do so. Probably one step easier than the reject alternative.

Create Carriage Return in PHP String?

$postfields["message"] = "This is a sample ticket opened by the API\rwith a carriage return";

Convert a tensor to numpy array in Tensorflow?

A simple example could be,

    import tensorflow as tf
    import numpy as np
    a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32)  #sampling from a std normal
    #<class 'tensorflow.python.framework.ops.Tensor'>
    tf.InteractiveSession()  # run an interactive session in Tf.

n now if we want this tensor a to be converted into a numpy array

    #<class 'numpy.ndarray'>

As simple as that!

How to throw an exception in C?

As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly.

JPA: unidirectional many-to-one and cascading delete

Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).

You'll therefore need to do this:

  • Either, change the unidirectional @ManyToOne relationship to a bi-directional @ManyToOne, or a unidirectional @OneToMany. You can then cascade REMOVE operations so that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection.
  • Or, specify the foreign key constraint in the child table as ON DELETE CASCADE. You'll need to invoke EntityManager.clear() after calling EntityManager.remove(parent) as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

AFNetworking Post Request

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       height, @"user[height]",
                       weight, @"user[weight]",

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                                             [NSURL URLWithString:@"http://localhost:8080/"]];

[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@", [error localizedDescription]);

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

Extract Google Drive zip from Google colab notebook

Mount GDrive:

from google.colab import drive

Open the link -> copy authorization code -> paste that into the prompt and press "Enter"

Check GDrive access:

!ls "/content/gdrive/My Drive"

Unzip (q stands for "quiet") file from GDrive:

!unzip -q "/content/gdrive/My Drive/"

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

How to check if "Radiobutton" is checked?

You can also maintain a flag value based on listener,

 radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                //handle the boolean flag here. 
                         //Do something

                    //do something else


Or simply isChecked() can also be used to check the state of your RadioButton.

Here is a link to a sample,

And then based on the flag you can execute your function.

Get selected value from combo box in C# WPF

It works for me:

System.Data.DataRowView typeItem = (System.Data.DataRowView)ComboBoxName.SelectedItem;
string value = typeItem.DataView.ToTable("a").Rows[0][0].ToString();

"Integer number too large" error message for 600851475143

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :


How to save image in database using C#

My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.

Run Batch File On Start-up

To start the batch file at the start of your system, you can also use a registry key.


Here you can create a string. As name you can choose anything and the data is the full path to your file.

There is also the registry key


to run something at only the next start of your system.

Access denied for user 'test'@'localhost' (using password: YES) except root user


CREATE USER 'golden'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'@'localhost';

Or even better use: mysql_setpermission to create the user

PHP Call to undefined function

This was a developer mistake - a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long - problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the "undefined function". That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

stringstream, string, and char* conversion confusion

What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.

As soon as the statement const char* cstr2 = ss.str().c_str(); is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char * is pointing to free'd memory.

Your statement string str(ss.str()); means that the temporary is used in the constructor for the string variable str that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char * within is still good memory when you try the cout.

Saving numpy array to txt file row wise

An alternative answer is to reshape the array so that it has dimensions (1, N) like so:

savetext(filename, a.reshape(1, a.shape[0]))

display html page with node.js

Check this basic code to setup html server. its work for me.

var http = require('http'),
    fs = require('fs');

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE `tableName` CHANGE  `columnName` DECIMAL(16,1) NOT NULL;

I uses This for the alterration

Maven Error: Could not find or load main class

For me the problem was nothing to do with Maven but to do with how I was running the .jar. I wrote some code and packaged it as a .jar with Maven. I ran it with

java target/gs-maven-0.1.0.jar

and got the error in the OP. Actually you need the -jar option:

java -jar target/gs-maven-0.1.0.jar

Spring boot - Not a managed type

If you configure your own EntityManagerFactory Bean or if you have copy-pasted such a persistence configuration from another project, you must set or adapt the package in EntityManagerFactory's configuration:

public EntityManagerFactory entityManagerFactory() throws PropertyVetoException {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    LocalContainerEntityManagerFactoryBean factory;
    factory = new LocalContainerEntityManagerFactoryBean();

Checking oracle sid and database name

I presume SELECT user FROM dual; should give you the current user

and SELECT sys_context('userenv','instance_name') FROM dual; the name of the instance

I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>


Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

SQL JOIN - WHERE clause vs. ON clause

There is great difference between where clause vs. on clause, when it comes to left join.

Here is example:

mysql> desc t1; 
| Field | Type        | Null | Key | Default | Extra |
| id    | int(11)     | NO   |     | NULL    |       |
| fid   | int(11)     | NO   |     | NULL    |       |
| v     | varchar(20) | NO   |     | NULL    |       |

There fid is id of table t2.

mysql> desc t2;
| Field | Type        | Null | Key | Default | Extra |
| id    | int(11)     | NO   |     | NULL    |       |
| v     | varchar(10) | NO   |     | NULL    |       |
2 rows in set (0.00 sec)

Query on "on clause" :

mysql> SELECT * FROM `t1` left join t2 on fid = AND t1.v = 'K' 
    -> ;
| id | fid | v | id   | v    |
|  1 |   1 | H | NULL | NULL |
|  2 |   1 | B | NULL | NULL |
|  3 |   2 | H | NULL | NULL |
|  4 |   7 | K | NULL | NULL |
|  5 |   5 | L | NULL | NULL |
5 rows in set (0.00 sec)

Query on "where clause":

mysql> SELECT * FROM `t1` left join t2 on fid = where t1.v = 'K';
| id | fid | v | id   | v    |
|  4 |   7 | K | NULL | NULL |
1 row in set (0.00 sec)

It is clear that, the first query returns a record from t1 and its dependent row from t2, if any, for row t1.v = 'K'.

The second query returns rows from t1, but only for t1.v = 'K' will have any associated row with it.

Show a child form in the centre of Parent form in C#

When you want to use a non-blocking window (show() instead of showDialog()), this not work:

//not work with .Show(this) but only with .ShowDialog(this)
loginForm.StartPosition = FormStartPosition.CenterParent;

In this case, you can use this code to center child form before display the form:

//this = the parent
frmDownloadPercent frm = new frmDownloadPercent();
frm.Show(this); //this = the parent form
//here the tips
frm.Top = this.Top + ((this.Height / 2) - (frm.Height / 2));
frm.Left = this.Left + ((this.Width / 2) - (frm.Width / 2));

converting json to string in python

There are other differences. For instance, {'time':} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Can you explain the HttpURLConnection connection process?

I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.

Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.

enter image description here

Below is my toy program and annotation

    /* Create a connection LOCAL object,
     * the openConnection() function DOES NOT initiate
     * any packet exchange with the remote server.
     * The configurations only setup the LOCAL
     * connection object properties.
    HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
    ...//headers setup
    byte[] testContent = {0x32, 0x32};

     * This triggers packet exchange with the remote
     * server to create a link. But writing/flushing
     * to a output stream does not send out any data.
     * Payload are buffered locally.
    try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {

     * Trigger payload sending to the server.
     * Client get ALL responses (including response code,
     * message, and content payload) 
    int responseCode = connection.getResponseCode();

    /* Here no further exchange happens with remote server, since
     * the input stream content has already been buffered
     * in previous step
    try (InputStream is = connection.getInputStream()) {
        Scanner scanner = new Scanner(is);
        StringBuilder stringBuilder = new StringBuilder();
        while (scanner.hasNextLine()) {

     * Trigger the disconnection from the server.
    String responsemsg = connection.getResponseMessage();

What does elementFormDefault do in XSD?

ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.

Here's the relevent section of the spec:

Element Declaration Schema

Component Property  {target namespace}
Representation      If form is present and its ·actual value· is qualified, 
                    or if form is absent and the ·actual value· of 
                    elementFormDefault on the <schema> ancestor is qualified, 
                    then the ·actual value· of the targetNamespace [attribute]
                    of the parent <schema> element information item, or 
                    ·absent· if there is none, otherwise ·absent·.

What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".

For example: If elementFormDefault is unqualified -

<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>

will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.

To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.

How to add an element to the beginning of an OrderedDict?

FWIW Here is a quick-n-dirty code I wrote for inserting to an arbitrary index position. Not necessarily efficient but it works in-place.

class OrderedDictInsert(OrderedDict):
    def insert(self, index, key, value):
        self[key] = value
        for ii, k in enumerate(list(self.keys())):
            if ii >= index and k != key:

How does a hash table work?

It's even simpler than that.

A hashtable is nothing more than an array (usually sparse one) of vectors which contain key/value pairs. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable.

The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array.

This is where storing vectors of key/value pairs in the array come in. Because the set of values that can be indexes in the array is typically smaller than the number of all possible values that the type can have, it is possible that your hash algorithm is going to generate the same value for two separate keys. A good hash algorithm will prevent this as much as possible (which is why it is relegated to the type usually because it has specific information which a general hash algorithm can't possibly know), but it's impossible to prevent.

Because of this, you can have multiple keys that will generate the same hash code. When that happens, the items in the vector are iterated through, and a direct comparison is done between the key in the vector and the key that is being looked up. If it is found, great and the value associated with the key is returned, otherwise, nothing is returned.

HTML table with fixed headers?

I found this workaround - move header row in a table above table with data:

 <title>Fixed header</title>_x000D_
  table td {width:75px;}_x000D_
<div style="height:auto; width:350px; overflow:auto">_x000D_
<table border="1">_x000D_
 <td>header 1</td>_x000D_
 <td>header 2</td>_x000D_
 <td>header 3</td>_x000D_
<div style="height:50px; width:350px; overflow:auto">_x000D_
<table border="1">_x000D_
 <td>row 1 col 1</td>_x000D_
 <td>row 1 col 2</td>_x000D_
 <td>row 1 col 3</td>  _x000D_
 <td>row 2 col 1</td>_x000D_
 <td>row 2 col 2</td>_x000D_
 <td>row 2 col 3</td>  _x000D_
 <td>row 3 col 1</td>_x000D_
 <td>row 3 col 2</td>_x000D_
 <td>row 3 col 3</td>  _x000D_
 <td>row 4 col 1</td>_x000D_
 <td>row 4 col 2</td>_x000D_
 <td>row 4 col 3</td>  _x000D_
 <td>row 5 col 1</td>_x000D_
 <td>row 5 col 2</td>_x000D_
 <td>row 5 col 3</td>  _x000D_
 <td>row 6 col 1</td>_x000D_
 <td>row 6 col 2</td>_x000D_
 <td>row 6 col 3</td>  _x000D_

javascript createElement(), style problem

Others have given you the answer about appendChild.

Calling document.write() on a page that is not open (e.g. has finished loading) first calls which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.

How to remove backslash on json_encode() function?

the solution that does work is this:

$str = preg_replace('/\\\"/',"\"", $str);

However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).

So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe" in your DB, php will bring this back as My name is \\"Joe\\".

This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:

$str = preg_replace('/\\\\\"/',"\"", $str);

yeah... it's ugly... but it works.

You're then left with something that vaguely resembles actual JSON.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

How to set bot's status

Bumping this all the way from 2018, sorry not sorry. But the newer users questioning how to do this need to know that game does not work anymore for this task.

    game: {
        name: 'with depression',
        type: "STREAMING",
        url: ""

does not work anymore. You will now need to do this:

    status: 'online',
    activity: {
        name: 'with depression',
        type: 'STREAMING',
        url: ''

This is referenced here as "game" is not a valid property of setPresence anymore. Read the PresenceData Documentation for more information about this.

Dynamic height for DIV

as prior ans remove the height attrib. if u want your expansion along with its min height then use min-height: 102px instead of height: 102px.

note ie 6 and min-height

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.

Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

Make sure you aren't connected to a VPN on another domain\user. Or, conversely, make sure you are connected, if that is what is required.

How can I clear the content of a file?

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                    Short_Fall = node.InnerText;


Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")


string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

Convert Current date to integer

On my Java 7, the output is different:

Integer : 1293732698
Long : 1345618496346
Long date : Wed Aug 22 10:54:56 MSK 2012
Int Date : Fri Jan 16 02:22:12 MSK 1970

which is an expected behavior.

It is impossible to display the current date in milliseconds as an integer (10 digit number), because the latest possible date is Sun Apr 26 20:46:39 MSK 1970:

Date d = new Date(9999_9999_99L);
System.out.println("Date: " + d);

Date: Sun Apr 26 20:46:39 MSK 1970

You might want to consider displaying it in seconds/minutes.

Read Excel File in Python

Here is the code to read an excel file and and print all the cells present in column 1 (except the first cell i.e the header):

import xlrd


for row in range(1,sheet.nrows):

How to split a string in Java

You can simply use StringTokenizer to split a string in two or more parts whether there are any type of delimiters:

StringTokenizer st = new StringTokenizer("004-034556", "-");

What are your favorite extension methods for C#? (

These extension methods are pretty useful for me when parsing form input before putting into the database

public static int? ToInt(this string input) 
    int val;
    if (int.TryParse(input, out val))
        return val;
    return null;

public static DateTime? ToDate(this string input)
    DateTime val;
    if (DateTime.TryParse(input, out val))
        return val;
    return null;

public static decimal? ToDecimal(this string input)
    decimal val;
    if (decimal.TryParse(input, out val))
        return val;
    return null;

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Regular Expression For Duplicate Words

Try this with below RE

  • \b start of word word boundary
  • \W+ any word character
  • \1 same word matched already
  • \b end of word
  • ()* Repeating again

    public static void main(String[] args) {
        String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
        Scanner in = new Scanner(;
        int numSentences = Integer.parseInt(in.nextLine());
        while (numSentences-- > 0) {
            String input = in.nextLine();
            Matcher m = p.matcher(input);
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(,;
            // Prints the modified sentence.

"Eliminate render-blocking CSS in above-the-fold content"

A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?

Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!

On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.

The best advice I could give you is:

  • Set width and height on replaced elements in your CSS, so that the browser can layout the elements and doesn't have to wait for the replaced content!

Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.

The things one should always take care of are:

  • reduce the number of requests as much as possible
  • keep your overall page weight as low as possible

And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)

Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.

As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web design it is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT (Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!

Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!

Sync data between Android App and webserver

@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).

Here's a blog post about it:

Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).

Also, if you wish to take a look at the 2015's code:

How to get day of the month?

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    return cal.get(Calendar.DAY_OF_MONTH);

Best way to create an empty map in Java

1) If the Map can be immutable:


// or, in some cases:
Collections.<String, String>emptyMap()

You'll have to use the latter sometimes when the compiler cannot automatically figure out what kind of Map is needed (this is called type inference). For example, consider a method declared like this:

public void foobar(Map<String, String> map){ ... }

When passing the empty Map directly to it, you have to be explicit about the type:

foobar(Collections.emptyMap());                 // doesn't compile
foobar(Collections.<String, String>emptyMap()); // works fine

2) If you need to be able to modify the Map, then for example:

new HashMap<String, String>()

(as tehblanx pointed out)

Addendum: If your project uses Guava, you have the following alternatives:

1) Immutable map:

// or:
ImmutableMap.<String, String>of()

Granted, no big benefits here compared to Collections.emptyMap(). From the Javadoc:

This map behaves and performs comparably to Collections.emptyMap(), and is preferable mainly for consistency and maintainability of your code.

2) Map that you can modify:

// or:
Maps.<String, String>newHashMap()

Maps contains similar factory methods for instantiating other types of maps as well, such as TreeMap or LinkedHashMap.

Update (2018): On Java 9 or newer, the shortest code for creating an immutable empty map is:


...using the new convenience factory methods from JEP 269.

How to disable an input type=text?

document.getElementById('foo').disabled = true;


document.getElementById('foo').readOnly = true;

Note that readOnly should be in camelCase to work correctly in Firefox (magic).

Demo: -- somewhat explains the difference between disabled and readOnly.

Get JSF managed bean by name in any Servlet related class

I had same requirement.

I have used the below way to get it.

I had session scoped bean.

class ManagedBean {

I have used the below code in my servlet doPost() method.

ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");

it solved my problem.