Programs & Examples On #Multiprocessor

Debug JavaScript in Eclipse

I tried to get aptana running on my ubuntu 10.4. Unfortunately I didn't succeed. Chrome on the other hand, has an eclipse plugin that lets you debug javascript that's running in a chrome instance. Works very well. YOu'll have to install the eclipse plugin you'll find here:

http://code.google.com/p/chromedevtools/

Set Breakpoints in the javascript sources you edit in eclipse and browser your page in chrome. As soon as a javascript breakpoint is hit, the eclipse debugger halts and lets you step into, step over, browse the variables etc. Very nice!

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

Get exit code of a background process

As I see almost all answers use external utilities (mostly ps) to poll the state of the background process. There is a more unixesh solution, catching the SIGCHLD signal. In the signal handler it has to be checked which child process was stopped. It can be done by kill -0 <PID> built-in (universal) or checking the existence of /proc/<PID> directory (Linux specific) or using the jobs built-in ( specific. jobs -l also reports the pid. In this case the 3rd field of the output can be Stopped|Running|Done|Exit . ).

Here is my example.

The launched process is called loop.sh. It accepts -x or a number as an argument. For -x is exits with exit code 1. For a number it waits num*5 seconds. In every 5 seconds it prints its PID.

The launcher process is called launch.sh:

#!/bin/bash

handle_chld() {
    local tmp=()
    for((i=0;i<${#pids[@]};++i)); do
        if [ ! -d /proc/${pids[i]} ]; then
            wait ${pids[i]}
            echo "Stopped ${pids[i]}; exit code: $?"
        else tmp+=(${pids[i]})
        fi
    done
    pids=(${tmp[@]})
}

set -o monitor
trap "handle_chld" CHLD

# Start background processes
./loop.sh 3 &
pids+=($!)
./loop.sh 2 &
pids+=($!)
./loop.sh -x &
pids+=($!)

# Wait until all background processes are stopped
while [ ${#pids[@]} -gt 0 ]; do echo "WAITING FOR: ${pids[@]}"; sleep 2; done
echo STOPPED

For more explanation see: Starting a process from bash script failed

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

Test if a property is available on a dynamic variable

I thought I'd do a comparison of Martijn's answer and svick's answer...

The following program returns the following results:

Testing with exception: 2430985 ticks
Testing with reflection: 155570 ticks

void Main()
{
    var random = new Random(Environment.TickCount);

    dynamic test = new Test();

    var sw = new Stopwatch();

    sw.Start();

    for (int i = 0; i < 100000; i++)
    {
        TestWithException(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with exception: " + sw.ElapsedTicks.ToString() + " ticks");

    sw.Restart();

    for (int i = 0; i < 100000; i++)
    {
        TestWithReflection(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with reflection: " + sw.ElapsedTicks.ToString() + " ticks");
}

class Test
{
    public bool Exists { get { return true; } }
}

bool FlipCoin(Random random)
{
    return random.Next(2) == 0;
}

bool TestWithException(dynamic d, bool useExisting)
{
    try
    {
        bool result = useExisting ? d.Exists : d.DoesntExist;
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

bool TestWithReflection(dynamic d, bool useExisting)
{
    Type type = d.GetType();

    return type.GetProperties().Any(p => p.Name.Equals(useExisting ? "Exists" : "DoesntExist"));
}

As a result I'd suggest using reflection. See below.


Responding to bland's comment:

Ratios are reflection:exception ticks for 100000 iterations:

Fails 1/1: - 1:43 ticks
Fails 1/2: - 1:22 ticks
Fails 1/3: - 1:14 ticks
Fails 1/5: - 1:9 ticks
Fails 1/7: - 1:7 ticks
Fails 1/13: - 1:4 ticks
Fails 1/17: - 1:3 ticks
Fails 1/23: - 1:2 ticks
...
Fails 1/43: - 1:2 ticks
Fails 1/47: - 1:1 ticks

...fair enough - if you expect it to fail with a probability with less than ~1/47, then go for exception.


The above assumes that you're running GetProperties() each time. You may be able to speed up the process by caching the result of GetProperties() for each type in a dictionary or similar. This may help if you're checking against the same set of types over and again.

Add centered text to the middle of a <hr/>-like line

<div style="text-align: center; border-top: 1px solid black">
  <div style="display: inline-block; position: relative; top: -10px; background-color: white; padding: 0px 10px">text</div>
</div>

C++11 rvalues and move semantics confusion (return statement)

None of those will do any extra copying. Even if RVO isn't used, the new standard says that move construction is preferred to copy when doing returns I believe.

I do believe that your second example causes undefined behavior though because you're returning a reference to a local variable.

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

sudo -u postgres createuser -s tom 

this should help you as this will happen if the administrator has not created a PostgreSQL user account for you. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name, in that case you need to use the -U switch.

Use async await with Array.map

The problem here is that you are trying to await an array of promises rather than a promise. This doesn't do what you expect.

When the object passed to await is not a Promise, await simply returns the value as-is immediately instead of trying to resolve it. So since you passed await an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type Promise<number>[].

What you need to do here is call Promise.all on the array returned by map in order to convert it to a single Promise before awaiting it.

According to the MDN docs for Promise.all:

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.

So in your case:

var arr = [1, 2, 3, 4, 5];

var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
    await callAsynchronousOperation(item);
    return item + 1;
}));

This will resolve the specific error you are encountering here.

Get last 5 characters in a string

in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)

Dim str as String = "Hello World"

Msgbox(Microsoft.VisualBasic.Right(str,5))

'World"

Same goes for Left() too.

Interpreting "condition has length > 1" warning from `if` function

if statement is not vectorized. For vectorized if statements you should use ifelse. In your case it is sufficient to write

w <- function(a){
if (any(a>0)){
  a/sum(a)
}
  else 1
}

or a short vectorised version

ifelse(a > 0, a/sum(a), 1)

It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse gives output vector of length equal to length of a.

How to parse date string to Date?

Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result); 
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

Function pointer to member function

Call member function on string command

#include <iostream>
#include <string>


class A 
{
public: 
    void call();
private:
    void printH();
    void command(std::string a, std::string b, void (A::*func)());
};

void A::printH()
{
    std::cout<< "H\n";
}

void A::call()
{
    command("a","a", &A::printH);
}

void A::command(std::string a, std::string b, void (A::*func)())
{
    if(a == b)
    {
        (this->*func)();
    }
}

int main()
{
    A a;
    a.call();
    return 0;
}

Pay attention to (this->*func)(); and the way to declare the function pointer with class name void (A::*func)()

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

If you want to make sure that the library is loaded if and only if the program lunar-calendar-gtk is launched, you can apply this:

You set the environment variable per command by prefixing the command with it:

$ LD_PRELOAD="liblunar-calendar-preload.so" printenv "LD_PRELOAD"
liblunar-calendar-preload.so
$ printenv "LD_PRELOAD"
$

You can then choose to put this in a shell script and make lunar-calendar-gtk a symlink to this shell script, replaceing the original referencee. This effectively makes sure that the library is loaded everytime the original application is executed.

You will have to rename the original lunar-calendar-gtk to something else, which might not be too intriguing as it possibly may cause issues with uninstallation and upgrading. However, I found it useful with a former version of Skype.

Android 'Unable to add window -- token null is not for an application' exception

Try getParent() at the argument place of context like new AlertDialog.Builder(getParent()); Hope it will work, it worked for me.

Better/Faster to Loop through set or list?

Just use a set. Its semantics are exactly what you want: a collection of unique items.

Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.

pandas convert some columns into rows

Use set_index with stack for MultiIndex Series, then for DataFrame add reset_index with rename:

df1 = (df.set_index(["location", "name"])
         .stack()
         .reset_index(name='Value')
         .rename(columns={'level_2':'Date'}))
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25

matplotlib does not show my drawings although I call pyplot.show()

I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using

pip install matplotlib

To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you.

Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with. Even worse, it fails silently; that is, pip install matplotlib appears to install matplotlib successfully. But when you try to use it (e.g. pyplot.show()), no plot window will appear. I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get ImportError because it's trying to import some dependency that's missing). I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies.

The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib. That worked perfectly. Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version...

subquery in codeigniter active record

It may be a little late for the original question but for future queries this might help. Best way to achieve this is Get the result of the inner query to an array like this

$this->db->select('id');
$result = $this->db->get('your_table');
return  $result->result_array();

And then use than array in the following active record clause

$this->db->where_not_in('id_of_another_table', 'previously_returned_array');

Hope this helps

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

When adding a Javascript library, Chrome complains about a missing source map, why?

This worked for me

Deactivate AdBlock.

Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.

Refresh.

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

Escape regex special characters in a Python string

If you only want to replace some characters you could use this:

import re

print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

in mvc 5

              @Html.EditorFor(x => x.Address, 
              new {htmlAttributes = new {@class = "form-control", 
                   @placeholder = "Complete Address", @cols = 10, @rows = 10 } })

How do I show the value of a #define at compile-time?

Without boost :

  1. define same macro again and compiler HIMSELF will give warning.

  2. From warning you can see location of the previous definition.

  3. vi file of previous definition .

ambarish@axiom:~/cpp$ g++ shiftOper.cpp
shiftOper.cpp:7:1: warning: "LINUX_VERSION_CODE" redefined
shiftOper.cpp:6:1: warning: this is the location of the previous definition

#define LINUX_VERSION_CODE 265216
#define LINUX_VERSION_CODE 666

int main ()
{

}

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.

cin and getline skipping input

The structure of your menu code is the issue:

cin >> choice;   // new line character is left in the stream

 switch ( ... ) {
     // We enter the handlers, '\n' still in the stream
 }

cin.ignore();   // Put this right after cin >> choice, before you go on
                // getting input with getline.

how do I join two lists using linq or lambda expressions

It sounds like you want something like:

var query = from order in workOrders
            join plan in plans
                 on order.WorkOrderNumber equals plan.WorkOrderNumber
            select new
            {
                order.WorkOrderNumber,
                order.Description,
                plan.ScheduledDate
            };

Remove menubar from Electron app

The menu can be hidden or auto-hidden (like in Slack or VS Code - you can press Alt to show/hide the menu).

Relevant methods:

---- win.setMenu(menu) - Sets the menu as the window’s menu bar, setting it to null will remove the menu bar. (This will remove the menu completly)

mainWindow.setMenu(null)


---- win.setAutoHideMenuBar(hide) - Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only
show
when users press the single Alt key.

mainWindow.setAutoHideMenuBar(true)

Source: https://github.com/Automattic/simplenote-electron/issues/293

There is also the method for making a frameless window as shown bellow:

(no close button no anything. Can be what we want (better design))

const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ width: 800, height: 600, frame: false })
win.show()

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

doc: https://electronjs.org/docs/api/frameless-window

Edit: (new)

win.removeMenu() Linux Windows Remove the window's menu bar.

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

Added win.removeMenu() to remove application menus instead of using win.setMenu(null)

That is added from v5 as per:

https://github.com/electron/electron/pull/16570

https://github.com/electron/electron/pull/16657

Electron v7 bug

For Electron 7.1.1 use Menu.setApplicationMenu instead of win.removeMenu()

as per this thread:
https://github.com/electron/electron/issues/16521

And the big note is: you have to call it before creating the BrowserWindow! Or it will not work!

const {app, BrowserWindow, Menu} = require('electron')

Menu.setApplicationMenu(null);

const browserWindow = new BrowserWindow({/*...*/});

UPDATE (Setting autoHideMenuBar on BrowserWindow construction)

As by @kcpr comment! We can set the property and many on the constructor

That's available on the latest stable version of electron by now which is 8.3!
But too in old versions i checked for v1, v2, v3, v4!
It's there in all versions!

As per this link
https://github.com/electron/electron/blob/1-3-x/docs/api/browser-window.md

And for the v8.3
https://github.com/electron/electron/blob/v8.3.0/docs/api/browser-window.md#new-browserwindowoptions

The doc link
https://www.electronjs.org/docs/api/browser-window#new-browserwindowoptions

From the doc for the option:

autoHideMenuBar Boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. Default is false.

Here a snippet to illustrate it:


let browserWindow = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true // <<< here
})

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

How to force link from iframe to be opened in the parent window

<a target="parent"> will open links in a new tab/window ... <a target="_parent"> will open links in the parent/current window, without opening new tabs/windows. Don't_forget_that_underscore!

How to disable Home and other system buttons in Android?

I followed the shaobin0604's answer and I finally managed to lock the HOME button, by adding:

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

to AndroidManifest.xml All you have to do is to copy HomeKeyLocker.java from shaobin's lib to your project and implement it like in shaobin's example. BTW: My AVD's Android version is Android 4.0.3.

string.split - by multiple character delimiter

Regex.Split("abc][rfd][5][,][.", @"\]\]");

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Some "real world" examples for static variables:

building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.

public static class Enemies
{
    public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}

The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.

public sealed class TextureManager
    {
        private TextureManager() {}
        public string LoadTexture(string aPath);

        private static TextureManager sInstance = new TextureManager();

        public static TextureManager Instance
        {
            get { return sInstance; }
        }
    }

and this is how you would call the texturemanager

TextureManager.Instance.LoadTexture("myImage.png");

About your last question: You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

How to force NSLocalizedString to use a specific language

The trick to use specific language by selecting it from the app is to force the NSLocalizedString to use specific bundle depending on the selected language ,

here is the post i have written for this learning advance localization in ios apps

and here is the code of one sample app advance localization in ios apps

Extract Number from String in Python

To extract a single number from a string you can use re.search(), which returns the first match (or None):

>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158

In Python 3.6+ you can also index into a match object instead of using group():

>>> int(re.search(r'\d+', string)[0])
3158

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

default value for struct member in C

Even more so, to add on the existing answers, you may use a macro that hides a struct initializer:

#define DEFAULT_EMPLOYEE { 0, "none" }

Then in your code:

employee john = DEFAULT_EMPLOYEE;

How to check string length with JavaScript

That's the function I wrote to get string in Unicode characters:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}

Reliable method to get machine's MAC address in C#

WMI is the best solution if the machine you are connecting to is a windows machine, but if you are looking at a linux, mac, or other type of network adapter, then you will need to use something else. Here are some options:

  1. Use the DOS command nbtstat -a . Create a process, call this command, parse the output.
  2. First Ping the IP to make sure your NIC caches the command in it's ARP table, then use the DOS command arp -a . Parse the output of the process like in option 1.
  3. Use a dreaded unmanaged call to sendarp in the iphlpapi.dll

Heres a sample of item #3. This seems to be the best option if WMI isn't a viable solution:

using System.Runtime.InteropServices;
...
[DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
...
private string GetMacUsingARP(string IPAddr)
{
    IPAddress IP = IPAddress.Parse(IPAddr);
    byte[] macAddr = new byte[6];
    uint macAddrLen = (uint)macAddr.Length;

    if (SendARP((int)IP.Address, 0, macAddr, ref macAddrLen) != 0)
        throw new Exception("ARP command failed");

    string[] str = new string[(int)macAddrLen];
    for (int i = 0; i < macAddrLen; i++)
        str[i] = macAddr[i].ToString("x2");

    return string.Join(":", str);
}

To give credit where it is due, this is the basis for that code: http://www.pinvoke.net/default.aspx/iphlpapi.sendarp#

How do I negate a test with regular expressions in a bash script?

I like to simplify the code without using conditional operators in such cases:

TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

Google Maps V3 - How to calculate the zoom level for a given bounds

For swift version

func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapDim: CGSize) -> Double {
        var bounds = bounds
        let WORLD_DIM = CGSize(width: 256, height: 256)
        let ZOOM_MAX: Double = 21.0
        func latRad(_ lat: Double) -> Double {
            let sin2 = sin(lat * .pi / 180)
            let radX2 = log10((1 + sin2) / (1 - sin2)) / 2
            return max(min(radX2, .pi), -.pi) / 2
        }
        func zoom(_ mapPx: CGFloat,_ worldPx: CGFloat,_ fraction: Double) -> Double {
            return floor(log10(Double(mapPx) / Double(worldPx) / fraction / log10(2.0)))
        }
        let ne = bounds.northEast
        let sw = bounds.southWest
        let latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / .pi
        let lngDiff = ne.longitude - sw.longitude
        let lngFraction = lngDiff < 0 ? (lngDiff + 360) : (lngDiff / 360)
        let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
        return min(latZoom, lngZoom, ZOOM_MAX)
    }

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

Just add this lines to your codes :

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

How do I POST urlencoded form data with $http without jQuery?

From the $http docs this should work..

  $http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
    .success(function(response) {
         // your code...
     });

moving changed files to another branch for check-in

Sadly this happens to me quite regularly as well and I use git stash if I realized my mistake before git commit and use git cherry-pick otherwise, both commands are explained pretty well in other answers

I want to add a clarification for git checkout targetBranch: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally

@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch

However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch (clean and throwaway changes) or git stage + git checkout targetBranch (clean and save changes), simply running git checkout targetBranch will give an error:

error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting

How can I format a decimal to always show 2 decimal places?

You should use the new format specifications to define how your value should be represented:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:

Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:

>>> f'{pi:.2f}'
'3.14'

How can I copy a conditional formatting from one document to another?

To achieve this you can try below steps:

  1. Copy the cell or column which has the conditional formatting you want to copy.
  2. Go to the desired cell or column (maybe other sheets) where you want to apply conditional formatting.
  3. Open the context menu of the desired cell or column (by right-click on it).
  4. Find the "Paste Special" option which has a sub-menu.
  5. Select the "Paste conditional formatting only" option of the sub-menu and done.

7-zip commandline

I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.

If that requirement is not met using command line utilities is rather tedious.

7z -a .

would be

d:\portable\z7\z7 -a c:\to\archive\folder*.*

Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.

If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.

You'll have to set your path when you hit the shell after making sure it's attached.

http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.

http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor

It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:

set path=%path%;"d:\portable\z7\";

when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/

The other answers address other problems better I'm not going to try..

http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.

PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

Overlapping elements in CSS

Use CSS grid and set all the grid items to be in the same cell.

.layered {
  display: grid;
}

.layered > * {
  grid-column-start: 1;
  grid-row-start: 1;
}

Adding the layered class to an element causes all it's children to be layered on top of each other.

if the layers are not the same size you can set the justify-items and align-items properties to set the horizontal and vertical alignment respectively.


Demo:

JsFiddle

_x000D_
_x000D_
.layered {
  display: grid;

  /* Set horizontal alignment of items in, case they have a different width. */
  /* justify-items: start | end | center | stretch (default); */
  justify-items: start;

  /* Set vertical alignment of items, in case they have a different height. */
  /* align-items: start | end | center | stretch (default); */
  align-items: start;
}

.layered > * {
  grid-column-start: 1;
  grid-row-start: 1;
}


/* for demonstration purposes only */
.layered > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}
_x000D_
<div class="layered">
  <img src="https://via.placeholder.com/250x100?text=first" />
  <p>
    2
  </p>
  <div>
    <p>
      Third layer
    </p>
    <p>
      Third layer continued
    </p>
    <p>
      Third layer continued
    </p>
    <p>
      Third layer continued
    </p>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to listen for a WebView finishing loading a URL?

Just to show progress bar, "onPageStarted" and "onPageFinished" methods are enough; but if you want to have an "is_loading" flag (along with page redirects, ...), this methods may executed with non-sequencing, like "onPageStarted > onPageStarted > onPageFinished > onPageFinished" queue.

But with my short test (test it yourself.), "onProgressChanged" method values queue is "0-100 > 0-100 > 0-100 > ..."

private boolean is_loading = false;

webView.setWebChromeClient(new MyWebChromeClient(context));

private final class MyWebChromeClient extends WebChromeClient{
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress == 0){
            is_loading = true;
        } else if (newProgress == 100){
            is_loading = false;
        }
        super.onProgressChanged(view, newProgress);
    }
}

Also set "is_loading = false" on activity close, if it is a static variable because activity can be finished before page finish.

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
  [myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value')
     ,  ret   = {};

     ret[key] = value;
     return ret;
  }) 

  callback(null, inputs);
}

How to insert a string which contains an "&"

In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser.

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

Java - Check if input is a positive integer, negative integer, natural number and so on.

You could use if(number >= 0). The fact that you use int number = input.nextInt(); makes sure that it has to be an Integer.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

Is there anyway to exclude artifacts inherited from a parent POM?

I really needed to do this dirty thing... Here is how

I redefined those dependencies with scope test. Scope provided did not work for me.

We use spring Boot plugin to build fat jar. We have module common which defines common libraries, for example Springfox swagger-2. My super-service needs to have parent common (it does not want to do so, but company rules force!)

So my parent or commons has pom.

<dependencyManagement>

    <!- I do not need Springfox in one child but in others ->

    <dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-bean-validators</artifactId>
            <version>${swagger.version}</version>
        </dependency>

       <!- All services need them ->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${apache.poi.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

And my super-service pom.

<name>super-service</name>
<parent>
    <groupId>com.company</groupId>
    <artifactId>common</artifactId>
    <version>1</version>
</parent>

<dependencies>

    <!- I don't need them ->

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-core</artifactId>
        <version>2.8.0</version>
        <scope>test</scope>
    </dependency>

    <!- Required dependencies ->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
    </dependency>
</dependencies>

This is size of the final fat artifact

82.3 MB (86,351,753 bytes) - redefined dependency with scope test
86.1 MB (90,335,466 bytes) - redefined dependency with scope provided
86.1 MB (90,335,489 bytes) - without exclusion

Also this answer is worth mentioning - I wanted to do so, but I am lazy... https://stackoverflow.com/a/48103554/4587961

Edit line thickness of CSS 'underline' attribute

Another way to do this is using ":after" (pseudo-element) on the element you want to underline.

h2{
  position:relative;
  display:inline-block;
  font-weight:700;
  font-family:arial,sans-serif;
  text-transform:uppercase;
  font-size:3em;
}
h2:after{
  content:"";
  position:absolute;
  left:0;
  bottom:0;
  right:0;
  margin:auto;
  background:#000;
  height:1px;

}

How do I look inside a Python object?

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

Getting the text that follows after the regex match

You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:

System.out.println("I found the text: " + matcher.group(**1**).toString());

Python : List of dict, if exists increment a dict value, if not append a new dict

Using the default works, but so does:

urls[url] = urls.get(url, 0) + 1

using .get, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.

Add space between cells (td) using css

Suppose cellspcing / cellpadding / border-spacing property did not worked, you can use the code as follow.

<div class="form-group">
  <table width="100%" cellspacing="2px" style="border-spacing: 10px;">
    <tr>                        
      <td width="47%">
        <input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
      </td>
      <td width="5%"></td>
      <td width="47%">
        <input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
      </td>
    </tr>
  </table>
</div>

I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.

How do I generate a SALT in Java for Salted-Hash?

Another version using SHA-3, I am using bouncycastle:

The interface:

public interface IPasswords {

    /**
     * Generates a random salt.
     *
     * @return a byte array with a 64 byte length salt.
     */
    byte[] getSalt64();

    /**
     * Generates a random salt
     *
     * @return a byte array with a 32 byte length salt.
     */
    byte[] getSalt32();

    /**
     * Generates a new salt, minimum must be 32 bytes long, 64 bytes even better.
     *
     * @param size the size of the salt
     * @return a random salt.
     */
    byte[] getSalt(final int size);

    /**
     * Generates a new hashed password
     *
     * @param password to be hashed
     * @param salt the randomly generated salt
     * @return a hashed password
     */
    byte[] hash(final String password, final byte[] salt);

    /**
     * Expected password
     *
     * @param password to be verified
     * @param salt the generated salt (coming from database)
     * @param hash the generated hash (coming from database)
     * @return true if password matches, false otherwise
     */
    boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash);

    /**
     * Generates a random password
     *
     * @param length desired password length
     * @return a random password
     */
    String generateRandomPassword(final int length);
}

The implementation:

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bouncycastle.jcajce.provider.digest.SHA3;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public final class Passwords implements IPasswords, Serializable {

    /*serialVersionUID*/
    private static final long serialVersionUID = 8036397974428641579L;
    private static final Logger LOGGER = Logger.getLogger(Passwords.class);
    private static final Random RANDOM = new SecureRandom();
    private static final int DEFAULT_SIZE = 64;
    private static final char[] symbols;

    static {
            final StringBuilder tmp = new StringBuilder();
            for (char ch = '0'; ch <= '9'; ++ch) {
                    tmp.append(ch);
            }
            for (char ch = 'a'; ch <= 'z'; ++ch) {
                    tmp.append(ch);
            }
            symbols = tmp.toString().toCharArray();
    }

    @Override public byte[] getSalt64() {
            return getSalt(DEFAULT_SIZE);
    }

    @Override public byte[] getSalt32() {
            return getSalt(32);
    }

    @Override public byte[] getSalt(int size) {
            final byte[] salt;
            if (size < 32) {
                    final String message = String.format("Size < 32, using default of: %d", DEFAULT_SIZE);
                    LOGGER.warn(message);
                    salt = new byte[DEFAULT_SIZE];
            } else {
                    salt = new byte[size];
            }
            RANDOM.nextBytes(salt);
            return salt;
    }

    @Override public byte[] hash(String password, byte[] salt) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    return md.digest();
            } catch (UnsupportedEncodingException e) {
                    final String message = String
                            .format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return new byte[0];
    }

    @Override public boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");
            Validate.notNull(hash, "Hash must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);

                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    final byte[] digest = md.digest();
                    return Arrays.equals(digest, hash);
            }catch(UnsupportedEncodingException e){
                    final String message =
                            String.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return false;


    }

    @Override public String generateRandomPassword(final int length) {

            if (length < 1) {
                    throw new IllegalArgumentException("length must be greater than 0");
            }

            final char[] buf = new char[length];
            for (int idx = 0; idx < buf.length; ++idx) {
                    buf[idx] = symbols[RANDOM.nextInt(symbols.length)];
            }
            return shuffle(new String(buf));
    }


    private String shuffle(final String input){
            final List<Character> characters = new ArrayList<Character>();
            for(char c:input.toCharArray()){
                    characters.add(c);
            }
            final StringBuilder output = new StringBuilder(input.length());
            while(characters.size()!=0){
                    int randPicker = (int)(Math.random()*characters.size());
                    output.append(characters.remove(randPicker));
            }
            return output.toString();
    }
}

The test cases:

public class PasswordsTest {

    private static final Logger LOGGER = Logger.getLogger(PasswordsTest.class);

    @Before
    public void setup(){
            BasicConfigurator.configure();
    }

    @Test
    public void testGeSalt() throws Exception {

            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt(0);
            int arrayLength = bytes.length;

            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testGeSalt32() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt32();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(32));
    }

    @Test
    public void testGeSalt64() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt64();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testHash() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] hash = passwords.hash("holacomoestas", passwords.getSalt64());
            assertThat("Array is not null", hash, Matchers.notNullValue());
    }


    @Test
    public void testSHA3() throws UnsupportedEncodingException {
            SHA3.DigestSHA3 md = new SHA3.Digest256();
            md.update("holasa".getBytes("UTF-8"));
            final byte[] digest = md.digest();
             assertThat("expected digest is:",digest,Matchers.notNullValue());
    }

    @Test
    public void testIsExpectedPasswordIncorrect() throws Exception {

            String password = "givemebeer";
            IPasswords passwords = new Passwords();

            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.

            final boolean isPasswordCorrect = passwords.isExpectedPassword("jfjdsjfsd", salt64, hash);

            assertThat("Password is not correct", isPasswordCorrect, is(false));

    }

    @Test
    public void testIsExpectedPasswordCorrect() throws Exception {
            String password = "givemebeer";
            IPasswords passwords = new Passwords();
            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.
            final boolean isPasswordCorrect = passwords.isExpectedPassword("givemebeer", salt64, hash);
            assertThat("Password is correct", isPasswordCorrect, is(true));
    }

    @Test
    public void testGenerateRandomPassword() throws Exception {
            IPasswords passwords = new Passwords();
            final String randomPassword = passwords.generateRandomPassword(10);
            LOGGER.info(randomPassword);
            assertThat("Random password is not null", randomPassword, Matchers.notNullValue());
    }
}

pom.xml (only dependencies):

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.1.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.51</version>
        <type>jar</type>
    </dependency>


    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>


</dependencies>

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

i solved this problem by changing jre required for server (in my case is tomcat). From Server tab in eclipse, double click on the server (in order to open page for server configuration), click on Runtime environment, then change JRE required

Getting JavaScript object key list

Use Object.keys()... it's the way to go.

Full documentation is available on the MDN site linked below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Is it possible to have different Git configuration for different projects?

Follow the Steps:

  1. Find .gitconfig from the system

    File Location For Windows : "C:\Users${USER_NAME}.gitconfig"

    File Location For Linux : "/usr/local/git/etc/gitconfig"

  2. Open .gitconfig file and add below lines as per your condition

     [includeIf "gitdir:D:\ORG-A-PROJECTS\"]
    
     [user]
    
         name = John Smith
    
         email = [email protected] [includeIf "gitdir:~/organization_b/"]
    
     [user]
    
         name = John Doe
    
         email = [email protected]
    

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

How to implement a SQL like 'LIKE' operator in java?

This's my take on this, it's in Kotlin but can be converted to Java with little effort:

val percentageRegex = Regex("""(?<!\\)%""")
val underscoreRegex = Regex("""(?<!\\)_""")

infix fun String.like(predicate: String): Boolean {

    //Split the text by every % not preceded by a slash.
    //We transform each slice before joining them with .* as a separator.
    return predicate.split(percentageRegex).joinToString(".*") { percentageSlice ->

        //Split the text by every _ not preceded by a slash.
        //We transform each slice before joining them with . as a separator.
        percentageSlice.split(underscoreRegex).joinToString(".") { underscoreSlice ->

            //Each slice is wrapped in "Regex quotes" to ignore all
            // the metacharacters they contain.
            //We also remove the slashes from the escape sequences
            // since they are now treated literally.
            Pattern.quote(
                underscoreSlice.replace("\\_", "_").replace("\\%", "%")
            )
        }

    }.let { "^$it$" }.toRegex().matches(this@like)
}

It might not be the most performant of all the solutions here, but it's probably the most accurate.

It ignores all the other Regex metacharacters other than % and _ and also supports escaping them with a slash.

How do you get an iPhone's device name

To get an iPhone's device name programmatically

 UIDevice *deviceInfo = [UIDevice currentDevice];

 NSLog(@"Device name:  %@", deviceInfo.name); 

// Device name: my iPod

Wait until page is loaded with Selenium WebDriver for Python

On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)

def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True

align images side by side in html

In your CSS:

.image123{
float:left;
}

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

How do you get the file size in C#?

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

Disable sorting on last column when using jQuery DataTables

This has resolved my issue, just added data-orderable="false" in <th></th> like this <th data-orderable="false">Salary</th>

How do I run a batch script from within a batch script?

huh, I don't know why, but call didn't do the trick
call script.bat didn't return to the original console.
cmd /k script.bat did return to the original console.

FFT in a single C-file

You could start converting this java snippet to C the author states he has converted it from C based on the book numerical recipies which you find online! here

How to sort List<Integer>?

Just use Collections.sort(yourListHere) here to sort.

You can read more about Collections from here.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

Downgrading the iOS development Target from 12.1 to 12 fix the issue for me as I don't have a dev team configured.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

Split a string into an array of strings based on a delimiter

You can use StrUtils.SplitString.

function SplitString(const S, Delimiters: string): TStringDynArray;

Its description from the documentation:

Splits a string into different parts delimited by the specified delimiter characters.

SplitString splits a string into different parts delimited by the specified delimiter characters. S is the string to be split. Delimiters is a string containing the characters defined as delimiters.

SplitString returns an array of strings of type System.Types.TStringDynArray that contains the split parts of the original string.

Convert Base64 string to an image file?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

How to download a folder from github?

How to download a specific folder from a GitHub repo

Here a proper solution according to this post:

  • Create a directory

     mkdir github-project-name 
     cd github-project-name
    
  • Set up a git repo

     git init
     git remote add origin <URL-link of the repo>
    
  • Configure your git-repo to download only specific directories

     git config core.sparseCheckout true # enable this
    
  • Set the folder you like to be downloaded, e.g. you only want to download the doc directory from https://github.com/project-tree/master/doc

     echo "/absolute/path/to/folder" > .git/info/sparse-checkout 
    

    E.g. if you only want to download the doc directory from your master repo https://github.com/project-tree/master/doc, then your command is echo "doc" > .git/info/sparse-checkout.

  • Download your repo as usual

     git pull origin master
    

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

ffmpeg logs to stderr, and can log to a file with a different log-level from stderr. The -report command-line option doesn't give you control of the log file name or the log level, so setting the environment variable is preferable.

(-v is a synonym for -loglevel. Run ffmpeg -v help to see the levels. Run ffmpeg -h full | less to see EVERYTHING. Or consult the online docs, or their wiki pages like the h.264 encode guide).

#!/bin/bash

of=out.mkv
FFREPORT="level=32:file=$of.log" ffmpeg -v verbose   -i src.mp4 -c:a copy -preset slower -c:v libx264 -crf 21 "$of"

That will trancode src.mp4 with x264, and set the log level for stderr to "verbose", and the log level for out.mkv.log to "status".

(AV_LOG_WARNING=24, AV_LOG_INFO=32, AV_LOG_VERBOSE=40, etc.). Support for this was added 2 years ago, so you need a non-ancient version of ffmpeg. (Always a good idea anyway, for security / bugfixes and speedups)


A few codecs, like -c:v libx265, write directly to stderr instead of using ffmpeg's logging infrastructure. So their log messages don't end up in the report file. I assume this is a bug / TODO-list item.

To log stderr, while still seeing it in a terminal, you can use tee(1).


If you use a log level that includes status line updates (the default -v info, or higher), they will be included in the log file, separated with ^M (carriage return aka \r). There's no log level that includes encoder stats (like SSIM) but not status-line updates, so the best option is probably to filter that stream.

If don't want to filter (e.g. so the fps / bitrate at each status-update interval is there in the file), you can use less -r to pass them through directly to your terminal so you can view the files cleanly. If you have .enc logs from several encodes that you want to flip through, less -r ++G *.enc works great. (++G means start at the end of the file, for all files). With single-key key bindings like . and , for next file and previous file, you can flip through some log files very nicely. (the default bindings are :n and :p).

If you do want to filter, sed 's/.*\r//' works perfectly for ffmpeg output. (In the general case, you need something like vt100.py, but not for just carriage returns). There are (at least) two ways to do this with tee + sed: tee to /dev/tty and pipe tee's output into sed, or use a process substitution to tee into a pipe to sed.

# pass stdout and stderr through to the terminal, 
## and log a filtered version to a file (with only the last status-line update).

of="$1-x265.mkv"
ffmpeg -v info -i "$1" -c:a copy -c:v libx265 ... "$of" |&    # pipe stdout and stderr
   tee /dev/tty | sed 's/.*\r//' >> "$of.enc"

## or with process substitution where tee's arg will be something like /dev/fd/123

ffmpeg -v info -i "$1" -c:a copy -c:v libx265 ... "$of" |&
  tee >(sed 's/.*\r//' >> "$of.enc")

For testing a few different encode parameters, you can make a function like this one that I used recently to test some stuff. I had it all on one line so I could easily up-arrow and edit it, but I'll un-obfuscate it here. (That's why there are ;s at the end of each line)

ffenc-testclip(){
  # v should be set by the caller, to a vertical resolution.  We scale to WxH, where W is a multiple of 8 (-vf scale=-8:$v)
  db=0;   # convenient to use shell vars to encode settings that you want to include in the filename and the ffmpeg cmdline
  [email protected].${v}p.x265$pre.mkv; 
  [[ -e "$of.enc" ]]&&echo "$of.enc exists"&&return;   # early-out if the file exists

  # encode 25 seconds starting at 21m15s (or the keyframe before that)
  nice -14 ffmpeg -ss $((21*60+15))  -i src.mp4 -t 25  -map 0 -metadata title= -color_primaries bt709 -color_trc bt709 -colorspace bt709 -sws_flags lanczos+print_info -c:a copy -c:v libx265 -b:v 1500k -vf scale=-8:$v  -preset $pre -ssim 1 -x265-params ssim=1:cu-stats=1:deblock=$db:aq-mode=1:lookahead-slices=0 "$of" |&
   tee /dev/tty | sed 's/.*\r//' >> "$of.enc";
}

# and use it with nested loops like this.
for pre in fast slow;  do for v in  360 480 648 792;do  ffenc-testclip ;done;done

less -r ++G *.enc       # -r is useful if you didn't use sed

Note that it tests for existence of the output video file to avoid spewing extra garbage into the log file if it already exists. Even so, I used and append (>>) redirect.

It would be "cleaner" to write a shell function that took args instead of looking at shell variables, but this was convenient and easy to write for my own use. That's also why I saved space by not properly quoting all my variable expansions. ($v instead of "$v")

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

Why do python lists have pop() but not push()

Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.

Think of a queue vs. a stack.

http://docs.python.org/tutorial/datastructures.html

Edit: To reword my second sentence more exactly, "Appending" very clearly implies adding something to the end of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.

Get selected option from select element

This worked for me:

$("#SelectedCountryId_option_selected")[0].textContent

Check if a record exists in the database

sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM  tblAttendance",con);
sda.Fill(dt);

string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);

if (bar >= 1){

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "empty");
}

Vue.js toggle class on click

If you don't need to access the toggle from outside the element, this code works without a data variable:

<a @click="e => e.target.classList.toggle('active')"></a>

Why is processing a sorted array faster than processing an unsorted array?

I just read up on this question and its answers, and I feel an answer is missing.

A common way to eliminate branch prediction that I've found to work particularly good in managed languages is a table lookup instead of using a branch (although I haven't tested it in this case).

This approach works in general if:

  1. it's a small table and is likely to be cached in the processor, and
  2. you are running things in a quite tight loop and/or the processor can preload the data.

Background and why

From a processor perspective, your memory is slow. To compensate for the difference in speed, a couple of caches are built into your processor (L1/L2 cache). So imagine that you're doing your nice calculations and figure out that you need a piece of memory. The processor will get its 'load' operation and loads the piece of memory into cache -- and then uses the cache to do the rest of the calculations. Because memory is relatively slow, this 'load' will slow down your program.

Like branch prediction, this was optimized in the Pentium processors: the processor predicts that it needs to load a piece of data and attempts to load that into the cache before the operation actually hits the cache. As we've already seen, branch prediction sometimes goes horribly wrong -- in the worst case scenario you need to go back and actually wait for a memory load, which will take forever (in other words: failing branch prediction is bad, a memory load after a branch prediction fail is just horrible!).

Fortunately for us, if the memory access pattern is predictable, the processor will load it in its fast cache and all is well.

The first thing we need to know is what is small? While smaller is generally better, a rule of thumb is to stick to lookup tables that are <= 4096 bytes in size. As an upper limit: if your lookup table is larger than 64K it's probably worth reconsidering.

Constructing a table

So we've figured out that we can create a small table. Next thing to do is get a lookup function in place. Lookup functions are usually small functions that use a couple of basic integer operations (and, or, xor, shift, add, remove and perhaps multiply). You want to have your input translated by the lookup function to some kind of 'unique key' in your table, which then simply gives you the answer of all the work you wanted it to do.

In this case: >= 128 means we can keep the value, < 128 means we get rid of it. The easiest way to do that is by using an 'AND': if we keep it, we AND it with 7FFFFFFF; if we want to get rid of it, we AND it with 0. Notice also that 128 is a power of 2 -- so we can go ahead and make a table of 32768/128 integers and fill it with one zero and a lot of 7FFFFFFFF's.

Managed languages

You might wonder why this works well in managed languages. After all, managed languages check the boundaries of the arrays with a branch to ensure you don't mess up...

Well, not exactly... :-)

There has been quite some work on eliminating this branch for managed languages. For example:

for (int i = 0; i < array.Length; ++i)
{
   // Use array[i]
}

In this case, it's obvious to the compiler that the boundary condition will never be hit. At least the Microsoft JIT compiler (but I expect Java does similar things) will notice this and remove the check altogether. WOW, that means no branch. Similarly, it will deal with other obvious cases.

If you run into trouble with lookups in managed languages -- the key is to add a & 0x[something]FFF to your lookup function to make the boundary check predictable -- and watch it going faster.

The result of this case

// Generate data
int arraySize = 32768;
int[] data = new int[arraySize];

Random random = new Random(0);
for (int c = 0; c < arraySize; ++c)
{
    data[c] = random.Next(256);
}

/*To keep the spirit of the code intact, I'll make a separate lookup table
(I assume we cannot modify 'data' or the number of loops)*/

int[] lookup = new int[256];

for (int c = 0; c < 256; ++c)
{
    lookup[c] = (c >= 128) ? c : 0;
}

// Test
DateTime startTime = System.DateTime.Now;
long sum = 0;

for (int i = 0; i < 100000; ++i)
{
    // Primary loop
    for (int j = 0; j < arraySize; ++j)
    {
        /* Here you basically want to use simple operations - so no
        random branches, but things like &, |, *, -, +, etc. are fine. */
        sum += lookup[data[j]];
    }
}

DateTime endTime = System.DateTime.Now;
Console.WriteLine(endTime - startTime);
Console.WriteLine("sum = " + sum);
Console.ReadLine();

How to remove a branch locally?

Force Delete a Local Branch:

$ git branch -D <branch-name>

[NOTE]:

-D is a shortcut for --delete --force.


Add inline style using Javascript

var div = document.createElement('div');
div.setAttribute('style', 'width:330px; float:left');
div.setAttribute('class', 'well');
var label = document.createElement('label');
label.innerHTML = 'YOUR TEXT HERE';
div.appendChild(label);

Angular ngClass and click event for toggling class

This should work for you.

In .html:

<div class="my_class" (click)="clickEvent()"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

In .ts:

status: boolean = false;
clickEvent(){
    this.status = !this.status;       
}

Switching a DIV background image with jQuery

I personally would just use the JavaScript code to switch between 2 classes.

Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).

CSS with different images

.div {
    /* button size etc properties */
}

.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}

Or CSS with image sprite

.div {
    background: url(img/sprite.gif) no-repeat left top;
    /* Other styles */
}

.expanded {background-position: left bottom;}

Then...

JavaScript code with images

$(function){
    $('#button').click(function(){
        if($(this).hasClass('expanded'))
        {
            $(this).addClass('collapsed').removeClass('expanded');
        }
        else
        {
            $(this).addClass('expanded').removeClass('collapsed');
        }
    });
}

JavaScript with sprite

Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass/removeClass method will work fine in this situation as well

The most elegant solution (unfortunately not Internet Explorer 6 friendly)

$(function){
        $('#button').click(function(){
            $(this).toggleClass('expanded');
        });
    }

$(function){
        $('#button').click(function(){
            if($(this).hasClass('expanded'))
            {
                $(this).removeClass('expanded');
            }
            else
            {
                $(this).addClass('expanded');
            }
        });
    }

As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.

Sometimes adding a WCF Service Reference generates an empty reference.cs

As @dblood points out, the main pain is in the DataContractSerializer, that doens't correctly re-use the types. There are already some answers here so I'll start by adding some pro's and cons about these:

  • The 'IsReference' flag causes a lot of trouble, but removing it isn't always the answer (specifically: in situations with recursion).
  • The underlying issue is that the data contract is somehow not the same as the type names, even though they sometimes are (huh? Yes, you read that right!). Apparently the serializer is quite picky and it's very hard to find the real issue.
  • Removing the 'references checks' from the 'Configure service reference' works, but leaves you with a multiple implementations. However, I often reuse SOAP interfaces across DLL's. Also, in most mature SOA's that I know, multiple services interfaces implement and extend the same interface classes. Removing 'use referenced types' checks results in a situation where you cannot simply pass objects around anymore.

Fortunately, if you are in control of your service, there is a simple solution that solves all these issues. This means you can still re-use service interfaces across DLL's - which is IMO a must-have for a proper solution. This is how the solution works:

  1. Create a separate interface DLL. In that DLL, include all DataContract and ServiceContract's; put ServiceContract's on your interfaces.
  2. Derive the server implementation from the interface.
  3. Use the same DLL to construct the client using your favorite method. For example (IMyInterface is the service contract interface):

    var httpBinding = new BasicHttpBinding();
    var identity = new DnsEndpointIdentity("");
    var address = new EndpointAddress(url, identity, new AddressHeaderCollection());
    var channel = new ChannelFactory<IMyInterface>(httpBinding, address);
    return channel.CreateChannel();
    

In other words: Don't use the 'add service reference' functionality, but force WCF to use the (correct) service types by bypassing the proxy generation. After all, you already have these classes.

Pro's:

  1. You bypass the svcutil.exe process, which means you don't have any IsReference issues
  2. DataContract types and names are correct by definition; after all, both server and client use the very same definition.
  3. If you extend the API or use types from another DLL, (1) and (2) still hold, so you won't run in any trouble there.

Cons:

  1. A-sync methods are a pain, since you don't generate an a-sync proxy. As a result, I wouldn't recommend doing this in Silverlight applications.

What is 'Currying'?

Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.

The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.

The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.

For example:

function curryMinus(x) 
{
  return function(y) 
  {
    return x - y;
  }
}

var minus5 = curryMinus(1);
minus5(3);
minus5(5);

I can also do...

var minus7 = curryMinus(7);
minus7(3);
minus7(5);

This is very great for making complex code neat and handling of unsynchronized methods etc.

How do I find which application is using up my port?

On the command prompt, do:

netstat -nb

How to download all dependencies and packages to directory

The aptitude --download-only ... approach only works if you have a debian distro with internet connection in your hands.

If you don't, I think it is better to run the following script on the disconnected debian machine:

apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list

move the downloads.list file into a connected linux (or non linux) machine, and run:

wget --input-file myurilist

this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.

credits: http://www.tuxradar.com/answers/517

PS I basically copied the blog post because it was not very readable, and in case the post will disappear.

Using GPU from a docker container?

Use x11docker by mviereck:

https://github.com/mviereck/x11docker#hardware-acceleration says

Hardware acceleration

Hardware acceleration for OpenGL is possible with option -g, --gpu.

This will work out of the box in most cases with open source drivers on host. Otherwise have a look at wiki: feature dependencies. Closed source NVIDIA drivers need some setup and support less x11docker X server options.

This script is really convenient as it handles all the configuration and setup. Running a docker image on X with gpu is as simple as

x11docker --gpu imagename

Set the maximum character length of a UITextField in Swift

1.Set the delegate of your textfield:

 textField.delegate = self

2.Implement the method in your view controller :

// MARK: Text field delegate

extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return range.location < maxLength (maxLength can be any maximum length you can define)
    }
}

Random numbers with Math.random() in Java

Math.random() generates a number between 0 (inclusive) and 1 (exclusive).

So (int)(Math.random() * max) ranges from 0 to max-1 inclusive.

Then (int)(Math.random() * max) + min ranges from min to max + min - 1, which is not what you want.

Google's formula is correct.

Npm install failed with "cannot run in wd"

The only thing that worked for me was adding a .npmrc file containing:

unsafe-perm = true

Adding the same config to package.json didn't have any effect.

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

CSS how to make an element fade in and then fade out?

I found this link to be useful: css-tricks fade-in fade-out css.

Here's a summary of the csstricks post:

CSS classes:

.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
.m-fadeIn {
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

In React:

toggle(){
    if(true condition){
        this.setState({toggleClass: "m-fadeIn"});
    }else{
        this.setState({toggleClass: "m-fadeOut"});
    }
}

render(){
    return (<div className={this.state.toggleClass}>Element to be toggled</div>)
}

jQuery count number of divs with a certain class?

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.

dyld: Library not loaded ... Reason: Image not found

You can use sudo install_name_tool -change change dylib path And sudo install_name_tool -id change dylib name

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :

PRINT 'Line 1
Line 2
Line 3'
PRINT ''

PRINT 'How long is a blank line feed?'
PRINT LEN('
')
PRINT ''

PRINT 'What are the ASCII values?'
PRINT ASCII(SUBSTRING('
',1,1))
PRINT ASCII(SUBSTRING('
',2,1))

Result :
Line 1
Line 2
Line 3

How long is a blank line feed?
2

What are the ASCII values?
13
10

Or if you'd rather specify your string on one line (almost!) you could employ REPLACE() like this (optionally use CHAR(13)+CHAR(10) as the replacement) :

PRINT REPLACE('Line 1`Line 2`Line 3','`','
')

Trusting all certificates using HttpClient over HTTPS

work with all https

httpClient = new DefaultHttpClient();

SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
};

ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

Run parallel multiple commands at once in the same terminal

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.

#!/bin/bash

for cmd in "$@"; do {
  echo "Process \"$cmd\" started";
  $cmd & pid=$!
  PID_LIST+=" $pid";
} done

trap "kill $PID_LIST" SIGINT

echo "Parallel processes have started";

wait $PID_LIST

echo
echo "All processes have completed";

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"

Example:

parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"

Start 4 parallel sleep and waits until "sleep 4" finishes.

RESTful URL design for search

There are a lot of good options for your case here. Still you should considering using the POST body.

The query string is perfect for your example, but if you have something more complicated, e.g. an arbitrary long list of items or boolean conditionals, you might want to define the post as a document, that the client sends over POST.

This allows a more flexible description of the search, as well as avoids the Server URL length limit.

Formatting a Date String in React Native

Write below function to get date in string, convert and return in string format.

getParsedDate(strDate){
    var strSplitDate = String(strDate).split(' ');
    var date = new Date(strSplitDate[0]);
    // alert(date);
    var dd = date.getDate();
    var mm = date.getMonth() + 1; //January is 0!

    var yyyy = date.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    date =  dd + "-" + mm + "-" + yyyy;
    return date.toString();
}

Print it where you required: Date : {this.getParsedDate(stringDate)}

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

How to check if array element exists or not in javascript?

Consider the array a:

var a ={'name1':1, 'name2':2}

If you want to check if 'name1' exists in a, simply test it with in:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

I had this in VS 2012 where the "Section name" had been changed in a project, and I fixed it by deleting "app.config" in the project, then right-clicking on the project in the "Solution Explorer", selecting "Properties", then "Settings", then making a change to one of the settings, saving, and re-building. This created a new app.config with the correct information.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

When to use RSpec let()?

In general, let() is a nicer syntax, and it saves you typing @name symbols all over the place. But, caveat emptor! I have found let() also introduces subtle bugs (or at least head scratching) because the variable doesn't really exist until you try to use it... Tell tale sign: if adding a puts after the let() to see that the variable is correct allows a spec to pass, but without the puts the spec fails -- you have found this subtlety.

I have also found that let() doesn't seem to cache in all circumstances! I wrote it up in my blog: http://technicaldebt.com/?p=1242

Maybe it is just me?

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

Control Panel > Turn Windows Features on or off

Internet Information Services > World Wide Web Services > Application Development Features

Enable the two options

.NET Extensibility 3.5
.ASP.NET 3.5

enter image description here

How to check if a string contains only numbers?

You may just remove all spaces and leverage LINQ All:

Determines whether all elements of a sequence satisfy a condition.

Use it as shown below:

Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
    Console.WriteLine("The string is all numeric (spaces ignored)!")
Else
    Console.WriteLine("The string contains a char that is not numeric and space!")
End If

To only check if a string consists of only digits use:

If number.All(AddressOf Char.IsDigit) Then

Pointer to class data member "::*"

A realworld example of a pointer-to-member could be a more narrow aliasing constructor for std::shared_ptr:

template <typename T>
template <typename U>
shared_ptr<T>::shared_ptr(const shared_ptr<U>, T U::*member);

What that constructor would be good for

assume you have a struct foo:

struct foo {
    int ival;
    float fval;
};

If you have given a shared_ptr to a foo, you could then retrieve shared_ptr's to its members ival or fval using that constructor:

auto foo_shared = std::make_shared<foo>();
auto ival_shared = std::shared_ptr<int>(foo_shared, &foo::ival);

This would be useful if want to pass the pointer foo_shared->ival to some function which expects a shared_ptr

https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

Git - Ignore files during merge

Example:

  1. You have two branches: master, develop
  2. You created file in develop branch and want to ignore it while merging

Code:

git config --global merge.ours.driver true
git checkout master
echo "path/file_to_ignore merge=ours" >> .gitattributes
git merge develop

You can also ignore files with same extension

for example all files with .txt extension:

echo "*.txt merge=ours" >> .gitattributes

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.

A:you need to configure the primeng tabulemodule in ngmodule

Get user input from textarea

Here is full component example

import { Component } from '@angular/core';

@Component({
  selector: 'app-text-box',
  template: `
        <h1>Text ({{textValue}})</h1>
        <input #textbox type="text" [(ngModel)]="textValue" required>
        <button (click)="logText(textbox.value)">Update Log</button>
        <button (click)="textValue=''">Clear</button>

        <h2>Template Reference Variable</h2>
        Type: '{{textbox.type}}', required: '{{textbox.hasAttribute('required')}}',
        upper: '{{textbox.value.toUpperCase()}}'

        <h2>Log <button (click)="log=''">Clear</button></h2>
        <pre>{{log}}</pre>`
})
export class TextComponent {

  textValue = 'initial value';
  log = '';

  logText(value: string): void {
    this.log += `Text changed to '${value}'\n`;
  }
}

How can I send the "&" (ampersand) character via AJAX?

You need to url-escape the ampersand. Use:

var wysiwyg_clean = wysiwyg.replace('&', '%26');

As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.

Outlets cannot be connected to repeating content iOS

As most people have pointed out that subclassing UITableViewCell solves this issue. But the reason this not allowed because the prototype cell(UITableViewCell) is defined by Apple and you cannot add any of your own outlets to it.

End-line characters from lines read from text file, using Python

What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n' as the last character, and therefore doing line = line[:-1] would incorrectly strip off the last character of the line.

The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:

def strip_trailing_newlines(file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
    # do something with line

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

How to call shell commands from Ruby

This is not really an answer but maybe someone will find it useful:

When using TK GUI on Windows, and you need to call shell commands from rubyw, you will always have an annoying CMD window popping up for less then a second.

To avoid this you can use:

WIN32OLE.new('Shell.Application').ShellExecute('ipconfig > log.txt','','','open',0)

or

WIN32OLE.new('WScript.Shell').Run('ipconfig > log.txt',0,0)

Both will store the ipconfig output inside log.txt, but no windows will come up.

You will need to require 'win32ole' inside your script.

system(), exec() and spawn() will all pop up that annoying window when using TK and rubyw.

Automatically open default email client and pre-populate content

Implemented this way without using Jquery:

<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>

sendEmail(message) {
    var email = message.emailId;
    var subject = message.subject;
    var emailBody = 'Hi '+message.from;
    document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}

Sizing elements to percentage of screen width/height

This is a supplemental answer showing the implementation of a couple of the solutions mentioned.

FractionallySizedBox

If you have a single widget you can use a FractionallySizedBox widget to specify a percentage of the available space to fill. Here the green Container is set to fill 70% of the available width and 30% of the available height.

FractionallySizedBox
Widget myWidget() {
  return FractionallySizedBox(
    widthFactor: 0.7,
    heightFactor: 0.3,
    child: Container(
      color: Colors.green,
    ),
  );
}

Expanded

The Expanded widget allows a widget to fill the available space, horizontally if it is in a row, or vertically if it is in a column. You can use the flex property with multiple widgets to give them weights. Here the green Container takes 70% of the width and the yellow Container takes 30% of the width.

Expanded

If you want to do it vertically, then just replace Row with Column.

Widget myWidget() {
  return Row(
    children: <Widget>[
      Expanded(
        flex: 7,
        child: Container(
          color: Colors.green,
        ),
      ),
      Expanded(
        flex: 3,
        child: Container(
          color: Colors.yellow,
        ),
      ),
    ],
  );
}

Supplemental code

Here is the main.dart code for your reference.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("FractionallySizedBox"),
        ),
        body: myWidget(),
      ),
    );
  }
}

// replace with example code above
Widget myWidget() {
  return ...
}

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I had tried most of the above solution and in past some of them had worked.

But this time none of them worked, so i had deleted my library project's .jar file. and rebuild both library and application project.

And this time it's worked!

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'firstname'=>'value',
    'lastname'=>'value',
    'email'=>'value',
    'address'=>'value',
    'tree' => array(
        'tree1'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree2'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree3'=>array(
            'fruit'=>'value',
            'height'=>'value'
        )
    )
)

How to check whether a file is empty or not?

>>> import os
>>> os.stat("file").st_size == 0
True

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

From http://www.javaroots.com/2013/02/classnotfoundexception-vs.html:

ClassNotFoundException : occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath.

NoClassDefFoundError : this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.

Example:

public class Test1
{
}


public class Test 
{
   public static void main(String[] args)
   {
        Test1 = new Test1();    
   }

}

Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw

Exception in thread "main" java.lang.NoClassDefFoundError: Test
    at Test1.main(Test1.java:5)
Caused by: java.lang.ClassNotFoundException: Test
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

ClassNotFoundException: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.

NoClassDefFoundError: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Refresh Fragment at reload

// Reload current fragment
Fragment frag = new Order();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_home, frag).commit();

Deleting rows with MySQL LEFT JOIN

This script worked for me:

DELETE t
FROM table t
INNER JOIN join_table jt ON t.fk_column = jt.id
WHERE jt.comdition_column…;

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

Scroll back to the top of scrollable div

these two codes worked for me like a charm this first will take to scroll to the top of the page but if you want to scroll to some specific div use the second one with your div id.

$('body, html, #containerDiv').scrollTop(0);
document.getElementById('yourDivID').scrollIntoView();

If you want to scroll to by a class name use the below code

var $container = $("html,body");
var $scrollTo = $('.main-content');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300);

Change value of input and submit form in JavaScript

Here is simple code. You must set an id for your input. Here call it 'myInput':

var myform = document.getElementById('myform');
myform.onsubmit = function(){
    document.getElementById('myInput').value = '1';
    myform.submit();
};

C read file line by line

In your readLine function, you return a pointer to the line array (Strictly speaking, a pointer to its first character, but the difference is irrelevant here). Since it's an automatic variable (i.e., it's “on the stack”), the memory is reclaimed when the function returns. You see gibberish because printf has put its own stuff on the stack.

You need to return a dynamically allocated buffer from the function. You already have one, it's lineBuffer; all you have to do is truncate it to the desired length.

    lineBuffer[count] = '\0';
    realloc(lineBuffer, count + 1);
    return lineBuffer;
}

ADDED (response to follow-up question in comment): readLine returns a pointer to the characters that make up the line. This pointer is what you need to work with the contents of the line. It's also what you must pass to free when you've finished using the memory taken by these characters. Here's how you might use the readLine function:

char *line = readLine(file);
printf("LOG: read a line: %s\n", line);
if (strchr(line, 'a')) { puts("The line contains an a"); }
/* etc. */
free(line);
/* After this point, the memory allocated for the line has been reclaimed.
   You can't use the value of `line` again (though you can assign a new value
   to the `line` variable if you want). */

Select multiple columns from a table, but group by one

Your Data

DECLARE @OrderDetails TABLE 
(ProductID INT,ProductName VARCHAR(10), OrderQuantity INT)

INSERT INTO @OrderDetails VALUES
(1001,'abc',5),(1002,'abc',23),(2002,'xyz',8),
(3004,'ytp',15),(4001,'aze',19),(1001,'abc',7)

Query

 Select ProductID, ProductName, Sum(OrderQuantity) AS Total
 from @OrderDetails 
 Group By ProductID, ProductName  ORDER BY ProductID

Result

+---------------------------------+
¦ ProductID ¦ ProductName ¦ Total ¦
¦-----------+-------------+-------¦
¦      1001 ¦ abc         ¦    12 ¦
¦      1002 ¦ abc         ¦    23 ¦
¦      2002 ¦ xyz         ¦     8 ¦
¦      3004 ¦ ytp         ¦    15 ¦
¦      4001 ¦ aze         ¦    19 ¦
+---------------------------------+

How to define an enumerated type (enum) in C?

If you declare the name for enumeration no error will occur.

If not declared, you have to use a typedef:

enum enum_name {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;

It will not display an error...

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

How to extract text from a PDF file?

PyPDF2 does work, but results may vary. I am seeing quite inconsistent findings from its result extraction.

reader=PyPDF2.pdf.PdfFileReader(self._path)
eachPageText=[]
for i in range(0,reader.getNumPages()):
    pageText=reader.getPage(i).extractText()
    print(pageText)
    eachPageText.append(pageText)

Difference between setUp() and setUpBeforeClass()

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

How to convert Javascript datetime to C# datetime?

You could use the toJSON() JavaScript method, it converts a JavaScript DateTime to what C# can recognise as a DateTime.

The JavaScript code looks like this

var date = new Date();
date.toJSON(); // this is the JavaScript date as a c# DateTime

Note: The result will be in UTC time

Running SSH Agent when starting Git Bash on Windows

P.S: These instructions are in context of a Bash shell opened in Windows 10 Linux Subsystem and doesn't mention about sym-linking SSH keys generated in Windows with Bash on Ubuntu on Windows

1) Update your .bashrc by adding following in it

# Set up ssh-agent
SSH_ENV="$HOME/.ssh/environment"

function start_agent {
    echo "Initializing new SSH agent..."
    touch $SSH_ENV
    chmod 600 "${SSH_ENV}"
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' >> "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add
}

# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
    . "${SSH_ENV}" > /dev/null
    kill -0 $SSH_AGENT_PID 2>/dev/null || {
        start_agent
    }
else
    start_agent
fi

2) Then run $ source ~/.bashrc to reload your config.

The above steps have been taken from https://github.com/abergs/ubuntuonwindows#2-start-an-bash-ssh-agent-on-launch

3) Create a SSH config file, if not present. Use following command for creating a new one: .ssh$ touch config

4) Add following to ~/.ssh/config

Host github.com-<YOUR_GITHUB_USERNAME> 
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_work_gmail # path to your private key
AddKeysToAgent yes


Host csexperimental.abc.com
IdentityFile ~/.ssh/id_work_gmail # path to your private key
AddKeysToAgent yes

<More hosts and github configs can be added in similar manner mentioned above>

5) Add your key to SSH agent using command $ ssh-add ~/.ssh/id_work_gmail and then you should be able to connect to your github account or remote host using ssh. For e.g. in context of above code examples:

$ ssh github.com-<YOUR_GITHUB_USERNAME>

or

$ ssh <USER>@csexperimental.abc.com

This adding of key to the SSH agent should be required to be performed only one-time.

6) Now logout of your Bash session on Windows Linux Subsystem i.e. exit all the Bash consoles again and start a new console again and try to SSH to your Github Host or other host as configured in SSH config file and it should work without needing any extra steps.

Note:

Thanks.

Lazy Method for Reading Big File in Python?

file.readlines() takes in an optional size argument which approximates the number of lines read in the lines returned.

bigfile = open('bigfilename','r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
    process([line for line in tmp_lines])
    tmp_lines = bigfile.readlines(BUF_SIZE)

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb line in web.config and it started working:

<system.web>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

How to compute the sum and average of elements in an array?

Here is my rookie way of simply finding the avg. Hope this helps somebody.

function numAvg(num){
    var total = 0;
    for(var i = 0;i < num.length; i++) { 
        total+=num[i];
    }
    return total/num.length;
}

Best way to encode text data for XML in Java?

Use JAXP and forget about text handling it will be done for you automatically.

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

php implode (101) with quotes

If you want to use loops you can also do:

$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo

Allow access permission to write in Program Files of Windows 7

If you have such a program just install it in C:\, not in Program Files. I had a lot of problems when I was installing Android SDK. My problem got solved by installing it in C:\.

The operation cannot be completed because the DbContext has been disposed error

Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList() statement inside using scope

Twig for loop for arrays with keys

I guess you want to do the "Iterating over Keys and Values"

As the doc here says, just add "|keys" in the variable you want and it will magically happen.

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

It never hurts to search before asking :)

Get the correct week number of a given date

There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.

  • 52 weeks * 7days = 364 days.

So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?

How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.

  • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.

Check your current Culture's settings to see what it uses as the first day of the week.

As you see it's normal to get 53 as a result.

  • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.

It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.

For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.

var d = new DateTime(2012, 12, 31);
CultureInfo cul = CultureInfo.CurrentCulture;

var firstDayWeek = cul.Calendar.GetWeekOfYear(
    d,
    CalendarWeekRule.FirstDay,
    DayOfWeek.Monday);

int weekNum = cul.Calendar.GetWeekOfYear(
    d,
    CalendarWeekRule.FirstDay,
    DayOfWeek.Monday);

int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
Console.WriteLine("Year: {0} Week: {1}", year, weekNum);

Prints out: Year: 2012 Week: 54

Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.

So week 53 starts on monday 2012-12-31, lasts one day and then stops.

53 is the correct answer. Change the Culture to germany if want to to try it.

CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");

How to run function in AngularJS controller on document ready?

If you're getting something like getElementById call returns null, it's probably because the function is running, but the ID hasn't had time to load in the DOM.

Try using Will's answer (towards the top) with a delay. Example:

angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    $scope.sleep = (time) => {
        return new Promise((resolve) => setTimeout(resolve, time));
    };
    angular.element(document).ready(function () {
        $scope.sleep(500).then(() => {        
            //code to run here after the delay
        });
    });
}]);

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

If you are using intellij and want to use gradle you need to add this to the dependencies section of build.gradle file:

testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")

global variable for all controller and views

If you are worried about repeated database access, make sure that you have some kind of caching built into your method so that database calls are only made once per page request.

Something like (simplified example):

class Settings {

    static protected $all;

    static public function cachedAll() {
        if (empty(self::$all)) {
           self::$all = self::all();
        }
        return self::$all;
    }
}

Then you would access Settings::cachedAll() instead of all() and this would only make one database call per page request. Subsequent calls will use the already-retrieved contents cached in the class variable.

The above example is super simple, and uses an in-memory cache so it only lasts for the single request. If you wanted to, you could use Laravel's caching (using Redis or Memcached) to persist your settings across multiple requests. You can read more about the very simple caching options here:

http://laravel.com/docs/cache

For example you could add a method to your Settings model that looks like:

static public function getSettings() {
    $settings = Cache::remember('settings', 60, function() {
        return Settings::all();
    });
    return $settings;
}

This would only make a database call every 60 minutes otherwise it would return the cached value whenever you call Settings::getSettings().

I want my android application to be only run in portrait mode?

Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

Works like a charm!

NOTICE: Change this.activity by your activity or add it to the main activity and remove this.activity ;-)

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

TO set the input type of EditText as decimal use this code:

EditText edit = new EditText(this);
edit.SetRawInputType(Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

How to redirect docker container logs to a single file?

docker logs -f <yourContainer> &> your.log &

Explanation:

  • -f (i.e.--follow): writes all existing logs and continues (follows) logging everything that comes next.
  • &> redirects both the standard output and standard error.
  • Likely you want to run that method in the background, thus the &.
  • You can separate output and stderr by: > output.log 2> error.log (instead of using &>).

Trim a string based on the string length

s = s.length() > 10 ? s.substring(0, 9) : s;

Capitalize words in string

function capitalize(s){
    return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};

capitalize('this IS THE wOrst string eVeR');

output: "This Is The Worst String Ever"

Update:

It appears this solution supersedes mine: https://stackoverflow.com/a/7592235/104380

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Find the PID of a process that uses a port on Windows

PowerShell (Core-compatible) one-liner to ease copypaste scenarios:

netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table

Output:

ProcessName State     Protocol AddressLocal AddressForeign
----------- -----     -------- ------------ --------------
System      LISTENING TCP      [::]:8080    [::]:0
System      LISTENING TCP      0.0.0.0:8080 0.0.0.0:0

Same code, developer-friendly:

$Port = 8080

# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
  | Select-String $Port
$PidsAtPort = $PidsAtPortString `
  | ForEach-Object { `
      $_ -replace '\s+', ',' `
  } `
  | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')

# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
  | ForEach-Object { `
    $portProcess = Get-Process `
      | Where-Object Id -eq $_.PID; `
    $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
    Write-Output $_;
  }

# Show output
$ProcessesAtPort `
  | Sort-Object    ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Format-Table

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

This error just means that myapp.views.home is not something that can be called, like a function. It is a string in fact. While your solution works in django 1.9, nevertheless it throws a warning saying this will deprecate from version 1.10 onwards, which is exactly what has happened. The previous solution by @Alasdair imports the necessary view functions into the script through either from myapp import views as myapp_views or from myapp.views import home, contact

comparing 2 strings alphabetically for sorting purposes

You do say that the comparison is for sorting purposes. Then I suggest instead:

"a".localeCompare("b");

It returns -1 since "a" < "b", 1 or 0 otherwise, like you need for Array.prototype.sort()

Keep in mind that sorting is locale dependent. E.g. in German, ä is a variant of a, so "ä".localeCompare("b", "de-DE") returns -1. In Swedish, ä is one of the last letters in the alphabet, so "ä".localeCompare("b", "se-SE") returns 1.

Without the second parameter to localeCompare, the browser's locale is used. Which in my experience is never what I want, because then it'll sort differently than the server, which has a fixed locale for all users.

Apache HttpClient Interim Error: NoHttpResponseException

Most likely persistent connections that are kept alive by the connection manager become stale. That is, the target server shuts down the connection on its end without HttpClient being able to react to that event, while the connection is being idle, thus rendering the connection half-closed or 'stale'. Usually this is not a problem. HttpClient employs several techniques to verify connection validity upon its lease from the pool. Even if the stale connection check is disabled and a stale connection is used to transmit a request message the request execution usually fails in the write operation with SocketException and gets automatically retried. However under some circumstances the write operation can terminate without an exception and the subsequent read operation returns -1 (end of stream). In this case HttpClient has no other choice but to assume the request succeeded but the server failed to respond most likely due to an unexpected error on the server side.

The simplest way to remedy the situation is to evict expired connections and connections that have been idle longer than, say, 1 minute from the pool after a period of inactivity. For details please see this section of the HttpClient tutorial.

JavaScript get clipboard data on paste event (Cross browser)

function myFunct( e ){
    e.preventDefault();

    var pastedText = undefined;
    if( window.clipboardData && window.clipboardData.getData ){
    pastedText = window.clipboardData.getData('Text');
} 
else if( e.clipboardData && e.clipboardData.getData ){
    pastedText = e.clipboardData.getData('text/plain');
}

//work with text

}
document.onpaste = myFunct;

How to SSH into Docker?

Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed. Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>. i.e:

docker run -p 52022:22 container1 
docker run -p 53022:22 container2

Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>. I.e.:

ssh -p 52022 myuser@RemoteServer --> SSH to container1

ssh -p 53022 myuser@RemoteServer --> SSH to container2

Fatal error: Call to undefined function mysqli_connect()

Simply do it

sudo apt install php-mysqli

It works perfectly and it is version independent

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:

http://php.net/manual/en/mysqli.error.php

Try altering your problem line like so and you should be in good shape:

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection));