Programs & Examples On #Reportparameter

How do I automatically resize an image for a mobile site?

Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).

A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.

Stopping a JavaScript function when a certain condition is met

The return statement exits a function from anywhere within the function:

function something(x)
{
    if (x >= 10)
        // this leaves the function if x is at least 10.
        return;

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");
}

Warn user before leaving web page with unsaved changes

Built on top of Wasim A.'s excellent idea to use serialization. The problem there was that the warning was also shown when the form was being submitted. This has been fixed here.

var isSubmitting = false

$(document).ready(function () {
    $('form').submit(function(){
        isSubmitting = true
    })

    $('form').data('initial-state', $('form').serialize());

    $(window).on('beforeunload', function() {
        if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
            return 'You have unsaved changes which will not be saved.'
        }
    });
})

It has been tested in Chrome and IE 11.

Best data type for storing currency values in a MySQL database

Assaf's response of

Depends on how much money you got...

sounds flippant, but actually it's pertinant.

Only today we had an issue where a record failed to be inserted into our Rate table, because one of the columns (GrossRate) is set to Decimal (11,4), and our Product department just got a contract for rooms in some amazing resort in Bora Bora, that sell for several million Pacific Francs per night... something that was never anticpated when the database schema was designed 10 years ago.

AngularJS view not updating on model change

Just use $interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

How to style the UL list to a single line

HTML code:

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

CSS code:

ul.list li{
  width: auto;
  float: left;
}

How to make for loops in Java increase by increments other than 1

The "increment" portion of a loop statement has to change the value of the index variable to have any effect. The longhand form of "++j" is "j = j + 1". So, as other answers have said, the correct form of your increment is "j = j + 3", which doesn't have as terse a shorthand as incrementing by one. "j + 3", as you know by now, doesn't actually change j; it's an expression whose evaluation has no effect.

Sorting JSON by values

jQuery isn't particularly helpful for sorting, but here's an elegant and efficient solution. Just write a plain JS function that takes the property name and the order (ascending or descending) and calls the native sort() method with a simple comparison function:

var people = [
    {
        "f_name": "john",
        "l_name": "doe",
        "sequence": "0",
        "title" : "president",
        "url" : "google.com",
        "color" : "333333",
    }
    // etc
];

function sortResults(prop, asc) {
    people.sort(function(a, b) {
        if (asc) {
            return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
        } else {
            return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
        }
    });
    renderResults();
}

Then:

sortResults('l_name', true);

Play with a working example here.

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

Java Reflection Performance

I think it depends on how light/heavy the target method is. if the target method is very light(e.g. getter/setter), It could be 1 ~ 3 times slower. if the target method takes about 1 millisecond or above, then the performance will be very close. here is the test I did with Java 8 and reflectasm :

public class ReflectionTest extends TestCase {    
    @Test
    public void test_perf() {
        Profiler.run(3, 100000, 3, "m_01 by refelct", () -> Reflection.on(X.class)._new().invoke("m_01")).printResult();    
        Profiler.run(3, 100000, 3, "m_01 direct call", () -> new X().m_01()).printResult();    
        Profiler.run(3, 100000, 3, "m_02 by refelct", () -> Reflection.on(X.class)._new().invoke("m_02")).printResult();    
        Profiler.run(3, 100000, 3, "m_02 direct call", () -> new X().m_02()).printResult();    
        Profiler.run(3, 100000, 3, "m_11 by refelct", () -> Reflection.on(X.class)._new().invoke("m_11")).printResult();    
        Profiler.run(3, 100000, 3, "m_11 direct call", () -> X.m_11()).printResult();    
        Profiler.run(3, 100000, 3, "m_12 by refelct", () -> Reflection.on(X.class)._new().invoke("m_12")).printResult();    
        Profiler.run(3, 100000, 3, "m_12 direct call", () -> X.m_12()).printResult();
    }

    public static class X {
        public long m_01() {
            return m_11();
        }    
        public long m_02() {
            return m_12();
        }    
        public static long m_11() {
            long sum = IntStream.range(0, 10).sum();
            assertEquals(45, sum);
            return sum;
        }    
        public static long m_12() {
            long sum = IntStream.range(0, 10000).sum();
            assertEquals(49995000, sum);
            return sum;
        }
    }
}

The complete test code is available at GitHub:ReflectionTest.java

How can you test if an object has a specific property?

I just started using PowerShell with PowerShell Core 6.0 (beta) and following simply works:

if ($members.NoteProperty) {
   # NoteProperty exist
}

or

if (-not $members.NoteProperty) {
   # NoteProperty does not exist
}

How to set opacity to the background color of a div?

I think this covers just about all of the browsers. I have used it successfully in the past.

#div {
    filter: alpha(opacity=50); /* internet explorer */
    -khtml-opacity: 0.5;      /* khtml, old safari */
    -moz-opacity: 0.5;       /* mozilla, netscape */
    opacity: 0.5;           /* fx, safari, opera */
}

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

Java using enum with switch statement

enumerations accessing is very simple in switch case

private TYPE currentView;

//declaration of enum 
public enum TYPE {
        FIRST, SECOND, THIRD
    };

//handling in switch case
switch (getCurrentView())
        {
        case FIRST:
            break;
        case SECOND:
            break;
        case THIRD:
            break;
        }

//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
        this.currentView = currentView;
    }

    public TYPE getCurrentView() {
        return currentView;
    }

//usage of setting the enum 
setCurrentView(TYPE.FIRST);

avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always

What exactly does a jar file contain?

JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.

GridLayout and Row/Column Span Woe

Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="First"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Second"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Third"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"        
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"
    android:text="fourth"/>

</android.support.v7.widget.GridLayout>

How can I bind to the change event of a textarea in jQuery?

Try this

 $('textarea').trigger('change');
 $("textarea").bind('cut paste', function(e) { });

Error in spring application context schema

This happen to me after upgrade eclipse version. What works for me was clean the eclipse cache. Go to Window > Preferences > Network Connection > Cache > Remove All.

I hope this works for anyone!

How to repair a serialized string which has been corrupted by an incorrect byte count length?

The corruption in this question is isolated to a single substring at the end of the serialized string with was probably manually replaced by someone who lazily wanted to update the image filename. This fact will be apparent in my demonstration link below using the OP's posted data -- in short, C:fakepath100.jpg does not have a length of 19, it should be 17.

Since the serialized string corruption is limited to an incorrect byte/character count number, the following will do a fine job of updating the corrupted string with the correct byte count value.

The following regex based replacement will only be effective in remedying byte counts, nothing more.

It looks like many of the earlier posts are just copy-pasting a regex pattern from someone else. There is no reason to capture the potentially corrupted byte count number if it isn't going to be used in the replacement. Also, adding the s pattern modifier is a reasonable inclusion in case a string value contains newlines/line returns.

*For those that are not aware of the treatment of multibyte characters with serializing, you must not use mb_strlen() in the custom callback because it is the byte count that is stored not the character count, see my output...

Code: (Demo with OP's data) (Demo with arbitrary sample data) (Demo with condition replacing)

$corrupted = <<<STRING
a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";}
STRING;

$repaired = preg_replace_callback(
        '/s:\d+:"(.*?)";/s',
        //  ^^^- matched/consumed but not captured because not used in replacement
        function ($m) {
            return "s:" . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted
    );

echo $corrupted , "\n" , $repaired;
echo "\n---\n";
var_export(unserialize($repaired));

Output:

a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
Newline2";i:3;s:6:"garçon";}
a:4:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
Newline2";i:3;s:7:"garçon";}
---
array (
  0 => 'three',
  1 => 'five',
  2 => 'newline1
Newline2',
  3 => 'garçon',
)

One leg down the rabbit hole... The above works fine even if double quotes occur in a string value, but if a string value contains "; or some other monkeywrenching sbustring, you'll need to go a little further and implement "lookarounds". My new pattern

checks that the leading s is:

  • the start of the entire input string or
  • preceded by ;

and checks that the "; is:

  • at the end of the entire input string or
  • followed by } or
  • followed by a string or integer declaration s: or i:

I haven't test each and every possibility; in fact, I am relatively unfamiliar with all of the possibilities in a serialized string because I never elect to work with serialized data -- always json in modern applications. If there are additional possible leading or trailing characters, leave a comment and I'll extend the lookarounds.

Extended snippet: (Demo)

$corrupted_byte_counts = <<<STRING
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
STRING;

$repaired = preg_replace_callback(
        '/(?<=^|;)s:\d+:"(.*?)";(?=$|}|[si]:)/s',
        //^^^^^^^^--------------^^^^^^^^^^^^^-- some additional validation
        function ($m) {
            return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted_byte_counts
    );

echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired));

Output:

corrupted serialized array:
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
---
repaired serialized array:
a:12:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
newline2";i:3;s:7:"garçon";i:4;s:24:"double " quote \"escaped";i:5;s:7:"a,comma";i:6;s:7:"a:colon";i:7;s:13:"single 'quote";i:8;s:10:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:39:"monkey";wrenching doublequote-semicolon";s:2:"s:";s:10:"val s: val";}
---
Array
(
    [0] => three
    [1] => five
    [2] => newline1
newline2
    [3] => garçon
    [4] => double " quote \"escaped
    [5] => a,comma
    [6] => a:colon
    [7] => single 'quote
    [8] => semi;colon
    [assoc] => yes
    [9] => monkey";wrenching doublequote-semicolon
    [s:] => val s: val
)

Check if a Class Object is subclass of another Class Object in Java

Another option is instanceof:

Object o =...
if (o instanceof Number) {
  double d = ((Number)o).doubleValue(); //this cast is safe
}

How do I use HTML as the view engine in Express?

Install ejs template

npm install ejs --save

Refer ejs in app.js

app.set('views', path.join(__dirname, 'views'));`
app.set('view engine', 'ejs');

Create a ejs template in views like views/indes.ejs & use ejs tempalte in router

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

Does a "Find in project..." feature exist in Eclipse IDE?

Ctrl + Alt + G can be used to find selected text across a workspace in eclipse.

OSX: ? Option + ? Command + G

How to display alt text for an image in chrome

You can put title attribute to tag.I hope it will work.

<img src="smiley.gif" title="Smiley face" width="42" height="42">

Use CSS to make a span not clickable

Yes you can.... you can place something on top of the link element.

<!DOCTYPE html>
<html>
<head>
    <title>Yes you CAN</title>
    <style type="text/css">
        ul{
            width: 500px;
            border: 5px solid black; 
        }
        .product-type-simple {
            position: relative;
            height: 150px;
            width: 150px;
        }
        .product-type-simple:before{
            position: absolute;
            height: 100% ;
            width: 100% ;
            content: '';
            background: green;//for debugging purposes , remove this if you want to see whats behind
            z-index: 999999999999;
        }
    </style>
</head>
<body>
<ul>
    <li class='product-type-simple'>
        <a href="/link1">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
    <li class='product-type-simple'>
        <a href="/link2">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
</ul>
</body>
</html>

the magic sauce happens at product-type-simple:before class Whats happening here is that for each element that has class of product-type-simple you create something that has the width and height equal to that of the product-type-simple , then you increase its z-index to make sure it will place it self on top of the content of product-type-simple. You can toggle the background color if you want to see whats going on.

here is an example of the code https://jsfiddle.net/92qky63j/

Unable to copy ~/.ssh/id_rsa.pub

The following is also working for me:

ssh <user>@<host>  "cat <filepath>"|pbcopy 

How to copy selected lines to clipboard in vim

set guioptions+=a

will, ... uhmm, in short, whenever you select/yank something put it in the clipboard as well (not Vim's, but the global keyboard of the window system). That way you don't have to think about yanking things into a special register.

How to push to History in React Router v4?

This is how I did it:

import React, {Component} from 'react';

export default class Link extends Component {
    constructor(props) {
        super(props);
        this.onLogout = this.onLogout.bind(this);
    }
    onLogout() {
        this.props.history.push('/');
    }
    render() {
        return (
            <div>
                <h1>Your Links</h1>
                <button onClick={this.onLogout}>Logout</button>
            </div>
        );
    }
}

Use this.props.history.push('/cart'); to redirect to cart page it will be saved in history object.

Enjoy, Michael.

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

UPDATE:

onActivityCreated() is deprecated from API Level 28.


onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


To sum up...
... they are all called in the Fragment but are called at different times.
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


If you want to view the official Android documentation, it can be found here:

There are also some slightly different, but less developed questions/answers here on Stack Overflow:

How can I programmatically determine if my app is running in the iphone simulator?

Works for Swift 5 and Xcode 12

Use this code:

#if targetEnvironment(simulator)
   // Simulator
#else
   // Device
#endif

Using Postman to access OAuth 2.0 Google APIs

I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.

enter image description here

Space between two divs

Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.

You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically

i.e:

<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px;  }
</style>

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?

Here is a jsfiddle example:

REFERENCE:

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

How to manage local vs production settings in Django?

My solution to that problem is also somewhat of a mix of some solutions already stated here:

  • I keep a file called local_settings.py that has the content USING_LOCAL = True in dev and USING_LOCAL = False in prod
  • In settings.py I do an import on that file to get the USING_LOCAL setting

I then base all my environment-dependent settings on that one:

DEBUG = USING_LOCAL
if USING_LOCAL:
    # dev database settings
else:
    # prod database settings

I prefer this to having two separate settings.py files that I need to maintain as I can keep my settings structured in a single file easier than having them spread across several files. Like this, when I update a setting I don't forget to do it for both environments.

Of course that every method has its disadvantages and this one is no exception. The problem here is that I can't overwrite the local_settings.py file whenever I push my changes into production, meaning I can't just copy all files blindly, but that's something I can live with.

I need to convert an int variable to double

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.

Two values from one input in python?

In Python 3, raw_input() was renamed to input().

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So you can do this way

x, y = input('Enter two numbers separating by a space: ').split();
print(int(x) + int(y))

If you do not put two numbers using a space you would get a ValueError exception. So that is good to go.

N.B. If you need old behavior of input(), use eval(input())

change cursor from block or rectangle to line?

If you happen to be using a mac keyboard on linux (ubuntu), Insert is actually fn + return. You can also click on the zero of the number pad to switch between the cursor types.

Took me a while to figure that out. :-P

How to hide status bar in Android

Use this code:

requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.youractivityxmlname);

Add click event on div tag using javascript

Just add the onclick-attribute:

<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>

It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.

While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.

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

(city + ', ' + state + ' ' + zip) as ctstzip for select
(city + ', ' + state + ' ' + zip) for insert

Only cast or convert if any field type is different from others.

On insert the value needs to be in the correct spot you need it be inserted. Using "as" will give you an error.

i.e.

Insert into testtable (ctstzip) Values ((city + ', ' + state + ' ' + zip))

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

How to set the current working directory?

people using pandas package

import os
import pandas as pd

tar = os.chdir('<dir path only>') # do not mention file name here
print os.getcwd()# to print the path name in CLI

the following syntax to be used to import the file in python CLI

dataset(*just a variable) = pd.read_csv('new.csv')

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

UIAlertController custom font, size, color

Not sure if this is against private APIs/properties but using KVC works for me on ios8

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Dont care what goes here, since we're about to change below" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:50.0]
              range:NSMakeRange(24, 11)];
[alertVC setValue:hogan forKey:@"attributedTitle"];



UIAlertAction *button = [UIAlertAction actionWithTitle:@"Label text" 
                                        style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction *action){
                                                    //add code to make something happen once tapped
}];
UIImage *accessoryImage = [UIImage imageNamed:@"someImage"];
[button setValue:accessoryImage forKey:@"image"];

For the record, it is possible to change alert action's font as well, using those private APIs. Again, it may get you app rejected, I have not yet tried to submit such code.

let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

let action = UIAlertAction(title: "Some title", style: .Default, handler: nil)
let attributedText = NSMutableAttributedString(string: "Some title")

let range = NSRange(location: 0, length: attributedText.length)
attributedText.addAttribute(NSKernAttributeName, value: 1.5, range: range)
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "ProximaNova-Semibold", size: 20.0)!, range: range)

alert.addAction(action)

presentViewController(alert, animated: true, completion: nil)

// this has to be set after presenting the alert, otherwise the internal property __representer is nil
guard let label = action.valueForKey("__representer")?.valueForKey("label") as? UILabel else { return }
label.attributedText = attributedText

For Swift 4.2 in XCode 10 and up the last 2 lines are now:

guard let label = (action!.value(forKey: "__representer")as? NSObject)?.value(forKey: "label") as? UILabel else { return }
        label.attributedText = attributedText

ListBox with ItemTemplate (and ScrollBar!)

I have never had any luck with any scrollable content placed inside a stackpanel (anything derived from ScrollableContainer. The stackpanel has an odd layout mechanism that confuses child controls when the measure operation is completed and I found the vertical size ends up infinite, therefore not constrained - so it goes beyond the boundaries of the container and ends up clipped. The scrollbar doesn't show because the control thinks it has all the space in the world when it doesn't.

You should always place scrollable content inside a container that can resolve to a known height during its layout operation at runtime so that the scrollbars size appropriately. The parent container up in the visual tree must be able to resolve to an actual height, and this happens in the grid if you set the height of the RowDefinition o to auto or fixed.

This also happens in Silverlight.

-em-

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

Change Bootstrap input focus blue glow

In Bootstrap 4, if you compile SASS by yourself, you can change the following variables to control the styling of the focus shadow:

$input-btn-focus-width:       .2rem !default;
$input-btn-focus-color:       rgba($component-active-bg, .25) !default;
$input-btn-focus-box-shadow:  0 0 0 $input-btn-focus-width $input-btn-focus-color !default;

Note: as of Bootstrap 4.1, the $input-btn-focus-color and $input-btn-focus-box-shadow variables are used only for input elements, but not for buttons. The focus shadow for buttons is hardcoded as box-shadow: 0 0 0 $btn-focus-width rgba($border, .5);, so you can only control the shadow width via the $input-btn-focus-width variable.

Decompile .smali files on an APK

No, APK Manager decompiles the .dex file into .smali and binary .xml to human readable xml.

The sequence (based on APK Manager 4.9) is 22 to select the package, and then 9 to decompile it. If you press 1 instead of 9, then you will just unpack it (useful only if you want to exchange .png images).

There is no tool available to decompile back to .java files and most probably it won't be any. There is an alternative, which is using dex2jar to transform the dex file in to a .class file, and then use a jar decompiler (such as the free jd-gui) to plain text java. The process is far from optimal, though, and it won't generate working code, but it's decent enough to be able to read it.

dex2jar: https://github.com/pxb1988/dex2jar

jd-gui: http://jd.benow.ca/

Edit: I knew there was somewhere here in SO a question with very similar answers... decompiling DEX into Java sourcecode

How can I detect the touch event of an UIImageView?

Instead of making a touchable UIImageView then placing it on the navbar, you should just create a UIBarButtonItem, which you make out of a UIImageView.

First make the image view:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nameOfYourImage.png"]];

Then make the barbutton item out of your image view:

UIBarButtonItem *yourBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:yourImageView];

Then add the bar button item to your navigation bar:

self.navigationItem.rightBarButtonItem = yourBarButtonItem;

Remember that this code goes into the view controller which is inside a navigation controller viewcontroller array. So basically, this "touchable image-looking bar button item" will only appear in the navigation bar when this view controller when it's being shown. When you push another view controller, this navigation bar button item will disappear.

HTML5 placeholder css padding

Setting line-height: 0px; fixed it for me in Chrome

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.

In this case, moving the inner class to its own .java file fixed the problem.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Start Eclipse with the option -Dosgi.locking=none.

I got the trick here and it works.

Don't do this unless you know nobody can work on the same file at the same time.

Text overflow ellipsis on two lines

For those working in scss, you need to add !autoprefixer to the start of the comment so that it is preserved for postcss:

I faced that issue that's why posting it here

line-height: 1em;
max-height: 2em;
display: -webkit-box;
/*! autoprefixer: off */
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

Reference

Hashing with SHA1 Algorithm in C#

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

PermissionError: [Errno 13] Permission denied

The problem could be in the path of the file you want to open. Try and print the path and see if it is fine I had a similar problem

def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
    filenm=filenm.split("?")[0]
    filenm=("{}.html").format(filenm)
    print("Converted a  file into html that was not compatible")

if ".aspx" in htm:
    htm=htm.replace(".aspx",".aspx.html")
    print("[process]...conversion fron aspx")
if ".jsp" in htm:
    htm=htm.replace(".jsp",".jsp.html")
    print("[process]..conversion from jsp")
if ".php" in htm:
    htm=htm.replace(".php",".php.html")
    print("[process]..conversion from php")

output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))

but after adding this code:

nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
    filenm=("{}index.html").format(filenm)

How to load external webpage in WebView

Thanks to this post, I finally found the solution. Here is the code:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;

public class Main extends Activity {

    private WebView mWebview ;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mWebview  = new WebView(this);

        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

        mWebview .loadUrl("http://www.google.com");
        setContentView(mWebview );

    }

}

How to destroy a JavaScript object?

You could put all of your code under one namespace like this:

var namespace = {};

namespace.someClassObj = {};

delete namespace.someClassObj;

Using the delete keyword will delete the reference to the property, but on the low level the JavaScript garbage collector (GC) will get more information about which objects to be reclaimed.

You could also use Chrome Developer Tools to get a memory profile of your app, and which objects in your app are needing to be scaled down.

Can't get Python to import from a different folder

You're missing __init__.py. From the Python tutorial:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Put an empty file named __init__.py in your Models directory, and all should be golden.

Find all storage devices attached to a Linux machine

You can always do fdisk -l which seems to work pretty well, even on strange setups such as EC2 xvda devices.

Here is a dump for a m1.large instance:

root@ip-10-126-247-82:~# fdisk -l

Disk /dev/xvda1: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda1 doesn't contain a valid partition table

Disk /dev/xvda2: 365.0 GB, 365041287168 bytes
255 heads, 63 sectors/track, 44380 cylinders, total 712971264 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda2 doesn't contain a valid partition table

Disk /dev/xvda3: 939 MB, 939524096 bytes
255 heads, 63 sectors/track, 114 cylinders, total 1835008 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda3 doesn't contain a valid partition table

While mount says:

root@ip-10-126-247-82:~# mount
/dev/xvda1 on / type ext4 (rw)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
fusectl on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
/dev/xvda2 on /mnt type ext3 (rw)

And /proc/partitions says:

root@ip-10-126-247-82:~# cat /proc/partitions
major minor  #blocks  name

 202        1   10485760 xvda1
 202        2  356485632 xvda2
 202        3     917504 xvda3

Side Note

How fdisk -l works is something I would love to know myself.

How to search and replace text in a file?

def findReplace(find, replace):

    import os 

    src = os.path.join(os.getcwd(), os.pardir) 

    for path, dirs, files in os.walk(os.path.abspath(src)):

        for name in files: 

            if name.endswith('.py'): 

                filepath = os.path.join(path, name)

                with open(filepath) as f: 

                    s = f.read()

                s = s.replace(find, replace) 

                with open(filepath, "w") as f:

                    f.write(s) 

How to add extra whitespace in PHP?

PHP (typically) generates HTML output for a web-site.

When displaying HTML, the browser (typically) collapses all whitespace in text into a single space. Sometimes, between tags, it even collapses whitespace to nothing.

In order to persuade the browser to display whitespace, you need to include special tags like &nbsp; or <br/> in your HTML to add non-breaking whitespace or new lines, respectively.

Restore a postgres backup file using the command line?

POSTGRESQL 9.1.12

DUMP:

pg_dump -U user db_name > archive_name.sql

put the user password and press enter.

RESTORE:

psql -U user db_name < /directory/archive.sql

put the user password and press enter.

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

jQuery: get the file name selected from <input type="file" />

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="viewImage"/>
<script>
 function readURL(fileName) {
    if (fileName.files && fileName.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#viewImage')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(fileName.files[0]);
    }
}
</script>

How to change the colors of a PNG image easily?

If you are going to be programming an application to do all of this, the process will be something like this:

  1. Convert image from RGB to HSV
  2. adjust H value
  3. Convert image back to RGB
  4. Save image

How to asynchronously call a method in Java

It's probably not a real solution, but now - in Java 8 - You can make this code look at least a little better using lambda expression.

final String x = "somethingelse";
new Thread(() -> {
        x.matches("something");             
    }
).start();

And You could even do this in one line, still having it pretty readable.

new Thread(() -> x.matches("something")).start();

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Invoke-customs are only supported starting with android 0 --min-api 26

If you have Java 7 so include the below following snippet within your app-level build.gradle :

compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

}

What is TypeScript and why would I use it in place of JavaScript?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth

1000ft view...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

Are there other technologies like it?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

Example

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Debugging TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

Want to know more?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.

What languages are Windows, Mac OS X and Linux written in?

Linux: C. Some parts in assembly.

[...] It's mostly in C, but most people wouldn't call what I write C. It uses every conceivable feature of the 386 I could find, as it was also a project to teach me about the 386. As already mentioned, it uses a MMU, for both paging (not to disk yet) and segmentation. It's the segmentation that makes it REALLY 386 dependent (every task has a 64Mb segment for code & data - max 64 tasks in 4Gb. Anybody who needs more than 64Mb/task - tough cookies). [...] Some of my "C"-files (specifically mm.c) are almost as much assembler as C. [...] Unlike minix, I also happen to LIKE interrupts, so interrupts are handled without trying to hide the reason behind them. (Source)

Mac OS X: Cocoa mostly in Objective-C. Kernel written in C, some parts in assembly.

Mac OS X, at the kernel layer, is mostly an older, free operating system called BSD (specifically, it’s Darwin, a sort of hybrid of BSD, Mach, and a few other things)... almost entirely C, with a bit of assembler thrown in. (Source)

Much of Cocoa is implemented in Objective-C, an object-oriented language that is compiled to run at incredible speed, yet employes a truly dynamic runtime making it uniquely flexible. Because Objective-C is a superset of C, it is easy to mix C and even C++ into your Cocoa applications. (Source)

Windows: C, C++, C#. Some parts in assembler.

We use almost entirely C, C++, and C# for Windows. Some areas of code are hand tuned/hand written assembly. (Source)

Unix: C. Some parts in assembly. (Source)

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

Standard deviation of a list

The other answers cover how to do std dev in python sufficiently, but no one explains how to do the bizarre traversal you've described.

I'm going to assume A-Z is the entire population. If not see Ome's answer on how to inference from a sample.

So to get the standard deviation/mean of the first digit of every list you would need something like this:

#standard deviation
numpy.std([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

#mean
numpy.mean([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

To shorten the code and generalize this to any nth digit use the following function I generated for you:

def getAllNthRanks(n):
    return [A_rank[n], B_rank[n], C_rank[n], D_rank[n], E_rank[n], F_rank[n], G_rank[n], H_rank[n], I_rank[n], J_rank[n], K_rank[n], L_rank[n], M_rank[n], N_rank[n], O_rank[n], P_rank[n], Q_rank[n], R_rank[n], S_rank[n], T_rank[n], U_rank[n], V_rank[n], W_rank[n], X_rank[n], Y_rank[n], Z_rank[n]] 

Now you can simply get the stdd and mean of all the nth places from A-Z like this:

#standard deviation
numpy.std(getAllNthRanks(n))

#mean
numpy.mean(getAllNthRanks(n))

Chaining multiple filter() in Django, is this a bug?

Saw this in a comment and I thought it was the simplest explanation.

filter(A, B) is the AND filter(A).filter(B) is OR

How to run composer from anywhere?

First install the composer like mentioned in the composer installation documentation. I just added here for reference.

curl -sS https://getcomposer.org/installer | php

and then move the file to '/usr/local/bin'.

sudo mv composer.phar /usr/local/bin/composer

Try to run composer -V. If you get a output like Composer version followed by the version number then the composer is installed successfully.

If you get any output like composer: command not found means use the following command to create a alias for the composer. So it will be executed globally.

alias composer='/usr/local/bin/composer'

Now if you run composer -V means you will get the output as Composer Version followed by the version number.

Hope this will help someone.

Parse String to Date with Different Format in Java

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

Please make sure the output folder in Java Build Path tab set as like below,which would determine where the .class file are generated.Then clean the project.

enter image description here

how to save and read array of array in NSUserdefaults in swift?

The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults. For those people I will add a few common examples.

String array

Save array

let array = ["horse", "cow", "camel", "sheep", "goat"]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")

Retrieve array

let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()

Int array

Save array

let array = [15, 33, 36, 723, 77, 4]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray")  as? [Int] ?? [Int]()

Bool array

Save array

let array = [true, true, false, true, false]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray")  as? [Bool] ?? [Bool]()

Date array

Save array

let array = [Date(), Date(), Date(), Date()]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray")  as? [Date] ?? [Date]()

Object array

Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults. See the following links for how to do it.

Notes

  • The nil coalescing operator (??) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ?? operator will be used instead.
  • As you can see, the basic setup was the same for Int, Bool, and Date. I also tested it with Double. As far as I know, anything that you can save in a property list will work like this.

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

to use unverified ssl you can add this to your code:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

How to generate UL Li list from string array using jquery?

With ES6 you can write this:

const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];

const $ul = $('<ul>', { class: "mylist" }).append(
  countries.map(country => 
    $("<li>").append($("<a>").text(country))
  )
);

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

Importing CSV File to Google Maps

We have now (jan2017) a csv layer import inside Google Maps itself.enter image description here

Google Maps > "Your Places" > "Open in My Maps"

setup.py examples?

Complete walkthrough of writing setup.py scripts here. (with some examples)

If you'd like a real-world example, I could point you towards the setup.py scripts of a couple major projects. Django's is here, pyglet's is here. You can just browse the source of other projects for a file named setup.py for more examples.

These aren't simple examples; the tutorial link I gave has those. These are more complex, but also more practical.

Setting default values for columns in JPA

Actually it is possible in JPA, although a little bit of a hack using the columnDefinition property of the @Column annotation, for example:

@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

Try this -->

 new DzieckoAndOpiekun(
                         p.Imie,
                         p.Nazwisko,
                         p.Opiekun.Imie,
                         p.Opiekun.Nazwisko).ToList()

Junit - run set up method once

Although I agree with @assylias that using @BeforeClass is a classic solution it is not always convenient. The method annotated with @BeforeClass must be static. It is very inconvenient for some tests that need instance of test case. For example Spring based tests that use @Autowired to work with services defined in spring context.

In this case I personally use regular setUp() method annotated with @Before annotation and manage my custom static(!) boolean flag:

private static boolean setUpIsDone = false;
.....
@Before
public void setUp() {
    if (setUpIsDone) {
        return;
    }
    // do the setup
    setUpIsDone = true;
}

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

How do I install a pip package globally instead of locally?

Why don't you try sudo with the H flag? This should do the trick.

sudo -H pip install flake8

A regular sudo pip install flake8 will try to use your own home directory. The -H instructs it to use the system's home directory. More info at https://stackoverflow.com/a/43623102/

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

It's a bit worse, I use a calling card for international calls, so its local number in the US + account# (6 digits) + pin (4 digits) + "pause" + what you described above.

I suspect there might be other cases

program cant start because php5.dll is missing

For Wamp x86+Phalcon users (with same error):

Take care of download the right version of Phalcon:

Phalcon 1.3.2 - Windows x86 for PHP 5.5.0 (VC11)

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

Show space, tab, CRLF characters in editor of Visual Studio

The correct shortcut is CTRL-R-W like you don't have to release CTRL button while pressing W. This worked for me in VS 2015

How can I initialize base class member variables in derived class constructor?

If you don't specify visibility for a class member, it defaults to "private". You should make your members private or protected if you want to access them in a subclass.

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
    param(
        [Parameter(Mandatory=$true)][string]$computername,
        [Parameter(Mandatory=$false)][string]$arg2,
        [Parameter(Mandatory=$false)][string]$domain
    )
    if(!($domain)){
        $domain = 'domain1'
    }
    write-host $domain
    if($arg2){
        write-host "arg2 present... executing script block"
    }
    else{
        write-host "arg2 missing... exiting or whatever"
    }
}

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

In my case, I fixed this error by change export default class yourComponent extends React.Component() {} to export default class yourComponent extends React.Component {}. Yes delete the parenthesis () fixed the error.

How to directly move camera to current location in Google Maps Android API v2?

I am explaining, How to get current location and Directly move to the camera to current location with assuming that you have implemented map-v2. For more details, You can refer official doc.

Add location service in gradle

implementation "com.google.android.gms:play-services-location:11.0.1"

Add location permission in manifest file

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

Make sure you ask for RunTimePermission. I am using Ask-Permission for that. Its easy to use.

Now refer below code to get the current location and display it on a map.

private FusedLocationProviderClient mFusedLocationProviderClient;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFusedLocationProviderClient = LocationServices
                .getFusedLocationProviderClient(getActivity());

}

private void getDeviceLocation() {
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            Location location = task.getResult();
                            LatLng currentLatLng = new LatLng(location.getLatitude(),
                                    location.getLongitude());
                            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
                                    DEFAULT_ZOOM);
                            googleMap.moveCamera(update);
                        }
                    }
                });
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
}

When user granted location permission call above getDeviceLocation() method

private void updateLocationUI() {
        if (googleMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                googleMap.setMyLocationEnabled(true);
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                getDeviceLocation();
            } else {
                googleMap.setMyLocationEnabled(false);
                googleMap.getUiSettings().setMyLocationButtonEnabled(false);
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
    }

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

This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.' and the slash '/'.

Instead of writing:

D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"

Write:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

enabling cross-origin resource sharing on IIS7

Alsalaam Aleykum.

The first way is to follow the instructions in this link:

http://help.infragistics.com/Help/NetAdvantage/jQuery/2013.1/CLR4.0/html/igOlapXmlaDataSource_Configuring_IIS_for_Cross_Domain_OLAP_Data.html

Which corresponds to these configuration:

_x000D_
_x000D_
<handlers>_x000D_
  <clear />_x000D_
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-ISAPI-4.0_64bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-ISAPI-4.0_32bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-Integrated-4.0" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="System.Xaml.Hosting.XamlHttpHandlerFactory, System.Xaml.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler" scriptProcessor=""_x000D_
  resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="rules-ISAPI-4.0_64bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="rules-ISAPI-4.0_32bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="rules-Integrated-4.0" path="*.rules" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="xoml-ISAPI-4.0_64bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="xoml-ISAPI-4.0_32bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="xoml-Integrated-4.0" path="*.xoml" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="svc-ISAPI-4.0_32bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="svc-Integrated-4.0" path="*.svc" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler" scriptProcessor=""_x000D_
  resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="ISAPI-dll" path="*.dll" verb="*" type="" modules="IsapiModule" scriptProcessor="" resourceType="File" requireAccess="Execute" allowPathInfo="true" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="AXD-ISAPI-4.0_64bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="PageHandlerFactory-ISAPI-4.0_64bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="SimpleHandlerFactory-ISAPI-4.0_64bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="WebServiceHandlerFactory-ISAPI-4.0_64bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_64bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_64bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="aspq-ISAPI-4.0_64bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="0" />_x000D_
  <add name="cshtm-ISAPI-4.0_64bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="cshtml-ISAPI-4.0_64bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="vbhtm-ISAPI-4.0_64bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="vbhtml-ISAPI-4.0_64bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="TraceHandler-Integrated-4.0" path="trace.axd" verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TraceHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="WebAdminHandler-Integrated-4.0" path="WebAdmin.axd" verb="GET,DEBUG" type="System.Web.Handlers.WebAdminHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="AssemblyResourceLoader-Integrated-4.0" path="WebResource.axd" verb="GET,DEBUG" type="System.Web.Handlers.AssemblyResourceLoader" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="PageHandlerFactory-Integrated-4.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.SimpleHandlerFactory" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="WebServiceHandlerFactory-Integrated-4.0" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-Integrated-4.0" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"_x000D_
  modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-Integrated-4.0" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"_x000D_
  modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="aspq-Integrated-4.0" path="*.aspq" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="cshtm-Integrated-4.0" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="cshtml-Integrated-4.0" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="vbhtm-Integrated-4.0" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="vbhtml-Integrated-4.0" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="ScriptHandlerFactoryAppServices-Integrated-4.0" path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="ScriptResourceIntegrated-4.0" path="*ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="AXD-ISAPI-4.0_32bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="PageHandlerFactory-ISAPI-4.0_32bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="SimpleHandlerFactory-ISAPI-4.0_32bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="WebServiceHandlerFactory-ISAPI-4.0_32bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_32bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_32bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="aspq-ISAPI-4.0_32bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="0" />_x000D_
  <add name="cshtm-ISAPI-4.0_32bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="cshtml-ISAPI-4.0_32bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="vbhtm-ISAPI-4.0_32bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="vbhtml-ISAPI-4.0_32bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="TRACEVerbHandler" path="*" verb="TRACE" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />_x000D_
  <add name="StaticFile" path="*" verb="*" type="" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" scriptProcessor="" resourceType="Either" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304"_x000D_
  />_x000D_
</handlers>
_x000D_
_x000D_
_x000D_

The second way is as to respond to the HTTP OPTIONS verb in your BeginRequest method.

  protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Request-Method", "GET ,POST, PUT, DELETE");

        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin,Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "86400"); // 24 hours
        HttpContext.Current.Response.End();
    }
}

Table column sizing

Using d-flex class works well but some other attributes don't work anymore like vertical-align: middle property.

The best way I found to size columns very easily is to use the width attribute with percentage only in thead cells.

<table class="table">
    <thead>
        <tr>
            <th width="25%">25%</th>
            <th width="25%">25%</th>
            <th width="50%">50%</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>25%</td>
            <td>25%</td>
            <td>50%</td>
        </tr>
    </tbody>
</table>

Add a UIView above all, even the navigation bar

[[UIApplication sharedApplication].windows.lastObject addSubview:myView];

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Linq on DataTable: select specific column into datatable, not whole table

Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on IEnumerable<T> where T is or derives from DataRow. You can select r the row object to call CopyToDataTable on it.

var query = from r in matrix.AsEnumerable()
                where r.Field<string>("c_to") == c_to &&
                      r.Field<string>("p_to") == p_to
                 select r;

DataTable conversions = query.CopyToDataTable();

You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.

How to delete columns that contain ONLY NAs?

Because performance was really important for me, I benchmarked all the functions above.

NOTE: Data from @Simon O'Hanlon's post. Only with size 15000 instead of 10.

library(tidyverse)
library(microbenchmark)

set.seed(123)
df <- data.frame(id = 1:15000,
                 nas = rep(NA, 15000), 
                 vals = sample(c(1:3, NA), 15000,
                               repl = TRUE))
df

MadSconeF1 <- function(x) x[, colSums(is.na(x)) != nrow(x)]

MadSconeF2 <- function(x) x[colSums(!is.na(x)) > 0]

BradCannell <- function(x) x %>% select_if(~sum(!is.na(.)) > 0)

SimonOHanlon <- function(x) x[ , !apply(x, 2 ,function(y) all(is.na(y)))]

jsta <- function(x) janitor::remove_empty(x)

SiboJiang <- function(x) x %>% dplyr::select_if(~!all(is.na(.)))

akrun <- function(x) Filter(function(y) !all(is.na(y)), x)

mbm <- microbenchmark(
  "MadSconeF1" = {MadSconeF1(df)},
  "MadSconeF2" = {MadSconeF2(df)},
  "BradCannell" = {BradCannell(df)},
  "SimonOHanlon" = {SimonOHanlon(df)},
  "SiboJiang" = {SiboJiang(df)},
  "jsta" = {jsta(df)}, 
  "akrun" = {akrun(df)},
  times = 1000)

mbm

Results:

Unit: microseconds
         expr    min      lq      mean  median      uq      max neval  cld
   MadSconeF1  154.5  178.35  257.9396  196.05  219.25   5001.0  1000 a   
   MadSconeF2  180.4  209.75  281.2541  226.40  251.05   6322.1  1000 a   
  BradCannell 2579.4 2884.90 3330.3700 3059.45 3379.30  33667.3  1000    d
 SimonOHanlon  511.0  565.00  943.3089  586.45  623.65 210338.4  1000  b  
    SiboJiang 2558.1 2853.05 3377.6702 3010.30 3310.00  89718.0  1000    d
         jsta 1544.8 1652.45 2031.5065 1706.05 1872.65  11594.9  1000   c 
        akrun   93.8  111.60  139.9482  121.90  135.45   3851.2  1000 a


autoplot(mbm)

enter image description here

mbm %>% 
  tbl_df() %>%
  ggplot(aes(sample = time)) + 
  stat_qq() + 
  stat_qq_line() +
  facet_wrap(~expr, scales = "free")

enter image description here

Why I got " cannot be resolved to a type" error?

In my case the missing type was referencing an import for java class in a dependent jar. For some reason my project file was missing the javabuilder and therefore couldnt resolve the path to the import.

Why it was missing in the first place I don't know, but adding these lines in fixed the error.

<buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
</buildCommand>

How can I get my Twitter Bootstrap buttons to right align?

<ul>
    <li class="span4">One <input class="btn btn-small" value="test"></li>
    <li class="span4">Two <input class="btn btn-small" value="test2"></li>
</ul>

One way would be to apply this style to your list items in order to keep them inline

or

<ul>
    <li>One <input class="btn" value="test"></li>
    <li>Two <input class="btn" value="test2"></li>
</ul>

in CSS

li {
    line-height: 20px;
    margin: 5px;
    padding: 2px;
}

Case insensitive comparison of strings in shell script

grep has a -i flag which means case insensitive so ask it to tell you if var2 is in var1.

var1=match 
var2=MATCH 
if echo $var1 | grep -i "^${var2}$" > /dev/null ; then
    echo "MATCH"
fi

How to check if an array element exists?

You can use the function array_key_exists to do that.

For example,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.

How can I color dots in a xy scatterplot according to column value?

Try this:

Dim xrndom As Random
    Dim x As Integer
    xrndom = New Random

    Dim yrndom As Random
    Dim y As Integer
    yrndom = New Random
    'chart creation
    Chart1.Series.Add("a")
    Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("a").MarkerSize = 10
    Chart1.Series.Add("b")
    Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("b").MarkerSize = 10
    Chart1.Series.Add("c")
    Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("c").MarkerSize = 10
    Chart1.Series.Add("d")
    Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("d").MarkerSize = 10
    'color
    Chart1.Series("a").Color = Color.Red
    Chart1.Series("b").Color = Color.Orange
    Chart1.Series("c").Color = Color.Black
    Chart1.Series("d").Color = Color.Green
    Chart1.Series("Chart 1").Color = Color.Blue

    For j = 0 To 70
        x = xrndom.Next(0, 70)
        y = xrndom.Next(0, 70)
        'Conditions
        If j < 10 Then
            Chart1.Series("a").Points.AddXY(x, y)
        ElseIf j < 30 Then
            Chart1.Series("b").Points.AddXY(x, y)
        ElseIf j < 50 Then
            Chart1.Series("c").Points.AddXY(x, y)
        ElseIf 50 < j Then
            Chart1.Series("d").Points.AddXY(x, y)
        Else
            Chart1.Series("Chart 1").Points.AddXY(x, y)
        End If
    Next

Performing a Stress Test on Web Application?

Trying all mentioned here, I found curl-loader as best for my purposes. very easy interface, real-time monitoring, useful statistics, from which I build graphs of performance. All features of libcurl are included.

Converting between strings and ArrayBuffers

Yes:

const encstr = (`TextEncoder` in window) ? new TextEncoder().encode(str) : Uint8Array.from(str, c => c.codePointAt(0));

Connect to network drive with user name and password

You can use the WindowsIdentity class (with a logon token) to impersonate while reading and writing files.

var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
    // Connect, read, write
}

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

Convert int to ASCII and back in Python

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L

The I/O operation has been aborted because of either a thread exit or an application request

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

Save plot to image file instead of displaying it using Matplotlib

As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don't have a million open figures during the loop:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).

C# 'or' operator?

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

How to unpackage and repackage a WAR file

no need to that, tomcat naturally extract the war file into a folder of the same name. you simply modify the desired file inside that folder (including .xml configuration files), that's all. technically no need to restart tomcat after applying the modifications

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

jQuery remove options from select

It works on either option tag or text field:

$("#idname option[value='option1']").remove();

Python script to copy text to clipboard

See Pyperclip. Example (taken from Pyperclip site):

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()

Also, see Xerox. But it appears to have more dependencies.

Port 80 is being used by SYSTEM (PID 4), what is that?

This Process works for me:

  1. Right click on My Computer.
  2. Select Manage.
  3. Double click Services and Applications.
  4. Then double-click Services.
  5. Right click on "World Wide Web Publishing Service".
  6. Select Stop
  7. Restart XAMPP

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Making authenticated POST requests with Spring RestTemplate for Android

I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.

What worked for me was encoding credentials in Base64 and adding them as Basic Authorization headers. I then added them as an HttpEntity to restTemplate.postForEntity, which gave me the response I needed.

Here's the class I wrote for this in full (extending RestTemplate):

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

    public AuthorizedRestTemplate(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getForObject(String url, Object... urlVariables){
        return authorizedRestCall(this, url, urlVariables);
    }

    private String authorizedRestCall(RestTemplate restTemplate, 
            String url, Object... urlVariables){
        HttpEntity<String> request = getRequest();
        ResponseEntity<String> entity = restTemplate.postForEntity(url, 
                request, String.class, urlVariables);
        return entity.getBody();
    }

    private HttpEntity<String> getRequest(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + getBase64Credentials());
        return new HttpEntity<String>(headers);
    }

    private String getBase64Credentials(){
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}

How to get file creation & modification date/times in Python?

I was able to get creation time on posix by running the system's stat command and parsing the output.

commands.getoutput('stat FILENAME').split('\"')[7]

Running stat outside of python from Terminal (OS X) returned:

805306374 3382786932 -rwx------ 1 km staff 0 1098083 "Aug 29 12:02:05 2013" "Aug 29 12:02:05 2013" "Aug 29 12:02:20 2013" "Aug 27 12:35:28 2013" 61440 2150 0 testfile.txt

... where the fourth datetime is the file creation (rather than ctime change time as other comments noted).

How to disable text selection using jQuery?

One solution to this, for appropriate cases, is to use a <button> for the text that you don't want to be selectable. If you are binding to the click event on some text block, and don't want that text to be selectable, changing it to be a button will improve the semantics and also prevent the text being selected.

<button>Text Here</button>

Removing cordova plugins from the project

v2.0.0 of cordova-check-plugins enables you to remove all plugins in a project:

$ npm install -g cordova-check-plugins
$ cordova-check-plugins --remove-all

It will attempt to use the Cordova CLI to remove each plugin, but if this fails it will force removal of the plugin from platforms/ and plugins/.

If you also want to remove from config.xml, use:

$ cordova-check-plugins --remove-all --save

Disclaimer: I am the author of cordova-check-plugins

How does Junit @Rule work?

Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.

For example, Using @Timeout rule we can set the timeout for all the tests.

public class TestApp {
    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

    ......
    ......

 }

@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.

public class TempFolderTest {

 @Rule
 public TemporaryFolder tempFolder= new TemporaryFolder();

 @Test
 public void testTempFolder() throws IOException {
  File folder = tempFolder.newFolder("demos");
  File file = tempFolder.newFile("Hello.txt");

  assertEquals(folder.getName(), "demos");
  assertEquals(file.getName(), "Hello.txt");

 }


}

You can see examples of some in-built rules provided by junit at this link.

ReactJS - Get Height of an element

See this fiddle (actually updated your's)

You need to hook into componentDidMount which is run after render method. There, you get actual height of element.

var DivSize = React.createClass({
    getInitialState() {
    return { state: 0 };
  },

  componentDidMount() {
    const height = document.getElementById('container').clientHeight;
    this.setState({ height });
  },

  render: function() {
    return (
        <div className="test">
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    );
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
    <!-- This element's contents will be replaced with your component. -->
</div>

Rails 3.1 and Image Assets

The asset pipeline in rails offers a method for this exact thing.

You simply add image_path('image filename') to your css or scss file and rails takes care of everything. For example:

.logo{ background:url(image_path('admin/logo.png'));

(note that it works just like in a .erb view, and you don't use "/assets" or "/assets/images" in the path)

Rails also offers other helper methods, and there's another answer here: How do I use reference images in Sass when using Rails 3.1?

Get the Application Context In Fragment In Android?

Use

getActivity().getApplicationContext()

to obtain the context in any fragment

Find substring in the string in TWIG

Just searched for the docs, and found this:

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

{# returns true #}

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

{{ 'cd' in 'abcde' }}

Fastest way to convert JavaScript NodeList to Array?

Assuming nodeList = document.querySelectorAll("div"), this is a concise form of converting nodelist to array.

var nodeArray = [].slice.call(nodeList);

See me use it here.

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

How do I use two submit buttons, and differentiate between which one was used to submit the form?

You can use it as follows,

<td>

<input type="submit" name="save" class="noborder" id="save" value="Save" alt="Save" 
tabindex="4" />

</td>

<td>

<input type="submit" name="publish" class="noborder" id="publish" value="Publish" 
alt="Publish" tabindex="5" />

</td>

And in PHP,

<?php
if($_POST['save'])
{
   //Save Code
}
else if($_POST['publish'])
{
   //Publish Code
}
?>

How do I completely rename an Xcode project (i.e. inclusive of folders)?

A quicker solution using shell commands (works with CocoaPods too):

PLEASE cd TO A NON-GIT REPOSITORY BEFORE PROCEEDING ??

Step 1 - Prerequisites

  1. Copy your original project folder to a temporary /NewProjectFolder OUTSIDE your git repository. ?? changes to .git could corrupt your git index ?

Step 2 - Open Terminal

Now we're going to rename the project from oldName to NewProject.

  • Close XCode.
  • Go to your /NewProjectFolder.
cd /Path/to/your/NewProjectFolder
  • Install the extra tools needed.
brew install rename ack
  • Rename the files and directories containing the source string. You’ll need to RUN THIS COMMAND TWICE, because directories will be renamed first, then files and directories inside those will be renamed on the next iteration.
find . -name 'oldName*' -print0 | xargs -0 rename --subst-all 'oldName' 'NewProject'
  • Check if all the files containing the source string are renamed. You should see empty output.
find . -name 'oldName*'
  • Replace all occurrences of the string in all files.
ack --literal --files-with-matches 'oldName' --print0 | xargs -0 sed -i '' 's/oldName/NewProject/g'
  • Check if all occurrences of the string in all files were replaced. You should see empty output.
ack --literal 'oldName'
  • Run pod install
  • Add NewProjectFolder to your repository.
  • You are done!

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

BigDecimal to string

To get exactly 10.0001 you need to use the String constructor or valueOf (which constructs a BigDecimal based on the canonical representation of the double):

BigDecimal bd = new BigDecimal("10.0001");
System.out.println(bd.toString()); // prints 10.0001
//or alternatively
BigDecimal bd = BigDecimal.valueOf(10.0001);
System.out.println(bd.toString()); // prints 10.0001

The problem with new BigDecimal(10.0001) is that the argument is a double and it happens that doubles can't represent 10.0001 exactly. So 10.0001 is "transformed" to the closest possible double, which is 10.000099999999999766941982670687139034271240234375 and that's what your BigDecimal shows.

For that reason, it rarely makes sense to use the double constructor.

You can read more about it here, Moving decimal places over in a double

Number input type that takes only integers?

The integer input would mean that it can only take positive numbers, 0 and negative numbers too. This is how I have been able to achieve this using Javascript keypress.

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){
  
    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
      return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.

Level 1 annotations: @Entity, @Id, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.

Level 2 annotations: @Table, @Column, @JoinColumn, ... Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.

In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.

To answer the questions: the @OneToMany/mappedBy is nicest because it only uses the annotations from the entity domain. The @oneToMany/@JoinColumn is also fine but it uses an implementation annotation where this is not strictly necessary.

php_network_getaddresses: getaddrinfo failed: Name or service not known

You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n"); 

That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

How do I find the difference between two values without knowing which is larger?

So simple just use abs((a) - (b)).

will work seamless without any additional care in signs(positive , negative)

def get_distance(p1,p2):
     return abs((p1) - (p2))

get_distance(0,2)
2

get_distance(0,2)
2

get_distance(-2,0)
2

get_distance(2,-1)
3

get_distance(-2,-1)
1

How to mount a single file in a volume

I have same issue on my Windows 8.1

It turned out that it was due to case-sensitivity of path. I called docker-compose up from directory cd /c/users/alex/ and inside container a file was turned into directory.

But when I did cd /c/Users/alex/ (not Users capitalized) and called docker-compose up from there, it worked.

In my system both Users dir and Alex dir are capitalized, though it seems like only Users dir matter.

How do I create and store md5 passwords in mysql

just get the hash by following line and store it into the database:

$encryptedValue = md5("YOUR STRING");

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

No, the errors occurs only after the Intelephense extension is automatically updated.

To solve the problem, you can downgrade it to the previous version by click "Install another version" in the Intelephense extension. There are no errors on version 1.2.3.

Selecting empty text input using jQuery

I'd recommend:

$('input:text:not([value])')

How to set Navigation Drawer to be opened from right to left

This answer is useful to set the navigation be open from right to left, but it has no solution to set its icon to be right side. This code can fix it. If you give it the drawer as its first param and ViewCompat.LAYOUT_DIRECTION_RTL as its second param, the entier layout will be set to RTL. It is a quick and simple solution, but I don't think it can be a correct solution for who that want to only set the menu to be opened from right to left and set its icon to be on right side. (Although, it's depended to your purpose.) However, I suggest giving the toolbar instead of the drawer. In this way just the toolbar has become RTL. So I think the combination of these 2 answers can exactly do what you want.

According to these descriptions, your code should be like this:

(Add these lines to onCreate method)

final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // Set it final to fix the error that will be mention below.

    ViewCompat.setLayoutDirection(toolbar, ViewCompat.LAYOUT_DIRECTION_RTL);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawer.isDrawerOpen(Gravity.RIGHT))
                drawer.closeDrawer(Gravity.RIGHT);
            else
                drawer.openDrawer(Gravity.RIGHT);
        }
    });

Notice that you should make drawer final, otherwise you will get this error:

Variable 'drawer' is accessed from within inner class, needs to be declared final

And don't forget to use end instead of start in onNavigationItemSelected method:

drawer.closeDrawer(GravityCompat.END);

and in your activity_main.xml

<android.support.v4.widget.DrawerLayout 
   android:id="@+id/drawer_layout"
   tools:openDrawer="end">

   <android.support.design.widget.NavigationView
      android:id="@+id/nav_view"
      android:layout_gravity="end"/>
</android.support.v4.widget.DrawerLayout>

Catching access violation exceptions?

There is a very easy way to catch any kind of exception (division by zero, access violation, etc.) in Visual Studio using try -> catch (...) block. A minor project settings tweaking is enough. Just enable /EHa option in the project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!

See details here: http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.80).aspx

What does <T> (angle brackets) mean in Java?

is called a generic type. You can instantiate an object Pool like this:

PoolFactory<Integer> pool = new Pool<Integer>();

The generic parameter can only be a reference type. So you can't use primitive types like int or double or char or other primitive types.

Cast received object to a List<object> or IEnumerable<object>

Do you actually need more information than plain IEnumerable gives you? Just cast it to that and use foreach with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable (or IList to access it like a list) works very well.

Easiest way to flip a boolean value?

flipVal ^= 1;

same goes for

otherVal

INNER JOIN in UPDATE sql for DB2

The reference documentation for the UPDATE statement on DB2 LUW 9.7 gives the following example:

   UPDATE (SELECT EMPNO, SALARY, COMM,
     AVG(SALARY) OVER (PARTITION BY WORKDEPT),
     AVG(COMM) OVER (PARTITION BY WORKDEPT)
     FROM EMPLOYEE E) AS E(EMPNO, SALARY, COMM, AVGSAL, AVGCOMM)
   SET (SALARY, COMM) = (AVGSAL, AVGCOMM)
   WHERE EMPNO = '000120'

The parentheses after UPDATE can contain a full-select, meaning any valid SELECT statement can go there.

Based on that, I would suggest the following:

UPDATE (
  SELECT
    f1.firstfield,
    f2.anotherfield,
    f2.something
  FROM file1 f1
  WHERE f1.firstfield like 'BLAH%' 
  INNER JOIN file2 f2
  ON substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
AS my_files(firstfield, anotherfield, something)
SET
  firstfield = ( 'BIT OF TEXT' || something )

Edit: Ian is right. My first instinct was to try subselects instead:

UPDATE file1 f1
SET f1.firstfield = ( 'BIT OF TEXT' || (
  SELECT f2.something
  FROM file2 f2
  WHERE substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
))
WHERE f1.firstfield LIKE 'BLAH%' 
AND substr(f1.firstfield,10,20) IN (
  SELECT substr(f2.anotherfield,1,10)
  FROM file2 f2
)

But I'm not sure if the concatenation would work. It also assumes that there's a 1:1 mapping between the substrings. If there are multiple rows that match, it wouldn't work.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

protected $primaryKey = 'SongID';

After adding to my model to tell the primary key because it was taking id(SongID) by default

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

Assign an initial value to radio button as checked

If you are using react-redux for your application and if you want to show data which is in the redux store, you can set "checked" option as below.

<label>Male</label>

 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "0"}
 />



 <label>Female</label>
 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "1"}
 />

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

How to add "active" class to wp_nav_menu() current menu item (simple way)

If you want the 'active' in the html:

header with html and php:

        <?php
        $menu_items = wp_get_nav_menu_items( 'main_nav' ); // id or name of menu
        foreach ( (array) $menu_items as $key => $menu_item ) {
            if ( ! $menu_item->menu_item_parent ) {
                echo "<li class=" . vince_check_active_menu($menu_item) . "><a href='$menu_item->url'>";
                echo $menu_item->title;
                echo "</a></li>";
            }
        }
        ?>

functions.php:

function vince_check_active_menu( $menu_item ) {
    $actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if ( $actual_link == $menu_item->url ) {
        return 'active';
    }
    return '';
}

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

Browse for a directory in C#

string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
    folderPath = folderBrowserDialog1.SelectedPath ;
}

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

Paste a multi-line Java String in Eclipse

Okay, I just found the answer (on Stackoverflow, no less).

Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:

Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

SSIS Connection Manager Not Storing SQL Password

The designed behavior in SSIS is to prevent storing passwords in a package, because it's bad practice/not safe to do so.

Instead, either use Windows auth, so you don't store secrets in packages or config files, or, if that's really impossible in your environment (maybe you have no Windows domain, for example) then you have to use a workaround as described in http://support.microsoft.com/kb/918760 (Sam's correct, just read further in that article). The simplest answer is a config file to go with the package, but then you have to worry that the config file is stored securely so someone can't just read it and take the credentials.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I downloaded "Microsoft® System CLR Types for Microsoft® SQL Server® 2012" and "Microsoft® SQL Server® 2012 Shared Management Objects" from @ImanMahmoudinasab mentioned link, but Shared Management Objects had problem while installing and it showed some dependencies message and at the end installation Failed!

Finally I solved the problem with Power Shell. I run PS as administrator with the below command:

Start-Process <path>\SharedManagementObjects.msi

iPhone UIView Animation Best Practice

I have been using the latter for a lot of nice lightweight animations. You can use it crossfade two views, or fade one in in front of another, or fade it out. You can shoot a view over another like a banner, you can make a view stretch or shrink... I'm getting a lot of mileage out of beginAnimation/commitAnimations.

Don't think that all you can do is:

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES];

Here is a sample:

[UIView beginAnimations:nil context:NULL]; {
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:self];
    if (movingViewIn) {
// after the animation is over, call afterAnimationProceedWithGame
//  to start the game
        [UIView setAnimationDidStopSelector:@selector(afterAnimationProceedWithGame)];

//      [UIView setAnimationRepeatCount:5.0]; // don't forget you can repeat an animation
//      [UIView setAnimationDelay:0.50];
//      [UIView setAnimationRepeatAutoreverses:YES];

        gameView.alpha = 1.0;
        topGameView.alpha = 1.0;
        viewrect1.origin.y = selfrect.size.height - (viewrect1.size.height);
        viewrect2.origin.y = -20;

        topGameView.alpha = 1.0;
    }
    else {
    // call putBackStatusBar after animation to restore the state after this animation
        [UIView setAnimationDidStopSelector:@selector(putBackStatusBar)];
        gameView.alpha = 0.0;
        topGameView.alpha = 0.0;
    }
    [gameView setFrame:viewrect1];
    [topGameView setFrame:viewrect2];

} [UIView commitAnimations];

As you can see, you can play with alpha, frames, and even sizes of a view. Play around. You may be surprised with its capabilities.

What is an Intent in Android?

An Android application can contain zero or more activities. When your application has more than one activity, you often need to navigate from one to another. In Android, you navigate between activities through what is known as an intent. You can pass some data to the activity which you want to start through intent, by using putExtra().

What are the aspect ratios for all Android phone and tablet devices?

In case anyone wanted more of a visual reference:

aspect_ratio_visual_reference

Decimal approximations reference table:

+----------------------------------------------------------------------------+
¦       aspect ratio       ¦     decimal approx.    ¦     decimal approx.    ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦         19.5 x 9         ¦        0.462...        ¦        2.167...        ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 9          ¦        0.474...        ¦         2.11...        ¦
¦--------------------------+------------------------+------------------------¦
¦        ~18.7 x 9         ¦        0.482...        ¦        2.074...        ¦
¦--------------------------+------------------------+------------------------¦    
¦         18.5 x 9         ¦        0.486...        ¦        2.056...        ¦
¦--------------------------+------------------------+------------------------¦
¦          18 x 9          ¦           0.5          ¦            2           ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 10         ¦        0.526...        ¦           1.9          ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 9          ¦         0.5625         ¦        1.778...        ¦
¦--------------------------+------------------------+------------------------¦
¦           5 x 3          ¦           0.6          ¦        1.667...        ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 10         ¦          0.625         ¦           1.6          ¦
¦--------------------------+------------------------+------------------------¦
¦           3 x 2          ¦        0.667...        ¦           1.5          ¦
¦--------------------------+------------------------+------------------------¦
¦           4 x 3          ¦          0.75          ¦        1.333...        ¦
+----------------------------------------------------------------------------+

Changelog:

  • May 2018: Added 56x27 === ~18.7x9 (Huawei P20), 19x9 (Nokia X6 2018) and 19.5x9 (LG G7 ThinQ)
  • May 2017: Added 19x10 (Essential Phone)
  • March 2017: Added 18.5x9 (Samsung Galaxy S8) and 18x9 (LG G6)

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

Setting a property by reflection with a string value

I tried the answer from LBushkin and it worked great, but it won't work for null values and nullable fields. So I've changed it to this:

propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
     Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
     object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
     propertyInfo.SetValue(ship, safeValue, null);
}

How do I convert a Python program to a runnable .exe Windows program?

py2exe works with Python 2.7 (as well as other versions). You just need the MSVCR90.dll

http://www.py2exe.org/index.cgi/Tutorial

Replacing spaces with underscores in JavaScript?

Try .replace(/ /g,"_");

Edit: or .split(' ').join('_') if you have an aversion to REs

Edit: John Resig said:

If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

WSDL/SOAP Test With soapui

  • yes, first ensure you added "?wsdl" to your "http......whatever.svc" link.
    • That didn't fix my problem, though. I had to create a new WCF project from the beginning and manually copy the code. That fixed it. Good luck.

And most important!!!

When you change a namespace in your code, also make sure you change it in web.config!

This view is not constrained

From Android Studio v3 and up, Infer Constraint was removed from the dropdown.

Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.

enter image description here

How to replace text in a column of a Pandas dataframe?

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

Is it better to return null or empty collection?

Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).

Is an HTTPS query string secure?

Yes, as long as no one is looking over your shoulder at the monitor.

PyLint "Unable to import" error - how to set PYTHONPATH?

One workaround that I only just discovered is to actually just run PyLint for the entire package, rather than a single file. Somehow, it manages to find imported module then.

How to center a component in Material-UI and make it responsive?

Here is another option without a grid:

<div
    style={{
        position: 'absolute', 
        left: '50%', 
        top: '50%',
        transform: 'translate(-50%, -50%)'
    }}
>
    <YourComponent/>
</div>

Python list / sublist selection -1 weirdness

-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".

so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3]. The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.

I hope this is somewhat understandable.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Upgrade python without breaking yum

vim `which yum`
modify #/usr/bin/python to #/usr/bin/python2.4

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

PHP 7: Missing VCRUNTIME140.dll

If you've followed Adam's instructions and you're still getting this error make sure you've installed the right variants (x86 or x64).

I had VC14x64 with PHP7x86 and I still got this error. Changing PHP7 to x64 fixed it. It's easy to miss you accidentally installed the wrong version.