Programs & Examples On #Vsunit

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

You must first remove the child view from its parent.

If your project is in Kotlin, your solution will look slightly different than Java. Kotlin simplifies casting with as?, returning null if left side is null or cast fails.

(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)

Kotlin Extension Solution

If you need to do this more than once, add this extension to make your code more readable.

childView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parentView = parent as? ViewGroup ?: return
    parentView.removeView(this)
}

It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup

addEventListener in Internet Explorer

addEventListener is supported from version 9 onwards; for older versions use the somewhat similar attachEvent function.

Linux command to list all available commands and aliases

compgen -c > list.txt && wc list.txt

How can I set a cookie in react?

A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.

VB.NET Switch Statement GoTo Case

Select Case parameter 
    ' does something here. 
    ' does something here. 
    Case "userID", "packageID", "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            goto case default 
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select

Plotting of 1-dimensional Gaussian distribution function

You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.

So just change the gaussian() function to:

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

The standard states that prompting can be controlled by canceling the beforeunload event or setting the return value to a non-null value. It also states that authors should use Event.preventDefault() instead of returnValue, and the message shown to the user is not customizable.

As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress. Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.

It is the author's responsibility to track whether changes have been made; it can be done with a variable or by ensuring the event is only handled when necessary.

_x000D_
_x000D_
window.addEventListener('beforeunload', function (e) {_x000D_
    // Cancel the event as stated by the standard._x000D_
    e.preventDefault();_x000D_
    // Chrome requires returnValue to be set._x000D_
    e.returnValue = '';_x000D_
});_x000D_
    _x000D_
window.location = 'about:blank';
_x000D_
_x000D_
_x000D_

When to use the different log levels

I suggest using only three levels

  1. Fatal - Which would break the application.
  2. Info - Info
  3. Debug - Less important info

How to pass parameters in $ajax POST?

I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
});

If you need to catch the fail cases, just do this:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});

Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.

$.post('superman', { field1: "hello", field2 : "hello2"}, 
     function(returnedData){
        console.log(returnedData);
}, 'json');

How to echo out table rows from the db (php)

$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
    echo "<tr>";
    foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; 
    }
    echo "</tr>";
}
echo "</table>";

In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.

VB.NET - Remove a characters from a String

You can use the string.replace method

string.replace("character to be removed", "character to be replaced with")

Dim strName As String
strName.Replace("[", "")

Where does Chrome store extensions?

For older versions of windows (2k, 2k3, xp)

"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions" 

Plot mean and standard deviation

plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()

plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

Example plot

How should I validate an e-mail address?

This is Android Studio suggestions:

public static boolean isEmailValid(String email) {
    return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

How to host google web fonts on my own server?

You can actually download all font format variants directly from Google and include them in your css to serve from your server. That way you don't have to concern about Google tracking your site's users. However, the downside maybe slowing down your own serving speed. Fonts are quite demanding on resources. I have not done any tests in this issue yet, and wonder if anyone has similar thoughts.

How to load npm modules in AWS Lambda?

npm module has to be bundeled inside your nodejs package and upload to AWS Lambda Layers as zip, then you would need to refer to your module/js as below and use available methods from it. const mymodule = require('/opt/nodejs/MyLogger');

How to set a variable to current date and date-1 in linux?

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic

to

@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

How to replace captured groups only?

A simplier option is to just capture the digits and replace them.

_x000D_
_x000D_
const name = 'preceding_text_0_following_text';_x000D_
const matcher = /(\d+)/;_x000D_
_x000D_
// Replace with whatever you would like_x000D_
const newName = name.replace(matcher, 'NEW_STUFF');_x000D_
console.log("Full replace", newName);_x000D_
_x000D_
// Perform work on the match and replace using a function_x000D_
// In this case increment it using an arrow function_x000D_
const incrementedName = name.replace(matcher, (match) => ++match);_x000D_
console.log("Increment", incrementedName);
_x000D_
_x000D_
_x000D_

Resources

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

JavaScript by reference vs. by value

My understanding is that this is actually very simple:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.

So, to work through some of your examples:

function f(a,b,c) {
    // Argument a is re-assigned to a new value.
    // The object or primitive referenced by the original a is unchanged.
    a = 3;
    // Calling b.push changes its properties - it adds
    // a new property b[b.length] with the value "foo".
    // So the object referenced by b has been changed.
    b.push("foo");
    // The "first" property of argument c has been changed.
    // So the object referenced by c has been changed (unless c is a primitive)
    c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

Example 2:

var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
              // it had at the time of assignment
a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
              // it had at the time of assignment, i.e. a reference to
              // the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

Print line numbers starting at zero using awk

Using awk.

i starts at 0, i++ will increment the value of i, but return the original value that i held before being incremented.

awk '{print i++ "," $0}' file

C: What is the difference between ++i and i++?

Pre-crement means increment on the same line. Post-increment means increment after the line executes.

int j=0;
System.out.println(j); //0
System.out.println(j++); //0. post-increment. It means after this line executes j increments.

int k=0;
System.out.println(k); //0
System.out.println(++k); //1. pre increment. It means it increments first and then the line executes

When it comes with OR, AND operators, it becomes more interesting.

int m=0;
if((m == 0 || m++ == 0) && (m++ == 1)) { //false
/* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
System.out.println("post-increment "+m);
}

int n=0;
if((n == 0 || n++ == 0) && (++n == 1)) { //true
System.out.println("pre-increment "+n); //1
}

In Array

System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 } ;
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); //12

jj = a[1]++; //12
System.out.println(a[1]); //a[1] = 13

mm = a[1];//13
System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13

for (int val: a) {
     System.out.print(" " +val); //55, 13, 15, 20, 25
}

In C++ post/pre-increment of pointer variable

#include <iostream>
using namespace std;

int main() {

    int x=10;
    int* p = &x;

    std::cout<<"address = "<<p<<"\n"; //prints address of x
    std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
    std::cout<<"address = "<<&x<<"\n"; //prints address of x

    std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
}

Handle Button click inside a row in RecyclerView

Just wanted to add another solution if you already have a recycler touch listener and want to handle all of the touch events in it rather than dealing with the button touch event separately in the view holder. The key thing this adapted version of the class does is return the button view in the onItemClick() callback when it's tapped, as opposed to the item container. You can then test for the view being a button, and carry out a different action. Note, long tapping on the button is interpreted as a long tap on the whole row still.

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
    public static interface OnItemClickListener
    {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
    {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
        {
            @Override
            public boolean onSingleTapUp(MotionEvent e)
            {
                // Important: x and y are translated coordinates here
                final ViewGroup childViewGroup = (ViewGroup) recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childViewGroup != null && mListener != null) {
                    final List<View> viewHierarchy = new ArrayList<View>();
                    // Important: x and y are raw screen coordinates here
                    getViewHierarchyUnderChild(childViewGroup, e.getRawX(), e.getRawY(), viewHierarchy);

                    View touchedView = childViewGroup;
                    if (viewHierarchy.size() > 0) {
                        touchedView = viewHierarchy.get(0);
                    }
                    mListener.onItemClick(touchedView, recyclerView.getChildPosition(childViewGroup));
                    return true;
                }

                return false;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
                }
            }
        });
    }

    public void getViewHierarchyUnderChild(ViewGroup root, float x, float y, List<View> viewHierarchy) {
        int[] location = new int[2];
        final int childCount = root.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = root.getChildAt(i);
            child.getLocationOnScreen(location);
            final int childLeft = location[0], childRight = childLeft + child.getWidth();
            final int childTop = location[1], childBottom = childTop + child.getHeight();

            if (child.isShown() && x >= childLeft && x <= childRight && y >= childTop && y <= childBottom) {
                viewHierarchy.add(0, child);
            }
            if (child instanceof ViewGroup) {
                getViewHierarchyUnderChild((ViewGroup) child, x, y, viewHierarchy);
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
    {
        mGestureDetector.onTouchEvent(e);

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Then using it from activity / fragment:

recyclerView.addOnItemTouchListener(createItemClickListener(recyclerView));

    public RecyclerItemClickListener createItemClickListener(final RecyclerView recyclerView) {
        return new RecyclerItemClickListener (context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (view instanceof AppCompatButton) {
                    // ... tapped on the button, so go do something
                } else {
                    // ... tapped on the item container (row), so do something different
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

Git keeps prompting me for a password

##Configuring credential.helper

On OS X (now macOS), run this in Terminal:

git config --global credential.helper osxkeychain

It enables Git to use file Keychain.app to store username and password and to retrieve the passphrase to your private SSH key from the keychain.

For Windows use:

git config --global credential.helper wincred

For Linux use:

git config --global credential.helper cache // If you want to cache the credentials for some time (default 15 minutes)

OR

git config --global credential.helper store // if you want to store the credentials for ever (considered unsafe)

Note : The first method will cache the credentials in memory, whereas the second will store them in ~/.git-credentials in plain text format.

Check here for more info about Linux method.
Check here for more info about all three.

##Troubleshooting

If the Git credential helper is configured correctly macOS saves the passphrase in the keychain. Sometimes the connection between SSH and the passphrases stored in the keychain can break. Run ssh-add -K or ssh-add ~/.ssh/id_rsa to add the key to keychain again.

macOS v10.12 (Sierra) changes to ssh

For macOS v10.12 (Sierra), ssh-add -K needs to be run after every reboot. To avoid this, create ~/.ssh/config with this content.

Host *
   AddKeysToAgent yes
   UseKeychain yes
   IdentityFile ~/.ssh/id_rsa

From the ssh_config man page on 10.12.2:

UseKeychain

On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be 'yes' or 'no'. The default is 'no'.

Apple has added Technote 2449 which explains what happened.

Prior to macOS Sierra, ssh would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.

How to get the type of T from a member of a generic class or method?

Using 3dGrabber's solution:

public static T GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return default(T);
}

//and now 

var list = new Dictionary<string, int>();
var stronglyTypedVar = list.GetEnumeratedType();

How to check if all elements of a list matches a condition?

this way is a bit more flexible than using all():

my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False

or more succinctly:

all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]

Check if a key exists inside a json object

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

_x000D_
_x000D_
var sessionA = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  merchant_id: "sam",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
_x000D_
_x000D_

Is there a function to make a copy of a PHP array to another?

I know this as long time ago, but this worked for me..

$copied_array = array_slice($original_array,0,count($original_array));

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

pip not working in Python Installation in Windows 10

instead of typing in "python". try using "py". for ex:

py -m pip install    packagename
py -m pip --install  packagename
py -m pip --upgrade  packagename
py -m pip upgrade    packagename

note: this should be done in the command prompt "cmd" and not in python idle. also FYI pip is installed with python 3.6 automatically.

How to write a PHP ternary operator

I'd rather than ternary if-statements go with a switch-case. For example:

switch($result->vocation){
case 1:
    echo "Sorcerer";
    break;
case 2:
    echo "Druid";
    break;
case 3:
    echo "Paladin";
    break;
case 4:
    echo "Knight";
    break;
case 5:
    echo "Master Sorcerer";
    break;
case 6:
    echo "Elder Druid";
    break;
case 7:
    echo "Royal Paladin";
    break;
default:
    echo "Elite Knight";
    break;
}

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Object of class stdClass could not be converted to string

In General to get rid of

Object of class stdClass could not be converted to string.

try to use echo '<pre>'; print_r($sql_query); for my SQL Query got the result as

stdClass Object
(
    [num_rows] => 1
    [row] => Array
        (
            [option_id] => 2
            [type] => select
            [sort_order] => 0
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [option_id] => 2
                    [type] => select
                    [sort_order] => 0
                )

        )

)

In order to acces there are different methods E.g.: num_rows, row, rows

echo $query2->row['option_id'];

Will give the result as 2

A better way to check if a path exists or not in PowerShell

To check if a Path exists to a directory, use this one:

$pathToDirectory = "c:\program files\blahblah\"
if (![System.IO.Directory]::Exists($pathToDirectory))
{
 mkdir $path1
}

To check if a Path to a file exists use what @Mathias suggested:

[System.IO.File]::Exists($pathToAFile)

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

Python speed testing - Time Difference - milliseconds

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

How may I reference the script tag that loaded the currently-executing script?

Probably the easiest thing to do would be to give your scrip tag an id attribute.

Generating random numbers with normal distribution in Excel

As @osknows said in a comment above (rather than an answer which is why I am adding this), the Analysis Pack includes Random Number Generation functions (e.g. NORM.DIST, NORM.INV) to generate a set of numbers. A good summary link is at http://www.bettersolutions.com/excel/EUN147/YI231420881.htm.

CSS Background Opacity

I would do something like this

<div class="container">
  <div class="text">
    <p>text yay!</p>
  </div>
</div>

CSS:

.container {
    position: relative;
}

.container::before {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: url('/path/to/image.png');
    opacity: .4;
    content: "";
    z-index: -1;
}

It should work. This is assuming you are required to have a semi-transparent image BTW, and not a color (which you should just use rgba for). Also assumed is that you can't just alter the opacity of the image beforehand in Photoshop.

What is meant by immutable?

Actually String is not immutable if you use the wikipedia definition suggested above.

String's state does change post construction. Take a look at the hashcode() method. String caches the hashcode value in a local field but does not calculate it until the first call of hashcode(). This lazy evaluation of hashcode places String in an interesting position as an immutable object whose state changes, but it cannot be observed to have changed without using reflection.

So maybe the definition of immutable should be an object that cannot be observed to have changed.

If the state changes in an immutable object after it has been created but no-one can see it (without reflection) is the object still immutable?

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

AngularJS : Difference between the $observe and $watch methods

I think this is pretty obvious :

  • $observe is used in linking function of directives.
  • $watch is used on scope to watch any changing in its values.

Keep in mind : both the function has two arguments,

$observe/$watch(value : string, callback : function);
  • value : is always a string reference to the watched element (the name of a scope's variable or the name of the directive's attribute to be watched)
  • callback : the function to be executed of the form function (oldValue, newValue)

I have made a plunker, so you can actually get a grasp on both their utilization. I have used the Chameleon analogy as to make it easier to picture.

List to array conversion to use ravel() function

if variable b has a list then you can simply do the below:

create a new variable "a" as: a=[] then assign the list to "a" as: a=b

now "a" has all the components of list "b" in array.

so you have successfully converted list to array.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

curl_init() function not working

RusAlex answer is right in that for Apache you have to install and enable curl and restart your apache service:

sudo apt-get install php5-curl
sudo service apache2 restart

On my Ubuntu Server with nginx and php5-fpm I however ran into the following problem. I had to restart nginx and php5-fpm like so:

sudo service nginx restart
sudo service php5-fpm restart

But I had non-working php5-fpm processes hanging around, which apparently is a bug in ubuntu https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1242376 So I had to kill all idle php5-fpm processes to able to restart php5-fpm so that the curl module is actually loaded

sudo kill <Process Id of php5-fpm Process)

npm ERR cb() never called

There may be two possibilities=>

  1. Try to update your node js and npm.

  2. Permission issue => a. Move your solution on c drive in your respective user account b. Need to run bash or cmd as administrator.

Hope this will resolve your issue

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

Get nodes where child node contains an attribute

I would think your own suggestion is correct, however the xml is not quite valid. If you are running the //book[title[@lang='it']] on <root>[Your"XML"Here]</root> then the free online xPath testers such as one here will find the expected result.

How do you read CSS rule values with JavaScript?

I made a similar helper function which shows the unneeded styles for this page. appends a <div> to the body listing all styles that where not used.

(to be used with the firebug console)

(function getStyles(){var CSSrules,allRules,CSSSheets, unNeeded, currentRule;
CSSSheets=document.styleSheets;

for(j=0;j<CSSSheets.length;j++){
for(i=0;i<CSSSheets[j].cssRules.length;i++){
    currentRule = CSSSheets[j].cssRules[i].selectorText;

    if(!document.querySelectorAll(currentRule).length){ 
       unNeeded+=CSSSheets[j].cssRules[i].cssText+"<br>"; 
  }       
 }
}

docBody=document.getElementsByTagName("body")[0];
allRulesContainer=document.createElement("div");
docBody.appendChild(allRulesContainer);
allRulesContainer.innerHTML=unNeeded+isHover;
return false
})()

How to dynamically allocate memory space for a string and get that string from user?

You can also use a regular expression, for instance the following piece of code:

char *names
scanf("%m[^\n]", &names)

will get the whole line from stdin, allocating dynamically the amount of space that it takes. After that, of course, you have to free names.

Why is my JavaScript function sometimes "not defined"?

I think your javascript code should be placed between tag,there is need of document load

Check if number is prime number

Prime numbers are numbers that are bigger than one and cannot be divided evenly by any other number except 1 and itself.

@This program will show you the given number is prime or not, and will show you for non prime number that it's divisible by (a number) which is rather than 1 or itself?@

        Console.Write("Please Enter a number: ");
        int number = int.Parse(Console.ReadLine());
        int count = 2; 
        // this is initial count number which is greater than 1

        bool prime = true;
        // used Boolean value to apply condition correctly

        int sqrtOfNumber = (int)Math.Sqrt(number); 
        // square root of input number this would help to simplify the looping.  

        while (prime && count <= sqrtOfNumber)
        {
            if ( number % count == 0)
            {
            Console.WriteLine($"{number} isn't prime and it divisible by 
                                      number {count}");  // this will generate a number isn't prime and it is divisible by a number which is rather than 1 or itself and this line will proves why it's not a prime number.
                prime = false;
            }
            
            count++;
            
        }
        if (prime && number > 1)
        
        {
            Console.WriteLine($"{number} is a prime number");
        }
        else if (prime == true)
        // if input is 1 or less than 1 then this code will generate
        {
            Console.WriteLine($"{number} isn't a prime");
        }
        

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

Answer is very Simple. You Must use app.engine('html') to render *.html Pages. try this.It must Solve the Problem.

app.set('views', path.join(__dirname, 'views'));
**// Set EJS View Engine**
app.set('view engine','ejs');
**// Set HTML engine**
app.engine('html', require('ejs').renderFile);

the .html file Will work

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

How to Apply Corner Radius to LinearLayout

Layout

<LinearLayout 
    android:id="@+id/linearLayout"
    android:layout_width="300dp"
    android:gravity="center"
    android:layout_height="300dp"
    android:layout_centerInParent="true"
    android:background="@drawable/rounded_edge">
 </LinearLayout>

Drawable folder rounded_edge.xml

<shape 
xmlns:android="http://schemas.android.com/apk/res/android">
    <solid 
        android:color="@android:color/darker_gray">
    </solid>
    <stroke 
         android:width="0dp" 
         android:color="#424242">
    </stroke>
    <corners 
         android:topLeftRadius="100dip"
         android:topRightRadius="100dip"
         android:bottomLeftRadius="100dip"
         android:bottomRightRadius="100dip">
    </corners>
</shape>

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to find all links / pages on a website

function getalllinks($url) {
    $links = array();
    if ($fp = fopen($url, 'r')) {
        $content = '';
        while ($line = fread($fp, 1024)) {
            $content. = $line;
        }
    }
    $textLen = strlen($content);
    if ($textLen > 10) {
        $startPos = 0;
        $valid = true;
        while ($valid) {
            $spos = strpos($content, '<a ', $startPos);
            if ($spos < $startPos) $valid = false;
            $spos = strpos($content, 'href', $spos);
            $spos = strpos($content, '"', $spos) + 1;
            $epos = strpos($content, '"', $spos);
            $startPos = $epos;
            $link = substr($content, $spos, $epos - $spos);
            if (strpos($link, 'http://') !== false) $links[] = $link;
        }
    }
    return $links;
}

try this code....

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

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

Do what the error message says:

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

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

  • PostgreSQL isn't running

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

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

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

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

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

So ... check those:

  • ps -f -u postgres should list postgres processes

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

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

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

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

PHP Fatal error: Cannot access empty property

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

How to resolve TypeError: can only concatenate str (not "int") to str

Change secret_string += str(chr(char + 7429146))

To secret_string += chr(ord(char) + 7429146)

ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.

Also, 7429146 is too big of a number, it should be less than 1114111

How to get the last characters in a String in Java, regardless of String size

String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

Modifying a file inside a jar

Yes you can, using SQLite you can read from or write to a database from within the jar file, so that you won't have to extract and then re jar it, follow my post http://shoaibinamdar.in/blog/?p=313

using the syntax "jdbc:sqlite::resource:" you would be able to read and write to a database from within the jar file

Why is access to the path denied?

I got this error and solved it in just a moment. Don't know why all of my folders are read-only,I cancelled the read-only and apply it. However, it is still read-only. So I moved the file into the root folder, it works - so weird.

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Where do I find the bashrc file on Mac?

On some system, instead of the .bashrc file, you can edit your profils' specific by editing:

sudo nano /etc/profile

jquery live hover

jQuery 1.4.1 now supports "hover" for live() events, but only with one event handler function:

$("table tr").live("hover",

function () {

});

Alternatively, you can provide two functions, one for mouseenter and one for mouseleave:

$("table tr").live({
    mouseenter: function () {

    },
    mouseleave: function () {

    }
});

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

you have to match the input format of your date field to the required entity format which is yyyy/mm/dd

Find JavaScript function definition in Chrome

If you are already debugging, you can hover over the function and the tooltip will allow you to navigate directly to the function definition:

Chrome Debugger Function Tooltip / Datatip

Further Reading:

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

How to get distinct results in hibernate with joins and row-based limiting (paging)?

session = (Session) getEntityManager().getDelegate();
Criteria criteria = session.createCriteria(ComputedProdDaily.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("user.id"), "userid");
projList.add(Projections.property("loanState"), "state");
criteria.setProjection(Projections.distinct(projList));
criteria.add(Restrictions.isNotNull("this.loanState"));
criteria.setResultTransformer(Transformers.aliasToBean(UserStateTransformer.class));

This helped me :D

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.

If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Why am I not getting a java.util.ConcurrentModificationException in this example?

I had that same problem but in case that I was adding en element into iterated list. I made it this way

public static void remove(Integer remove) {
    for(int i=0; i<integerList.size(); i++) {
        //here is maybe fine to deal with integerList.get(i)==null
        if(integerList.get(i).equals(remove)) {                
            integerList.remove(i);
        }
    }
}

Now everything goes fine because you don't create any iterator over your list, you iterate over it "manually". And condition i < integerList.size() will never fool you because when you remove/add something into List size of the List decrement/increment..

Hope it helps, for me that was solution.

What is a vertical tab?

The ASCII vertical tab (\x0B)is still used in some databases and file formats as a new line WITHIN a field. For example:

Remove spaces from a string in VB.NET

To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:

While ImageText1.Contains("  ")                     '2 spaces.
    ImageText1 = ImageText1.Replace("  ", " ")      'Replace with 1 space.
End While

Do something if screen width is less than 960 px

You might want to combine it with a resize event:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

For R.J.:

var eventFired = 0;

if ($(window).width() < 960) {
    alert('Less than 960');

}
else {
    alert('More than 960');
    eventFired = 1;
}

$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});

I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.

How to parse SOAP XML?

PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example

$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

Javascript for "Add to Home Screen" on iPhone?

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

How to make a TextBox accept only alphabetic characters?

You can try by handling the KeyPress event for the textbox

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you

EDIT

The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.

How do I conditionally add attributes to React components?

From my point of view the best way to manage multiple conditional props is the props object approach from @brigand. But it can be improved in order to avoid adding one if block for each conditional prop.

The ifVal helper

rename it as you like (iv, condVal, cv, _, ...)

You can define a helper function to return a value, or another, if a condition is met:

// components-helpers.js
export const ifVal = (cond, trueValue=true, falseValue=null) => {
  return cond ? trueValue : falseValue
}

If cond is true (or truthy), the trueValue is returned - or true. If cond is false (or falsy), the falseValue is returned - or null.

These defaults (true and null) are, usually the right values to allow a prop to be passed or not to a React component. You can think to this function as an "improved React ternary operator". Please improve it if you need more control over the returned values.

Let's use it with many props.

Build the (complex) props object

// your-code.js
import { ifVal } from './components-helpers.js'

// BE SURE to replace all true/false with a real condition in you code
// this is just an example

const inputProps = {
  value: 'foo',
  enabled: ifVal(true), // true
  noProp: ifVal(false), // null - ignored by React
  aProp: ifVal(true, 'my value'), // 'my value'
  bProp: ifVal(false, 'the true text', 'the false text') // 'my false value',
  onAction: ifVal(isGuest, handleGuest, handleUser) // it depends on isGuest value
};

 <MyComponent {...inputProps} />

This approach is something similar to the popular way to conditionally manage classes using the classnames utility, but adapted to props.

Why you should use this approach

You'll have a clean and readable syntax, even with many conditional props: every new prop just add a line of code inside the object declaration.

In this way you replace the syntax noise of repeated operators (..., &&, ? :, ...), that can be very annoying when you have many props, with a plain function call.

Our top priority, as developers, is to write the most obvious code that solve a problem. Too many times we solve problems for our ego, adding complexity where it's not required. Our code should be straightforward, for us today, for us tomorrow and for our mates.

just because we can do something doesn't mean we should

I hope this late reply will help.

Throw HttpResponseException or return Request.CreateErrorResponse?

I like Oppositional answer

Anyway, I needed a way to catch the inherited Exception and that solution doesn't satisfy all my needs.

So I ended up changing how he handles OnException and this is my version

public override void OnException(HttpActionExecutedContext actionExecutedContext) {
   if (actionExecutedContext == null || actionExecutedContext.Exception == null) {
      return;
   }

   var type = actionExecutedContext.Exception.GetType();

   Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;

   if (!this.Handlers.TryGetValue(type, out registration)) {
      //tento di vedere se ho registrato qualche eccezione che eredita dal tipo di eccezione sollevata (in ordine di registrazione)
      foreach (var item in this.Handlers.Keys) {
         if (type.IsSubclassOf(item)) {
            registration = this.Handlers[item];
            break;
         }
      }
   }

   //se ho trovato un tipo compatibile, uso la sua gestione
   if (registration != null) {
      var statusCode = registration.Item1;
      var handler = registration.Item2;

      var response = handler(
         actionExecutedContext.Exception.GetBaseException(),
         actionExecutedContext.Request
      );

      // Use registered status code if available
      if (statusCode.HasValue) {
         response.StatusCode = statusCode.Value;
      }

      actionExecutedContext.Response = response;
   }
   else {
      // If no exception handler registered for the exception type, fallback to default handler
      actionExecutedContext.Response = DefaultHandler(actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
      );
   }
}

The core is this loop where I check if the exception type is a subclass of a registered type.

foreach (var item in this.Handlers.Keys) {
    if (type.IsSubclassOf(item)) {
        registration = this.Handlers[item];
        break;
    }
}

my2cents

How to redirect and append both stdout and stderr to a file with Bash?

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1

A nonportable way, starting with Bash 4 is

cmd &>> outfile

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

Remove Fragment Page from ViewPager in Android

My final version code, fixed ALL bugs. It took me 3 days

Updated 2020/07/18: I had changed a lot of the source code and fix so many bugs, but I don't promise it still work today.

https://github.com/lin1987www/FragmentBuilder/blob/master/commonLibrary/src/main/java/android/support/v4/app/FragmentStatePagerAdapterFix.java

public class FragmentStatePagerAdapterFix extends PagerAdapter {
    private static final String TAG = FragmentStatePagerAdapterFix.class.getSimpleName();
    private static final boolean DEBUG = false;

    private WeakReference<FragmentActivity> wrFragmentActivity;
    private WeakReference<Fragment> wrParentFragment;
    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    protected ArrayList<Fragment> mFragments = new ArrayList<>();
    protected ArrayList<FragmentState> mFragmentStates = new ArrayList<>();
    protected ArrayList<String> mFragmentTags = new ArrayList<>();
    protected ArrayList<String> mFragmentClassNames = new ArrayList<>();
    protected ArrayList<Bundle> mFragmentArgs = new ArrayList<>();

    private Fragment mCurrentPrimaryItem = null;
    private boolean[] mTempPositionChange;

    @Override
    public int getCount() {
        return mFragmentClassNames.size();
    }

    public FragmentActivity getFragmentActivity() {
        return wrFragmentActivity.get();
    }

    public Fragment getParentFragment() {
        return wrParentFragment.get();
    }

    public FragmentStatePagerAdapterFix(FragmentActivity activity) {
        mFragmentManager = activity.getSupportFragmentManager();
        wrFragmentActivity = new WeakReference<>(activity);
        wrParentFragment = new WeakReference<>(null);
    }

    public FragmentStatePagerAdapterFix(Fragment fragment) {
        mFragmentManager = fragment.getChildFragmentManager();
        wrFragmentActivity = new WeakReference<>(fragment.getActivity());
        wrParentFragment = new WeakReference<>(fragment);
    }

    public void add(Class<? extends android.support.v4.app.Fragment> fragClass) {
        add(fragClass, null, null);
    }

    public void add(Class<? extends android.support.v4.app.Fragment> fragClass, Bundle args) {
        add(fragClass, args, null);
    }

    public void add(Class<? extends android.support.v4.app.Fragment> fragClass, String tag) {
        add(fragClass, null, tag);
    }

    public void add(Class<? extends android.support.v4.app.Fragment> fragClass, Bundle args, String tag) {
        add(fragClass, args, tag, getCount());
    }

    public void add(Class<? extends android.support.v4.app.Fragment> fragClass, Bundle args, String tag, int position) {
        mFragments.add(position, null);
        mFragmentStates.add(position, null);
        mFragmentTags.add(position, tag);
        mFragmentClassNames.add(position, fragClass.getName());
        mFragmentArgs.add(position, args);
        mTempPositionChange = new boolean[getCount()];
    }

    public void remove(int position) {
        if (position < getCount()) {
            mTempPositionChange = new boolean[getCount()];
            for (int i = position; i < mTempPositionChange.length; i++) {
                mTempPositionChange[i] = true;
            }
            mFragments.remove(position);
            mFragmentStates.remove(position);
            mFragmentTags.remove(position);
            mFragmentClassNames.remove(position);
            mFragmentArgs.remove(position);
        }
    }

    public void clear(){
        mFragments.clear();
        mFragmentStates.clear();
        mFragmentTags.clear();
        mFragmentClassNames.clear();
        mFragmentArgs.clear();
    }

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment;
        // If we already have this item instantiated, there is nothing
        // to do.  This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.
        fragment = mFragments.get(position);
        if (fragment != null) {
            return fragment;
        }
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        FragmentState fs = mFragmentStates.get(position);
        if (fs != null) {
            fragment = fs.instantiate(getFragmentActivity(), getParentFragment());
            // Fix bug
            // http://stackoverflow.com/questions/11381470/classnotfoundexception-when-unmarshalling-android-support-v4-view-viewpagersav
            if (fragment.mSavedFragmentState != null) {
                fragment.mSavedFragmentState.setClassLoader(fragment.getClass().getClassLoader());
            }
        }
        if (fragment == null) {
            fragment = Fragment.instantiate(getFragmentActivity(), mFragmentClassNames.get(position), mFragmentArgs.get(position));
        }
        if (DEBUG) {
            Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        mFragmentStates.set(position, null);
        mCurTransaction.add(container.getId(), fragment, mFragmentTags.get(position));
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) {
            Log.v(TAG, "Removing item #" + position + ": f=" + object
                    + " v=" + ((Fragment) object).getView());
        }
        if (position < getCount()) {
            FragmentState fragmentState = new FragmentState(fragment);
            Fragment.SavedState savedState = mFragmentManager.saveFragmentInstanceState(fragment);
            if (savedState != null) {
                fragmentState.mSavedFragmentState = savedState.mState;
            }
            mFragmentStates.set(position, fragmentState);
            mFragments.set(position, null);
        }
        mCurTransaction.remove(fragment);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
            // Fix: Fragment is added by transaction. BUT didn't add to FragmentManager's mActive.
            for (Fragment fragment : mFragments) {
                if (fragment != null) {
                    fixActiveFragment(mFragmentManager, fragment);
                }
            }
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment) object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        // ????? Fragments
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null && f.isAdded()) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        if (mFragmentStates.size() > 0) {
            if (state == null) {
                state = new Bundle();
            }
            FragmentState[] fs = new FragmentState[mFragmentStates.size()];
            mFragmentStates.toArray(fs);
            state.putParcelableArray("states_fragment", fs);
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle) state;
            bundle.setClassLoader(loader);
            Parcelable[] fs = bundle.getParcelableArray("states_fragment");
            mFragments.clear();
            mFragmentStates.clear();
            mFragmentTags.clear();
            mFragmentClassNames.clear();
            mFragmentArgs.clear();
            if (fs != null) {
                for (int i = 0; i < fs.length; i++) {
                    FragmentState fragmentState = (FragmentState) fs[i];
                    mFragmentStates.add(fragmentState);
                    if (fragmentState != null) {
                        mFragmentArgs.add(fragmentState.mArguments);
                        mFragmentTags.add(fragmentState.mTag);
                        mFragmentClassNames.add(fragmentState.mClassName);
                    } else {
                        mFragmentArgs.add(null);
                        mFragmentTags.add(null);
                        mFragmentClassNames.add(null);
                    }
                    mFragments.add(null);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key : keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                        mFragmentArgs.set(index, f.mArguments);
                        mFragmentTags.set(index, f.mTag);
                        mFragmentClassNames.set(index, f.getClass().getName());
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
            // If restore will change
            notifyDataSetChanged();
        }
    }

    public static void fixActiveFragment(FragmentManager fragmentManager, Fragment fragment) {
        FragmentManagerImpl fm = (FragmentManagerImpl) fragmentManager;
        if (fm.mActive != null) {
            int index = fragment.mIndex;
            Fragment origin = fm.mActive.get(index);
            if (origin != null) {
                if ((origin.mIndex != fragment.mIndex) || !(origin.equals(fragment))) {
                    Log.e(TAG,
                            String.format("fixActiveFragment: Not Equal! Origin: %s %s, Fragment: %s $s",
                                    origin.getClass().getName(), origin.mIndex,
                                    fragment.getClass().getName(), fragment.mIndex
                            ));
                }
            }
            fm.mActive.set(index, fragment);
        }
    }

    // Fix
    // http://stackoverflow.com/questions/10396321/remove-fragment-page-from-viewpager-in-android
    @Override
    public int getItemPosition(Object object) {
        int index = mFragments.indexOf(object);
        if (index < 0) {
            return PagerAdapter.POSITION_NONE;
        }
        boolean isPositionChange = mTempPositionChange[index];
        int result = PagerAdapter.POSITION_UNCHANGED;
        if (isPositionChange) {
            result = PagerAdapter.POSITION_NONE;
        }
        return result;
    }
}

How to update UI from another thread running in another class

Felt the need to add this better answer, as nothing except BackgroundWorker seemed to help me, and the answer dealing with that thus far was woefully incomplete. This is how you would update a XAML page called MainWindow that has an Image tag like this:

<Image Name="imgNtwkInd" Source="Images/network_on.jpg" Width="50" />

with a BackgroundWorker process to show if you are connected to the network or not:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

public partial class MainWindow : Window
{
    private BackgroundWorker bw = new BackgroundWorker();

    public MainWindow()
    {
        InitializeComponent();

        // Set up background worker to allow progress reporting and cancellation
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;

        // This is your main work process that records progress
        bw.DoWork += new DoWorkEventHandler(SomeClass.DoWork);

        // This will update your page based on that progress
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

        // This starts your background worker and "DoWork()"
        bw.RunWorkerAsync();

        // When this page closes, this will run and cancel your background worker
        this.Closing += new CancelEventHandler(Page_Unload);
    }

    private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        BitmapImage bImg = new BitmapImage();
        bool connected = false;
        string response = e.ProgressPercentage.ToString(); // will either be 1 or 0 for true/false -- this is the result recorded in DoWork()

        if (response == "1")
            connected = true;

        // Do something with the result we got
        if (!connected)
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_off.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
        else
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_on.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
    }

    private void Page_Unload(object sender, CancelEventArgs e)
    {
        bw.CancelAsync();  // stops the background worker when unloading the page
    }
}


public class SomeClass
{
    public static bool connected = false;

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bw = sender as BackgroundWorker;

        int i = 0;
        do 
        {
            connected = CheckConn();  // do some task and get the result

            if (bw.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                Thread.Sleep(1000);
                // Record your result here
                if (connected)
                    bw.ReportProgress(1);
                else
                    bw.ReportProgress(0);
            }
        }
        while (i == 0);
    }

    private static bool CheckConn()
    {
        bool conn = false;
        Ping png = new Ping();
        string host = "SomeComputerNameHere";

        try
        {
            PingReply pngReply = png.Send(host);
            if (pngReply.Status == IPStatus.Success)
                conn = true;
        }
        catch (PingException ex)
        {
            // write exception to log
        }
        return conn;
    }
}

For more information: https://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

Getting the class of the element that fired an event using JQuery

If you are using jQuery 1.7:

alert($(this).prop("class"));

or:

alert($(event.target).prop("class"));

Replace tabs with spaces in vim

IIRC, something like:

set tabstop=2 shiftwidth=2 expandtab

should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.

If you already have tabs you want to replace,

:retab

How to check whether a string contains a substring in Ruby

A more succinct idiom than the accepted answer above that's available in Rails (from 3.1.0 and above) is .in?:

my_string = "abcdefg"
if "cde".in? my_string
  puts "'cde' is in the String."
  puts "i.e. String includes 'cde'"
end

I also think it's more readable.

See the in? documentation for more information.

Note again that it's only available in Rails, and not pure Ruby.

Detect the Enter key in a text input field

The solution that work for me is the following

$("#element").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // do something
    }
});

conversion from string to json object android

Using Kotlin

    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
    
try {
      val jsonObject = JSONObject(data)
      val infoObj = jsonObject.getJSONObject("ApiInfo")
    } catch (e: Exception) {
    }

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

Check if bash variable equals 0

Looks like your depth variable is unset. This means that the expression [ $depth -eq $zero ] becomes [ -eq 0 ] after bash substitutes the values of the variables into the expression. The problem here is that the -eq operator is incorrectly used as an operator with only one argument (the zero), but it requires two arguments. That is why you get the unary operator error message.

EDIT: As Doktor J mentioned in his comment to this answer, a safe way to avoid problems with unset variables in checks is to enclose the variables in "". See his comment for the explanation.

if [ "$depth" -eq "0" ]; then
   echo "false";
   exit;
fi

An unset variable used with the [ command appears empty to bash. You can verify this using the below tests which all evaluate to true because xyz is either empty or unset:

  • if [ -z ] ; then echo "true"; else echo "false"; fi
  • xyz=""; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
  • unset xyz; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi

Communication between tabs or windows

I created a module that works equal to the official Broadcastchannel but has fallbacks based on localstorage, indexeddb and unix-sockets. This makes sure it always works even with Webworkers or NodeJS. See pubkey:BroadcastChannel

How to get to Model or Viewbag Variables in a Script Tag

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);

Why does "pip install" inside Python raise a SyntaxError?

you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

this is calling pip like pip <commands> in terminal. The commands will be seperated by spaces that you are doing there to.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You could use THROW (available in SQL Server 2012+):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>

MSDN THROW (Transact-SQL)

Differences Between RAISERROR and THROW in Sql Server

What is the best IDE for PHP?

For PHP in particular, PHPEdit is the best, and I tried and worked in some of them including, Dreamweaver, Elipse, Emacs, Notepad++, NetBeans, UltraEdit ...

How can I format date by locale in Java?

Joda-Time

Using the Joda-Time 2.4 library. The DateTimeFormat class is a factory of DateTimeFormatter formatters. That class offers a forStyle method to access formatters appropriate to a Locale.

DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );

The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.

Note that we specified both a Locale and a time zone. Some people confuse the two.

  • A time zone is an offset from UTC and a set of rules for Daylight Saving Time and other anomalies along with their historical changes.
  • A Locale is a human language such as Français, plus a country code such as Canada that represents cultural practices including formatting of date-time strings.

We need all those pieces to properly generate a string representation of a date-time value.

How to restore/reset npm configuration to default values?

If it's about just one property - let's say you want to temporarily change some default, for instance disable CA checking: you can do it with

npm config set ca ""

To come back to the defaults for that setting, simply

npm config delete ca

To verify, use npm config get ca.

How to create full path with node's fs.mkdirSync?

fs-extra adds file system methods that aren't included in the native fs module. It is a drop in replacement for fs.

Install fs-extra

$ npm install --save fs-extra

const fs = require("fs-extra");
// Make sure the output directory is there.
fs.ensureDirSync(newDest);

There are sync and async options.

https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md

initialize a numpy array

To initialize a numpy array with a specific matrix:

import numpy as np

mat = np.array([[1, 1, 0, 0, 0],
                [0, 1, 0, 0, 1],
                [1, 0, 0, 1, 1],
                [0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1]])

print mat.shape
print mat

output:

(5, 5)
[[1 1 0 0 0]
 [0 1 0 0 1]
 [1 0 0 1 1]
 [0 0 0 0 0]
 [1 0 1 0 1]]

CodeIgniter htaccess and URL rewrite issues

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /dmizone_bkp
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
   RewriteRule ^(.*)$ /dmizone_bkp/index.php?/$1 [L]
</IfModule> 

How to read all files in a folder from Java?

to prevent Nullpointerexceptions on the listFiles() function and recursivly get all files from subdirectories too..

 public void listFilesForFolder(final File folder,List<File> fileList) {
    File[] filesInFolder = folder.listFiles();
    if (filesInFolder != null) {
        for (final File fileEntry : filesInFolder) {
            if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry,fileList);
        } else {
            fileList.add(fileEntry);
        }
     }
    }
 }

 List<File> fileList = new List<File>();
 final File folder = new File("/home/you/Desktop");
 listFilesForFolder(folder);

PHP cURL, extract an XML response

$sXML = download_page('http://alanstorm.com/atom');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);

Java JTable getting the data of the selected row

if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.getSelectedRow());

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

How to redirect to action from JavaScript method?

Youcan either send a Ajax request to server or use window.location to that url.

How to get the separate digits of an int number?

if digit is meant to be a Character

String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
  s -> s.charAt( 0 ) ).toArray( Character[]::new );  // [1, 2, 3]

and the following works correctly
numstr = "000123" gets [0, 0, 0, 1, 2, 3]
numstr = "-123"    gets [-, 1, 2, 3]

Convert Unix timestamp into human readable date using MySQL

Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.

I have an automatically updated last_modified field, defined as:

`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC

SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`

In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.

Run this twice, first without setting the time_zone.

Import data.sql MySQL Docker Container

I can import with this command

docker-compose exec -T mysql mysql -uroot -proot mydatabase < ~/Desktop/mydatabase_2019-10-05.sql

Adding items in a Listbox with multiple columns

There is one more way to achieve it:-

Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
    .Top = 30
    .Left = 30
    .Width = 200
    .Height = 340
    .ColumnHeads = True
    .ColumnCount = 2
    .ColumnWidths = "100;100"
    .MultiSelect = fmMultiSelectExtended
    .RowSource = "Sheet1!C4:D25"
End With End Sub

Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.

The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

You can update the angular with command 'ng update --all'. It will take time but make sure your all components are up to date.

Getting Textarea Value with jQuery

change id="#message" to id="message" on your textarea element.

and by the way, just use this:

$('#send-thoughts')

remember that you should only use ID's once and you can use classes over and over.

https://css-tricks.com/the-difference-between-id-and-class/

Convert a python dict to a string and back

The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.

import json
json.dumps(dict)

Background service with location listener in android

Background location service. It will be restarted even after killing the app.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AlarmManager alarmManager;
    Button stop;
    PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (alarmManager == null) {
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, AlarmReceive.class);
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
                    pendingIntent);
        }
    }
}

BookingTrackingService.java

public class BookingTrackingService extends Service implements LocationListener {

    private static final String TAG = "BookingTrackingService";
    private Context context;
    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;
    LocationManager locationManager;
    Location location;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 30000;

    public double track_lat = 0.0;
    public double track_lng = 0.0;
    public static String str_receiver = "servicetutorial.service.receiver";
    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.context = this;


        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy <<");
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    private void trackLocation() {
        Log.e(TAG, "trackLocation");
        String TAG_TRACK_LOCATION = "trackLocation";
        Map<String, String> params = new HashMap<>();
        params.put("latitude", "" + track_lat);
        params.put("longitude", "" + track_lng);

        Log.e(TAG, "param_track_location >> " + params.toString());

        stopSelf();
        mTimer.cancel();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /******************************/

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable) {
            Log.e(TAG, "CAN'T GET LOCATION");
            stopSelf();
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            if (isGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            Log.e(TAG, "START SERVICE");
            trackLocation();

        }
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

//    private void fn_update(Location location) {
//
//        intent.putExtra("latutide", location.getLatitude() + "");
//        intent.putExtra("longitude", location.getLongitude() + "");
//        sendBroadcast(intent);
//    }
}

AlarmReceive.java (BroadcastReceiver)

public class AlarmReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("Service_call_"  , "You are in AlarmReceive class.");
        Intent background = new Intent(context, BookingTrackingService.class);
//        Intent background = new Intent(context, GoogleService.class);
        Log.e("AlarmReceive ","testing called broadcast called");
        context.startService(background);
    }
}

AndroidManifest.xml

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

 <service
            android:name=".ServiceAndBroadcast.BookingTrackingService"
            android:enabled="true" />

        <receiver
            android:name=".ServiceAndBroadcast.AlarmReceive"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

How to call C++ function from C?

I would do it in the following way:

(If working with MSVC, ignore the GCC compilation commands)

Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.

The C++ code of class AAA - Pure C++, I don't modify it:

aaa.h

#ifndef AAA_H
#define AAA_H

class AAA {
    public:
        AAA();
        void sayHi(const char *name);
};

#endif

aaa.cpp

#include <iostream>

#include "aaa.h"

AAA::AAA() {
}

void AAA::sayHi(const char *name) {
    std::cout << "Hi " << name << std::endl;
}

Compiling this class as regularly done for C++. This code "does not know" that it is going to be used by C code. Using the command:

g++ -fpic -shared aaa.cpp -o libaaa.so

Now, also in C++, creating a C connector. Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:

aaa_c_connector.h

#ifndef AAA_C_CONNECTOR_H 
#define AAA_C_CONNECTOR_H 

#ifdef __cplusplus
extern "C" {
#endif

void AAA_sayHi(const char *name);

#ifdef __cplusplus
}
#endif


#endif

aaa_c_connector.cpp

#include <cstdlib>

#include "aaa_c_connector.h"
#include "aaa.h"

#ifdef __cplusplus
extern "C" {
#endif

// Inside this "extern C" block, I can implement functions in C++, which will externally 
//   appear as C functions (which means that the function IDs will be their names, unlike
//   the regular C++ behavior, which allows defining multiple functions with the same name
//   (overloading) and hence uses function signature hashing to enforce unique IDs),


static AAA *AAA_instance = NULL;

void lazyAAA() {
    if (AAA_instance == NULL) {
        AAA_instance = new AAA();
    }
}

void AAA_sayHi(const char *name) {
    lazyAAA();
    AAA_instance->sayHi(name);
}

#ifdef __cplusplus
}
#endif

Compiling it, again, using a regular C++ compilation command:

g++ -fpic -shared aaa_c_connector.cpp -L. -laaa -o libaaa_c_connector.so

Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:

main.c

#include "aaa_c_connector.h"

int main() {
    AAA_sayHi("David");
    AAA_sayHi("James");

    return 0;
}

Compiling it using a C compilation command:

gcc main.c -L. -laaa_c_connector -o c_aaa

I will need to set LD_LIBRARY_PATH to contain $PWD, and if I run the executable ./c_aaa, I will get the output I expect:

Hi David
Hi James

EDIT:

On some linux distributions, -laaa and -lstdc++ may also be required for the last compilation command. Thanks to @AlaaM. for the attention

How to append elements into a dictionary in Swift?

Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

Example-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")

Result-

?  : 2 elements
    - key : "userId"
    - value : 866
?  : 2 elements
    - key : "otherNotes"
    - value : "Hello"

How to deal with SQL column names that look like SQL keywords?

If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.

select [select]
from [table]

"could not find stored procedure"

There are 2 causes:

1- store procedure name When you declare store procedure in code make sure you do not exec or execute keyword for example:

C#

string sqlstr="sp_getAllcustomers";// right way to declare it.

string sqlstr="execute sp_getAllCustomers";//wrong way and you will get that error message.

From this code:

MSDBHelp.ExecuteNonQuery(sqlconexec, CommandType.StoredProcedure, sqlexec);

CommandType.StoreProcedure will look for only store procedure name and ExecuteNonQuery will execute the store procedure behind the scene.

2- connection string:

Another cause is the wrong connection string. Look inside the connection string and make sure you have the connection especially the database name and so on.

How to save a git commit message from windows cmd?

Press Shift-zz. Saves changes and Quits. Escape didn't work for me.

I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.

Python wildcard search in string

Same idea as Yuushi in using regular expressions, but this uses the findall method within the re library instead of a list comprehension:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)

How can I list ALL DNS records?

When you query for ANY you will get a list of all records at that level but not below.

# try this
dig google.com any

This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly "google.com". However, it will not return child records (e.g., www.google.com). More precisely, you MAY get these records if they exist. The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response).

An AXFR is a zone transfer and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).

# This will return "Transfer failed"
dig @ns1.google.com google.com axfr

If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the the client can send to the server to authorize the transfer.

Environment variable substitution in sed

With your question edit, I see your problem. Let's say the current directory is /home/yourname ... in this case, your command below:

sed 's/xxx/'$PWD'/'

will be expanded to

sed `s/xxx//home/yourname//

which is not valid. You need to put a \ character in front of each / in your $PWD if you want to do this.

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

Create a custom callback in JavaScript

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

Example:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

This is the Codepend with full example.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

When I use junit5, it's working. But every time I execute gradle --clean, I get Class not found error. Then I add this to build.gradle to resolve my problem and I can still use junit4:

test {
}

Eclipse jump to closing brace

Place the cursor next to an opening or closing brace and punch Ctrl + Shift + P to find the matching brace. If Eclipse can't find one you'll get a "No matching bracket found" message.

edit: as mentioned by Romaintaz below, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.

Catch KeyError in Python

You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

Alternatively, a good way to debug this kind of thing is to say:

except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.

Split (explode) pandas dataframe string entry to separate rows

After painful experimentation to find something faster than the accepted answer, I got this to work. It ran around 100x faster on the dataset I tried it on.

If someone knows a way to make this more elegant, by all means please modify my code. I couldn't find a way that works without setting the other columns you want to keep as the index and then resetting the index and re-naming the columns, but I'd imagine there's something else that works.

b = DataFrame(a.var1.str.split(',').tolist(), index=a.var2).stack()
b = b.reset_index()[[0, 'var2']] # var1 variable is currently labeled 0
b.columns = ['var1', 'var2'] # renaming var1

Mailto links do nothing in Chrome but work in Firefox?

Another solution is to implement your own custom popup/form/user control that will be universally interpreted across all browsers.

Granted this will not leverage the "mailto" out of the box capabilities. It all depends on what availability adherence you are working against. Unfortunately for myself - the mailto needed to be available to everyone by default without "inconveniencing the client".

Your decision ultimately.

PHP cURL HTTP CODE return 0

Try this:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Defining private module functions in python

Python allows for private class members with the double underscore prefix. This technique doesn't work at a module level so I am thinking this is a mistake in Dive Into Python.

Here is an example of private class functions:

class foo():
    def bar(self): pass
    def __bar(self): pass

f = foo()
f.bar()   # this call succeeds
f.__bar() # this call fails

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Was following one of training with Spring webmvc 4.2.3, while I'm using Spring webmvc 5.2.3 they suggested to create a form

<form:form modelAttribute="aNewAccount" method="get" action="/accountCreated">

that was causing the "disclose" error.

Altered as below to make it work. Looks like method above was the culprit.

<form:form modelAttribute="aNewAccount" action="accountCreated.html">

in fact, exploring further, method="post" in form annotation would work if properly declared:

@RequestMapping(value="/accountCreated", method=RequestMethod.POST)

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

_tkinter.TclError: no display name and no $DISPLAY environment variable

I want to add an answer here that noone has explicitly stated with implementation.

This is a great resource to refer to for this failure: https://matplotlib.org/faq/usage_faq.html

In my case, using matplotlib.use did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:

export MPLBACKEND=Agg

This takes care of the issue.

My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest, however would fail when using parallelism along with circleci tests split feature. However, declaring this env variable resolved the issue.

How to reference Microsoft.Office.Interop.Excel dll?

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this ('Microsoft Excel 12.0 Object Library' if you want to use Office 2007)

enter image description here

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

Easiest way to convert int to string in C++

If you're using MFC, you can use CString:

int a = 10;
CString strA;
strA.Format("%d", a);

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Personnaly I encountered this issue while migrating a IIS6 website into IIS7, in order to fix this issue I used this command line :
%windir%\System32\inetsrv\appcmd migrate config "MyWebSite\"
Make sure to backup your web.config

ORA-28000: the account is locked error getting frequently

Solution 01

Account Unlock by using below query :

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       LOCKED

SQL> alter user ABCD_DEV account unlock;    
User altered.

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       OPEN

Solution 02

Check PASSWORD_LIFE_TIME parameter by using below query :

SELECT resource_name, limit FROM dba_profiles WHERE profile = 'DEFAULT' AND resource_type = 'PASSWORD';

RESOURCE_NAME                    LIMIT
-------------------------------- ------------------------------
FAILED_LOGIN_ATTEMPTS            10
PASSWORD_LIFE_TIME               10
PASSWORD_REUSE_TIME              10
PASSWORD_REUSE_MAX               UNLIMITED
PASSWORD_VERIFY_FUNCTION         NULL
PASSWORD_LOCK_TIME               1
PASSWORD_GRACE_TIME              7
INACTIVE_ACCOUNT_TIME            UNLIMITED

Change the parameter using below query

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

Java 8: Lambda-Streams, Filter by Method with Exception

Your example can be written as:

import utils.stream.Unthrow;

class Bank{
   ....
   public Set<String> getActiveAccountNumbers() {
       return accounts.values().stream()
           .filter(a -> Unthrow.wrap(() -> a.isActive()))
           .map(a -> Unthrow.wrap(() -> a.getNumber()))
           .collect(Collectors.toSet());
   }
   ....
}

The Unthrow class can be taken here https://github.com/SeregaLBN/StreamUnthrower

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

git: How to ignore all present untracked files?

-u no doesn't show unstaged files either. -uno works as desired and shows unstaged, but hides untracked.

What is the difference between resource and endpoint?

According https://apiblueprint.org/documentation/examples/13-named-endpoints.html is a resource a "general" place of storage of the given entity - e.g. /customers/30654/orders, whereas an endpoint is the concrete action (HTTP Method) over the given resource. So one resource can have multiple endpoints.

The meaning of NoInitialContextException error

Easy & configurable solution is create one jndi.properties file and put this file in classpath. jndi.properties can be created as

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = vm://localhost

# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue


# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic

Just specify your naming factory & url and put this file in your classpath. JMS will fetch required info by itself and it's easily configurable in future also.

Windows batch: formatted date into variable

Check this one..

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

Fastest way to extract frames using ffmpeg?

If you know exactly which frames to extract, eg 1, 200, 400, 600, 800, 1000, try using:

select='eq(n\,1)+eq(n\,200)+eq(n\,400)+eq(n\,600)+eq(n\,800)+eq(n\,1000)' \
       -vsync vfr -q:v 2

I'm using this with a pipe to Imagemagick's montage to get 10 frames preview from any videos. Obviously the frame numbers you'll need to figure out using ffprobe

ffmpeg -i myVideo.mov -vf \
    select='eq(n\,1)+eq(n\,200)+eq(n\,400)+eq(n\,600)+eq(n\,800)+eq(n\,1000)',scale=320:-1 \
    -vsync vfr -q:v 2 -f image2pipe -vcodec ppm - \
  | montage -tile x1 -geometry "1x1+0+0<" -quality 100 -frame 1 - output.png

.

Little explanation:

  1. In ffmpeg expressions + stands for OR and * for AND
  2. \, is simply escaping the , character
  3. Without -vsync vfr -q:v 2 it doesn't seem to work but I don't know why - anyone?

Transposing a 2D-array in JavaScript

Another approach by iterating the array from outside to inside and reduce the matrix by mapping inner values.

_x000D_
_x000D_
const_x000D_
    transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),_x000D_
    matrix = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];_x000D_
_x000D_
console.log(transpose(matrix));
_x000D_
_x000D_
_x000D_

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Web application context, specified by the WebApplicationContext interface, is a Spring application context for a web applications. It has all the properties of a regular Spring application context, given that the WebApplicationContext interface extends the ApplicationContext interface, and add a method for retrieving the standard Servlet API ServletContext for the web application.

In addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:

  • request - scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition
  • session - scopes a single bean definition to the lifecycle of an HTTP Session
  • application - scopes a single bean definition to the lifecycle of a ServletContext

how to convert an RGB image to numpy array?

PIL (Python Imaging Library) and Numpy work well together.

I use the following functions.

from PIL import Image
import numpy as np

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
    img.save( outfilename )

The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.

An RGB image would be something like:

 outimg = Image.fromarray( ycc_uint8, "RGB" )
 outimg.save( "ycc.tif" )

How to enumerate an object's properties in Python?

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of a dictionary (which is different from an 'object' in Python), use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

Get class name using jQuery

This works too.

const $el = $(".myclass");
const className = $el[0].className;

How do I check if a directory exists? "is_dir", "file_exists" or both?

I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath

Here is an example function:

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (long version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    if($path !== false AND is_dir($path))
    {
        // Return canonicalized absolute pathname
        return $path;
    }

    // Path/folder does not exist
    return false;
}

Short version of the same function

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (sort version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    return ($path !== false AND is_dir($path)) ? $path : false;
}

Output examples

<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input);               // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output);              // bool(false)

/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input);         // string(5) "/home"
var_dump($output);              // string(5) "/home"

/** CASE 3 **/
$input = '/home/..';
var_dump($input);               // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output);              // string(1) "/"

Usage

<?php

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))
{
    die('Folder ' . $path . ' already exist');
}

mkdir($folder);
// Continue do stuff

How to download a file from a website in C#

Use WebClient.DownloadFile:

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

How does C#'s random number generator work?

I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}

Simple explanation,

  1. create a 1 dimensional integer array.
  2. full up the array with unordered numbers.
  3. use the rnd.Next to get the position of the number that will be picked.

This works well.

To obtain a random number less than 100 use

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}

and so on for 3, 4, 5, and 6 ... digit random numbers.

Hope this assists someone positively.

Format string to a 3 digit number

(Can't comment yet with enough reputation , let me add a sidenote)

Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .

yourNumber=1001;
yourString= yourNumber.ToString("D3");        // "1001" 
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected

Trail sample on Fiddler https://dotnetfiddle.net/qLrePt

ld: framework not found Pods

In my case, after comparing the difference between a branch I knew built correctly, I noticed this line in my Podfile:

platform :ios, '11.0'

I had inadvertently up'd my target version from 10 to 11 while my targets in Xcode remained set to 10. Reverting back to 10 solved my issue for me.

Ensure your target iOS versions are properly set.

load and execute order of scripts

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

To test this fact:

// file: test.php
sleep(10);
die("alert('Done!');");

// HTML file:
<script type="text/javascript" src="test.php"></script>

Dynamically added scripts are executed as soon as they are appended to the document.

To test this fact:

<!DOCTYPE HTML>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.src = "link.js"; // file contains alert("hello!");
        document.body.appendChild(s);
        alert("appended");
    </script>
    <script type="text/javascript">
        alert("final");
    </script>
</body>
</html>

Order of alerts is "appended" -> "hello!" -> "final"

If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>) then you will get an error.

Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script> tag and start a new one.

Excel formula to remove space between words in a cell

Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.

How to position a table at the center of div horizontally & vertically

You can center a box both vertically and horizontally, using the following technique :

The outher container :

  • should have display: table;

The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box :

  • should have display: inline-block;

If you use this technique, just add your table (along with any other content you want to go with it) to the content box.

Demo :

_x000D_
_x000D_
body {_x000D_
    margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
    position : absolute;_x000D_
    display: table;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
    display: inline-block;_x000D_
    background: #fff;_x000D_
    padding : 20px;_x000D_
    border : 1px solid #000;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
   <div class="inner-container">_x000D_
     <div class="centered-content">_x000D_
        <em>Data :</em>_x000D_
        <table>_x000D_
            <tr>_x000D_
                <th>Name</th>_x000D_
                <th>Age</th>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>Tom</td>_x000D_
                <td>15</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>Anne</td>_x000D_
                <td>15</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>Gina</td>_x000D_
                <td>34</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
     </div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

How to fix request failed on channel 0

As you already found the -T flag that create a PTY, I will just respond to the second part:

shell request failed on channel 0

You should pass a command:

ssh [email protected] -p 22 help

After reading back the manual here: https://www.jenkins.io/doc/book/managing/cli/, I find it not really clear that it would not work without a command. But as stated by @U.V., the ssh interface is not a console interface, rather a connection utility. So you need to pass a command...

If someone from the "jenkins" team pass accross this post, it would be great that if we pass no command, the help would show up :-)

Call method in directive controller from other controller

I got much better solution .

here is my directive , I have injected on object reference in directive and has extend that by adding invoke function in directive code .

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
        /*The object that passed from the cntroller*/
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',

        link: function ($scope, element, attrs) {
            /*This method will be called whet the 'objectToInject' value is changes*/
            $scope.$watch('objectToInject', function (value) {
                /*Checking if the given value is not undefined*/
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                }    
            });
        }
    };
});

Declaring the directive in the HTML with a parameter:

<my-directive object-to-inject="injectedObject"></ my-directive>

my Controller:

app.controller("myController", ['$scope', function ($scope) {
   // object must be empty initialize,so it can be appended
    $scope.injectedObject = {};

    // now i can directly calling invoke function from here 
     $scope.injectedObject.invoke();
}];

What is the difference between active and passive FTP?

Active Mode—The client issues a PORT command to the server signaling that it will “actively” provide an IP and port number to open the Data Connection back to the client.

Passive Mode—The client issues a PASV command to indicate that it will wait “passively” for the server to supply an IP and port number, after which the client will create a Data Connection to the server.

There are lots of good answers above, but this blog post includes some helpful graphics and gives a pretty solid explanation: https://titanftp.com/2018/08/23/what-is-the-difference-between-active-and-passive-ftp/

How can I use iptables on centos 7?

If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:

Put the following lines in /etc/fail2ban/jail.d/sshd.local

[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
logpath  = /var/log/secure
maxretry = 5
bantime = 86400

Enable and start fail2ban:

systemctl enable fail2ban
systemctl start fail2ban

Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/

How do I replace all the spaces with %20 in C#?

To properly escape spaces as well as the rest of the special characters, use System.Uri.EscapeDataString(string stringToEscape).

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

Convert Bitmap to File

Try this:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

See this

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

Differences between utf8 and latin1

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

How to split data into training/testing sets using sample function

Use caTools package in R sample code will be as follows:-

data
split = sample.split(data$DependentcoloumnName, SplitRatio = 0.6)
training_set = subset(data, split == TRUE)
test_set = subset(data, split == FALSE)

Can anonymous class implement interface?

The best solution is just not to use anonymous classes.

public class Test
{
    class DummyInterfaceImplementor : IDummyInterface
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new DummyInterfaceImplementor()
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());

    }

    public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.

ASP.Net MVC 4 Form with 2 submit buttons/actions

If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".

@{
  if (IsPost)
    {
       if(Request["btn"].Equals("button_A"))
        {
          Response.Redirect("PageA.cshtml");
        }
      if(Request["btn"].Equals("button_B"))
        {
          Response.Redirect("PageB.cshtml");
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

How to display request headers with command line curl

curl's -v or --verbose option shows the HTTP request headers, among other things. Here is some sample output:

$ curl -v http://google.com/
* About to connect() to google.com port 80 (#0)
*   Trying 66.102.7.104... connected
* Connected to google.com (66.102.7.104) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.16.4 (i386-apple-darwin9.0) libcurl/7.16.4 OpenSSL/0.9.7l zlib/1.2.3
> Host: google.com
> Accept: */*
> 
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Thu, 15 Jul 2010 06:06:52 GMT
< Expires: Sat, 14 Aug 2010 06:06:52 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 219
< X-XSS-Protection: 1; mode=block
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
* Closing connection #0

Python Unicode Encode Error

Try adding the following line at the top of your python script.

# _*_ coding:utf-8 _*_

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Submitting a form on 'Enter' with jQuery?

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

open program minimized via command prompt

The answer is simple. Just look at the image.

enter image description here

Trim Whitespaces (New Line and Tab space) in a String in Oracle

How about the quick and dirty translate function?

This will remove all occurrences of each character in string1:

SELECT translate(
           translate(
               translate(string1, CHR(10), '')
           , CHR(13), '')
       , CHR(09), '') as massaged
FROM BLAH;

Regexp_replace is an option, but you may see a performance hit depending on how complex your expression is.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Instead of using window.open you can use a link with the onclick event.
And you can put the html table into the uri and set the file name to be downloaded.

Live demo :

_x000D_
_x000D_
function exportF(elem) {_x000D_
  var table = document.getElementById("table");_x000D_
  var html = table.outerHTML;_x000D_
  var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url _x000D_
  elem.setAttribute("href", url);_x000D_
  elem.setAttribute("download", "export.xls"); // Choose the file name_x000D_
  return false;_x000D_
}
_x000D_
<table id="table" border="1">_x000D_
  <tr>_x000D_
    <td>_x000D_
      Foo_x000D_
    </td>_x000D_
    <td>_x000D_
      Bar_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>
_x000D_
_x000D_
_x000D_

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

KeyListener, keyPressed versus keyTyped

keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.

I personally would use keyReleased for this. It will fire only when they lift their finger up.

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

How to select all instances of selected region in Sublime Text

On Mac:

?+CTRL+g

However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.


On Windows/Linux:

Alt+F3

If anyone has how-tos or articles on this, I'd be more than happy to update.

How to test a variable is null in python

try:
    if val is None: # The variable
        print('It is None')
except NameError:
    print ("This variable is not defined")
else:
    print ("It is defined and has a value")

How to create <input type=“text”/> dynamically

With JavaScript:

var input = document.createElement("input");
input.type = "text";
input.className = "css-class-name"; // set the CSS class
container.appendChild(input); // put it into the DOM

Centering a button vertically in table cell, using Twitter Bootstrap

add this to your css

.table-vcenter td {
   vertical-align: middle!important;
}

then add to the class to your table:

        <table class="table table-hover table-striped table-vcenter">

SQL Server : export query as a .txt file

You can use windows Powershell to execute a query and output it to a text file

Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt

Collision resolution in Java HashMap

There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.