Programs & Examples On #Python multithreading

python-multithreading refers to how to divide work into multiple streams of execution in Python.

What is the use of join() in Python threading?

The method join()

blocks the calling thread until the thread whose join() method is called is terminated.

Source : http://docs.python.org/2/library/threading.html

How to obtain a Thread id in Python?

The thread.get_ident() function returns a long integer on Linux. It's not really a thread id.

I use this method to really get the thread id on Linux:

import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')

# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186

def getThreadId():
   """Returns OS thread id - Specific to Linux"""
   return libc.syscall(SYS_gettid)

Timeout on a function call

Here is a POSIX version that combines many of the previous answers to deliver following features:

  1. Subprocesses blocking the execution.
  2. Usage of the timeout function on class member functions.
  3. Strict requirement on time-to-terminate.

Here is the code and some test cases:

import threading
import signal
import os
import time

class TerminateExecution(Exception):
    """
    Exception to indicate that execution has exceeded the preset running time.
    """


def quit_function(pid):
    # Killing all subprocesses
    os.setpgrp()
    os.killpg(0, signal.SIGTERM)

    # Killing the main thread
    os.kill(pid, signal.SIGTERM)


def handle_term(signum, frame):
    raise TerminateExecution()


def invoke_with_timeout(timeout, fn, *args, **kwargs):
    # Setting a sigterm handler and initiating a timer
    old_handler = signal.signal(signal.SIGTERM, handle_term)
    timer = threading.Timer(timeout, quit_function, args=[os.getpid()])
    terminate = False

    # Executing the function
    timer.start()
    try:
        result = fn(*args, **kwargs)
    except TerminateExecution:
        terminate = True
    finally:
        # Restoring original handler and cancel timer
        signal.signal(signal.SIGTERM, old_handler)
        timer.cancel()

    if terminate:
        raise BaseException("xxx")

    return result

### Test cases
def countdown(n):
    print('countdown started', flush=True)
    for i in range(n, -1, -1):
        print(i, end=', ', flush=True)
        time.sleep(1)
    print('countdown finished')
    return 1337


def really_long_function():
    time.sleep(10)


def really_long_function2():
    os.system("sleep 787")


# Checking that we can run a function as expected.
assert invoke_with_timeout(3, countdown, 1) == 1337

# Testing various scenarios
t1 = time.time()
try:
    print(invoke_with_timeout(1, countdown, 3))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)

t1 = time.time()
try:
    print(invoke_with_timeout(1, really_long_function2))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)


t1 = time.time()
try:
    print(invoke_with_timeout(1, really_long_function))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)

# Checking that classes are referenced and not
# copied (as would be the case with multiprocessing)


class X:
    def __init__(self):
        self.value = 0

    def set(self, v):
        self.value = v


x = X()
invoke_with_timeout(2, x.set, 9)
assert x.value == 9

Are lists thread-safe?

I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error

The FLAWED version

import threading
import time

# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []

def add():
    for i in range(count):
        l.append(i)
        time.sleep(0.0001)

def remove():
    for i in range(count):
        l.remove(i)
        time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output when ERROR

Exception in thread Thread-63:
Traceback (most recent call last):
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
    l.remove(i)
ValueError: list.remove(x): x not in list

Version that uses locks

import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
    with lock:
        for i in range(count):
            l.append(i)
            time.sleep(0.0001)

def remove():
    with lock:
        for i in range(count):
            l.remove(i)
            time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output

[] # Empty list

Conclusion

As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another

How to Multi-thread an Operation Within a Loop in Python

import numpy as np
import threading


def threaded_process(items_chunk):
    """ Your main process which runs in thread for each chunk"""
    for item in items_chunk:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')  

n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
    thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
    thread_list.append(thread)
    thread_list[thr].start()

for thread in thread_list:
    thread.join()

How to terminate a thread when main program ends?

Check this question. The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?

To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:

try:
    start_thread()  
except (KeyboardInterrupt, SystemExit):
    cleanup_stop_thread()
    sys.exit()

This way you can control what to do whenever the program is abruptly terminated.

You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

How can I use threading in Python?

Most documentation and tutorials use Python's Threading and Queue module, and they could seem overwhelming for beginners.

Perhaps consider the concurrent.futures.ThreadPoolExecutor module of Python 3.

Combined with with clause and list comprehension it could be a real charm.

from concurrent.futures import ThreadPoolExecutor, as_completed

def get_url(url):
    # Your actual program here. Using threading.Lock() if necessary
    return ""

# List of URLs to fetch
urls = ["url1", "url2"]

with ThreadPoolExecutor(max_workers = 5) as executor:

    # Create threads
    futures = {executor.submit(get_url, url) for url in urls}

    # as_completed() gives you the threads once finished
    for f in as_completed(futures):
        # Get the results
        rs = f.result()

Open a new tab in the background?

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

Decimal separator comma (',') with numberDecimal inputType in EditText

A workaround (until Google fix this bug) is to use an EditText with android:inputType="numberDecimal" and android:digits="0123456789.,".

Then add a TextChangedListener to the EditText with the following afterTextChanged:

public void afterTextChanged(Editable s) {
    double doubleValue = 0;
    if (s != null) {
        try {
            doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
        } catch (NumberFormatException e) {
            //Error
        }
    }
    //Do something with doubleValue
}

How to use Fiddler to monitor WCF service

This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.

I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.

This worked perfectly.

If your client is a WCF client, then see this Q&A for how to set the proxy.

Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.

String replace method is not replacing characters

You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

sentence = sentence.replace("and", " ");

A String is immutable in java. Methods like replace return a new String.

Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

How do I save JSON to local text file

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json" and format to .json

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Put quotes around a variable string in JavaScript

In case of array like

result = [ '2015',  '2014',  '2013',  '2011' ],

it gets tricky if you are using escape sequence like:

result = [ \'2015\',  \'2014\',  \'2013\',  \'2011\' ].

Instead, good way to do it is to wrap the array with single quotes as follows:

result = "'"+result+"'";

How to use radio buttons in ReactJS?

I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.

_x000D_
_x000D_
/*_x000D_
 * A simple React component_x000D_
 */_x000D_
class App extends React.Component {_x000D_
  constructor(params) {_x000D_
     super(params) _x000D_
     // initial gender state set from props_x000D_
     this.state = {_x000D_
       gender: this.props.gender_x000D_
     }_x000D_
     this.setGender = this.setGender.bind(this)_x000D_
  }_x000D_
  _x000D_
  setGender(e) {_x000D_
    this.setState({_x000D_
      gender: e.target.value_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const {gender} = this.state_x000D_
    return  <div>_x000D_
        Gender:_x000D_
        <div>_x000D_
          <input type="radio" checked={gender == "male"} _x000D_
onClick={this.setGender} value="male" /> Male_x000D_
          <input type="radio" checked={gender == "female"} _x000D_
onClick={this.setGender} value="female"  /> Female_x000D_
        </div>_x000D_
        { "Select Gender: " } {gender}_x000D_
      </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

Check if key exists and iterate the JSON array using Python

I wrote a tiny function for this purpose. Feel free to repurpose,

def is_json_key_present(json, key):
    try:
        buf = json[key]
    except KeyError:
        return False

    return True

Remove grid, background color, and top and right borders from ggplot2

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.

Here's updated code reflecting current ggplot syntax:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:

plot output

How do I convert a string to enum in TypeScript?

I also ran into the same compiler error. Just a slight shorter variation of Sly_cardinal's approach.

var color: Color = Color[<string>colorId];

How to copy directories with spaces in the name

After some trial and error and observing the results (in other words, I hacked it), I got it to work.

Quotes ARE required to use a path name with spaces. The trick is there MUST be a space after the path names before the closing quote...like this...

robocopy "C:\Source Path " "C:\Destination Path " /option1 /option2...

This almost seems like a bug and certainly not very intuitive.

Todd K.

What's the best way to cancel event propagation between nested ng-click calls?

If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to zip a file using cmd line?

If you want a simple program that will run with .net 4.6.1 or above on Windows, I wrote this for my own purposes after finding this question.

You simply cd to the directory above the folder you want to zip, then pass in the directory name and it will output mydir.zip. Add zipper to your path, I personally have a utils folder on C:\utils that have things like this in it.

cd C:\Users\SomeUser\Desktop\
zipper myfolder

Below is the source code and copy of the exe:

https://github.com/tryonlinux/commandLineZipper

How to get row index number in R?

It not quite clear what exactly you are trying to do.

To reference a row in a data frame use df[row,]

To get the first position in a vector of something use match(item,vector), where the vector could be one of the columns of your data frame, eg df$cname if the column name is cname.

Edit:

To combine these you would write:

df[match(item,df$cname),]

Note that the match gives you the first item in the list, so if you are not looking for a unique reference number, you may want to consider something else.

The container 'Maven Dependencies' references non existing library - STS

Although it's too late , But here is my experience .

Whenever you get your maven project from a source controller or just copying your project from one machine to another , you need to update the dependencies .

For this Right-click on Project on project explorer -> Maven -> Update Project.

Please consider checking the "Force update of snapshot/releases" checkbox.

If you have not your dependencies in m2/repository then you need internet connection to get from the remote maven repository.

In case you have get from the source controller and you have not any unit test , It's probably your test folder does not include in the source controller in the first place , so you don't have those in the new repository.so you need to create those folders manually.

I have had both these cases .

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

After having tried some things on this page without success I had a look in the page-source and remarked that all quotes in the serialized string have been replaced by html-entities. Decoding these entities helps avoiding much headache:

$myVar = html_entity_decode($myVar);

How do I get column datatype in Oracle with PL-SQL with low privileges?

The best solution that I've found for such case is

select column_name, data_type||
case
when data_precision is not null and nvl(data_scale,0)>0 then '('||data_precision||','||data_scale||')'
when data_precision is not null and nvl(data_scale,0)=0 then '('||data_precision||')'
when data_precision is null and data_scale is not null then '(*,'||data_scale||')'
when char_length>0 then '('||char_length|| case char_used 
                                                         when 'B' then ' Byte'
                                                         when 'C' then ' Char'
                                                         else null 
                                           end||')'
end||decode(nullable, 'N', ' NOT NULL')
from user_tab_columns
where table_name = 'TABLE_NAME'
and column_name = 'COLUMN_NAME';

@Aaron Stainback, thank you for correction!

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

how to remove untracked files in Git?

While git clean works well, I still find it useful to use my own script to clean the git repo, it has some advantages.

This shows a list of files to be cleaned, then interactively prompts to clean or not. This is nearly always what I want since interactively prompting per file gets tedious.

It also allows manual filtering of the list which comes in handy when there are file types you don't want to clean (and have reason not to commit).


git_clean.sh


#!/bin/bash
readarray -t -d '' FILES < <(
    git ls-files -z --other --directory |
        grep --null-data --null -v '.bin$\|Cargo.lock$'
)
if [ "$FILES" = "" ]; then
    echo  "Nothing to clean!"
    exit 0
fi

echo "Dirty files:"
printf '  %s\n' "${FILES[@]}"

DO_REMOVE=0
while true; do
    echo ""
    read -p "Remove ${#FILES[@]} files? [y/n]: " choice
    case "$choice" in
        y|Y )
            DO_REMOVE=1
            break ;;
        n|N )
            echo "Exiting!"
            break ;;
        * ) echo "Invalid input, expected [Y/y/N/n]"
            continue ;;
    esac
done

if [ "$DO_REMOVE" -eq 1 ];then
    echo "Removing!"
    for f in "${FILES[@]}"; do
       rm -rfv "$f"
    done
fi

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

Oracle SQL Developer: Unable to find a JVM

The solution that worked for me: If you have Sqldeveloper with java incorporated, you can use the \sqldeveloper\bin\sqldeveloper.bat to launch sqldeveloper as told here.

How to show x and y axes in a MATLAB graph?

This should work in Matlab:

set(gca, 'XAxisLocation', 'origin')

Options are: bottom, top, origin.

For Y.axis:

YAxisLocation; left, right, origin

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Get exit code of a background process

The pid of a backgrounded child process is stored in $!. You can store all child processes' pids into an array, e.g. PIDS[].

wait [-n] [jobspec or pid …]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If the -n option is supplied, wait waits for any job to terminate and returns its exit status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

Use wait command you can wait for all child processes finish, meanwhile you can get exit status of each child processes via $? and store status into STATUS[]. Then you can do something depending by status.

I have tried the following 2 solutions and they run well. solution01 is more concise, while solution02 is a little complicated.

solution01

#!/bin/bash

# start 3 child processes concurrently, and store each pid into array PIDS[].
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
  ./${app} &
  PIDS+=($!)
done

# wait for all processes to finish, and store each process's exit code into array STATUS[].
for pid in ${PIDS[@]}; do
  echo "pid=${pid}"
  wait ${pid}
  STATUS+=($?)
done

# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
  if [[ ${st} -ne 0 ]]; then
    echo "$i failed"
  else
    echo "$i finish"
  fi
  ((i+=1))
done

solution02

#!/bin/bash

# start 3 child processes concurrently, and store each pid into array PIDS[].
i=0
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
  ./${app} &
  pid=$!
  PIDS[$i]=${pid}
  ((i+=1))
done

# wait for all processes to finish, and store each process's exit code into array STATUS[].
i=0
for pid in ${PIDS[@]}; do
  echo "pid=${pid}"
  wait ${pid}
  STATUS[$i]=$?
  ((i+=1))
done

# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
  if [[ ${st} -ne 0 ]]; then
    echo "$i failed"
  else
    echo "$i finish"
  fi
  ((i+=1))
done

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

Why does my 'git branch' have no master?

master is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.

You can add it back with git checkout -b master.

Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

Oracle 12c Installation failed to access the temporary location

Summarized: Oracle under Windows has problems with usernames containing non-English letters or special characters:

If your machine is fresh installed, first look here. All the network related or 32 vs. 64 related issues may be not significant for you:

As others already pointed out partly, this error is highly related to the name of the TEMP dir. It occurred to me when installing Oracle 11g first time on a totally fresh Windows (e.g. Server 2008 R2 or Win 7, not important).

As I found out, on my machine the problem was, that the username contained a German special character ("ö"). Moreover Oracle cannot handle any special character, I assume, the TEMP path is limited to letters. Other colleagues here have reported problems with underscore and chinese characters.

Explanation: In Windows the TEMP dir (environment variable %TEMP%) is by default in the user directory, for example:

C:\Users\ThisUser\AppData\Local\Temp

If "ThisUser" contains special or non-ASCII characters, then in this case this affects the TEMP path, and that is where Oracle is gettings problems.

Setting the TEMP dir to different directory is of course another possibility instead of installing with another username.

Moreover, Oracle is not a fully native Windows citizen which everybody will recognize, if he opens the Oracle install logfile with notepad ;-) Obviously, this is not programmed cleanly and portable, e.g. with using "std::endl" instead of "\n" . (Yes, Notepad++ and other editors do the job.)

Overall, my impression is, if the database were of the same quality as it's installer, Oracle would not be so successful ..

Last remark: Yes, after failed install because of the special characters you see only one Oracle service named OracleRemExecService, but there is no reason to stop this manually as recommended in other solutions, if you are able to install again a fresh OS..

JavaFX Location is not set error message

I've stumbled upon the same problem. Program was running great from Eclipse via "Run" button, but NOT from runnable JAR which I'd exported before. My solution was:

1) Move Main class to default package

2) Set other path for Eclipse, and other while running from the JAR file (paste this into Main.java)

public static final String sourcePath = isProgramRunnedFromJar() ? "src/" : "";
public static boolean isProgramRunnedFromJar() {
    File x = getCurrentJarFileLocation();
    if(x.getAbsolutePath().contains("target"+File.separator+"classes")){
        return false;
    } else {
        return true;
    }
}
public static File getCurrentJarFileLocation() {
        try {
            return new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        } catch(URISyntaxException e){
            e.printStackTrace();
            return null;
        }
}

And after that in start method you have to load files like this:

FXMLLoader loader = new FXMLLoader(getClass().getResource(sourcePath +"MainScene.fxml"));

It works for me in Eclipse Mars with e(fx)clipse plugin.

adb is not recognized as internal or external command on windows

You have two ways:

First go to the particular path of Android SDK:

1) Open your command prompt and traverse to the platform-tools directory through it such as

$ cd Frameworks\Android-Sdk\platform-tools

2) Run your adb commands now such as to know that your adb is working properly :

$ adb devices OR adb logcat OR simply adb

Second way is :

1) Right click on your My Computer.

2) Open Environment variables.

3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).

4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.

5) Restart your computer once.

6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.

Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"

Unable to preventDefault inside passive event listener

In plain JS add { passive: false } as third argument

document.addEventListener('wheel', function(e) {
    e.preventDefault();
    doStuff(e);
}, { passive: false });

JSON parsing using Gson for Java

You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

public class Response {

   @SerializedName("data")
   private Data data;

   private static class Data {
      @SerializedName("translations")
      public Translation[] translations;
   }

   private static class Translation {
      @SerializedName("translatedText")
      public String translatedText;
   }

   public String getTranslatedText() {
      return data.translations[0].translatedText;
   }
}

Then you can do the parsing in your parse() method using a Gson object:

Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);

System.out.println("Translated text: " + response.getTranslatedText());

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.

Angular - POST uploaded file

First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:

var data : {
  name: string;
  file: File;
} = {
  name: "Name",
  file: inputValue.files[0]
  };

Then you send it to the Server with JSON.stringify(data)

let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);

How are people unit testing with Entity Framework 6, should you bother?

Effort Experience Feedback here

After a lot of reading I have been using Effort in my tests: during the tests the Context is built by a factory that returns a in memory version, which lets me test against a blank slate each time. Outside of the tests, the factory is resolved to one that returns the whole Context.

However i have a feeling that testing against a full featured mock of the database tends to drag the tests down; you realize you have to take care of setting up a whole bunch of dependencies in order to test one part of the system. You also tend to drift towards organizing together tests that may not be related, just because there is only one huge object that handles everything. If you don't pay attention, you may find yourself doing integration testing instead of unit testing

I would have prefered testing against something more abstract rather than a huge DBContext but i couldn't find the sweet spot between meaningful tests and bare-bone tests. Chalk it up to my inexperience.

So i find Effort interesting; if you need to hit the ground running it is a good tool to quickly get started and get results. However i think that something a bit more elegant and abstract should be the next step and that is what I am going to investigate next. Favoriting this post to see where it goes next :)

Edit to add: Effort do take some time to warm up, so you're looking at approx. 5 seconds at test start up. This may be a problem for you if you need your test suite to be very efficient.


Edited for clarification:

I used Effort to test a webservice app. Each message M that enters is routed to a IHandlerOf<M> via Windsor. Castle.Windsor resolves the IHandlerOf<M> which resovles the dependencies of the component. One of these dependencies is the DataContextFactory, which lets the handler ask for the factory

In my tests I instantiate the IHandlerOf component directly, mock all the sub-components of the SUT and handles the Effort-wrapped DataContextFactory to the handler.

It means that I don't unit test in a strict sense, since the DB is hit by my tests. However as I said above it let me hit the ground running and I could quickly test some points in the application

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

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

I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:

tsql -H somehost.com -p 1433

In my case, the output was:

Error 20009 (severity 9):
  Unable to connect: Adaptive Server is unavailable or does not exist
  OS error 111, "Connection refused"
There was a problem connecting to the server

Should I call Close() or Dispose() for stream objects?

This is an old question, but you can now write using statements without needing to block each one. They will be disposed of in reverse order when the containing block is finished.

using var responseStream = response.GetResponseStream();
using var reader = new StreamReader(responseStream);
using var writer = new StreamWriter(filename);

int chunkSize = 1024;
while (!reader.EndOfStream)
{
    char[] buffer = new char[chunkSize];
    int count = reader.Read(buffer, 0, chunkSize);
    if (count != 0)
    {
        writer.Write(buffer, 0, count);
    }
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using

What's the best way to do a backwards loop in C/C#/C++?

That's definitely the best way for any array whose length is a signed integral type. For arrays whose lengths are an unsigned integral type (e.g. an std::vector in C++), then you need to modify the end condition slightly:

for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)
    // blah

If you just said i >= 0, this is always true for an unsigned integer, so the loop will be an infinite loop.

Virtualenv Command Not Found

I had the same problem for a long time. I solved it by running these two commands, first is to install second is to activate the env:

python3 -m pip install virtualenv
python3 -m virtualenv yourenvname

Note that I'm using python3, you can change it to just python if python3 fails. Thanks.

TypeScript function overloading

As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.

myComponent {
  method(): { console.info("no args"); },
  method(arg): { console.info("with arg"); }
}

Calling:

myComponent.method()

seems to execute the method with arguments, silently ignoring the no-arg version, with output:

with arg

scp from Linux to Windows

To send a file from windows to linux system

scp path-to-file user@ipaddress:/path-to-destination

Example:

scp C:/Users/adarsh/Desktop/Document.txt [email protected]:/tmp

keep in mind that there need to use forward slash(/) inplace of backward slash(\) in for the file in windows path else it will show an error

C:UsersadarshDesktopDocument.txt: No such file or directory

. After executing scp command you will ask for password of root user in linux machine. There you GO...

To send a file from linux to windows system

scp -r user@ipaddress:/path-to-file path-to-destination

Example:

scp -r [email protected]:/tmp/Document.txt C:/Users/adarsh/Desktop/

and provide your linux password. only one you have to add in this command is -r. Thanks.

PHP Get name of current directory

For EXAMPLE

Your Path = /home/serverID_name/www/your_route_Dir/

THIS_is_the_DIR_I_Want

A Soultion that WORKS:

$url = dirname(\__FILE__);
$array = explode('\\\',$url);
$count = count($array);
echo $array[$count-1];

File upload from <input type="file">

There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

Callback functions in C++

A Callback function is a method that is passed into a routine, and called at some point by the routine to which it is passed.

This is very useful for making reusable software. For example, many operating system APIs (such as the Windows API) use callbacks heavily.

For example, if you wanted to work with files in a folder - you can call an API function, with your own routine, and your routine gets run once per file in the specified folder. This allows the API to be very flexible.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Linq to Entities - SQL "IN" clause

I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.

Now well, that looks like this:

Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
    while(productIds.Count > 0)
    {
        sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
          entities.Products.Name, productIds.Dequeue());
    }
}

Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where throws the following exception:

The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.

Found this in MSDN Forums, might be helpful to have in mind.

Matthias

... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)

Java AES encryption and decryption

You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).

Take a look at the following link for more information.

http://crackstation.net/hashing-security.htm

Show values from a MySQL database table inside a HTML table on a webpage

Here is an easy way to fetch data from a MySQL database using PDO.

define("DB_HOST", "localhost");    // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");

$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);

$print = ""; // assign an empty string

$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);

$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';

while ($names = $stmt->fetch()) { // loop and display data
    $print .= '<tr>';
    $print .= "<td>{$names->firstname}</td>";
    $print .= "<td>{$names->lastname}</td>";
    $print .= '</tr>';
}

$print .= "</table>";
echo $print;

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Make an /login url, than accept "user" and "password" parameters via GET and don't require basic auth. Here, use php, node, java, whatever and parse your passwd file and match parameters (user/pass) against it. If there is a match then redirect to http://user:[email protected]/ (this will set credential on your browser) if not, send 401 response (without WWW-Authenticate header).

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

No assembly found containing an OwinStartupAttribute Error

Check you have the correct startup project selected. I had a web api project as startup. That generated this error.

Skipping Iterations in Python

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()

Can I prevent text in a div block from overflowing?

I guess you should start with the basics from w3

https://www.w3schools.com/cssref/css3_pr_text-overflow.asp

div {
    white-space: nowrap; 
    overflow: hidden;
    text-overflow: ellipsis;
}

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Here's something else I found interesting. If your source is a DataTable, you can use dynamic sorting without using Dynamic Linq

DataTable orders = dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
                                         orderby order.Field<DateTime>("OrderDate")
                                         select order;
DataView view = query.AsDataView();
bindingSource1.DataSource = view;

reference: http://msdn.microsoft.com/en-us/library/bb669083.aspx (Using DataSetExtensions)

Here is one more way to do it by converting it to a DataView:

DataTable contacts = dataSet.Tables["Contact"];    
DataView view = contacts.AsDataView();    
view.Sort = "LastName desc, FirstName asc";    
bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();

How to add element into ArrayList in HashMap

Typical code is to create an explicit method to add to the list, and create the ArrayList on the fly when adding. Note the synchronization so the list only gets created once!

@Override
public synchronized boolean addToList(String key, Item item) {
   Collection<Item> list = theMap.get(key);
   if (list == null)  {
      list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
      theMap.put(key, list );
   }

   return list.add(item);
}

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

How to make rpm auto install dependencies

For dnf users just use dnf install *.rpm, localinstall is no longer needed.

batch file Copy files with certain extensions from multiple directories into one directory

you can also use vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
strDestination = "c:\tmp\"
Set objFolder = objFS.GetFolder(strFolder)

Go(objFolder)

Sub Go(objDIR)
  If objDIR <> "\System Volume Information" Then
    For Each eFolder in objDIR.SubFolders       
        Go eFolder
    Next
    For Each strFile In objDIR.Files
        strFileName = strFile.Name
        strExtension = objFS.GetExtensionName(strFile)
        If strExtension = "doc" Then
            objFS.CopyFile strFile , strDestination & strFileName
        End If 
    Next    
  End If  
End Sub 

save as mycopy.vbs and on command line

c:\test> cscript /nologo mycopy.vbs

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

Javascript - Get Image height

Do you want to adjust the images themselves, or just the way they display? If the former, you want something on the server side. If the latter, you just need to change image.height and image.width.

Clear git local cache

git rm --cached *.FileExtension

This must ignore all files from this extension

Is it possible to GROUP BY multiple columns using MySQL?

If you prefer (I need to apply this) group by two columns at same time, I just saw this point:

SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

Undo a Git merge that hasn't been pushed yet

Answering the question "Undo a Git merge that hasn't been pushed yet"

You can use git reset --hard HEAD~1

Consider the following situation where there are 2 branches master and feature-1:


$ git log --graph --oneline --all

Do Git merge

$ git merge feature-1

$ git log --graph --oneline --all

Undo Git merge

$ git reset --hard HEAD~1

$ git log --graph --oneline --all

How to pass a value to razor variable from javascript variable?

But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

Changing Java Date one hour back

You can use from bellow code for date and time :

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

       cal.add(Calendar.DATE, 1);
       System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, 1);
       System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, 1);
       System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, 1);
       System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, 1);
       System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, 1);
       System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.DATE, -1);
       System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, -1);
       System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, -1);
       System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, -1);
       System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, -1);
       System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, -1);
       System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));

Output :

Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52

This link is good : See here

And see : See too

And : Here

And : Here

And : Here

If you need just time :

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

Remove char at specific index - python

rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'

Break out of a While...Wend loop

Another option would be to set a flag variable as a Boolean and then change that value based on your criteria.

Dim count as Integer 
Dim flag as Boolean

flag = True

While flag
    count = count + 1 

    If count = 10 Then
        'Set the flag to false         '
        flag = false
    End If 
Wend

Get first key in a (possibly) associative array?

I think the best and fastest way to do it is:

$first_key=key(array_slice($array, 0, 1, TRUE))

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

In InnoDB you have START TRANSACTION;, which in this engine is the officialy recommended way to do transactions, instead of SET AUTOCOMMIT = 0; (don't use SET AUTOCOMMIT = 0; for transactions in InnoDB unless it is for optimizing read only transactions). Commit with COMMIT;.

You might want to use SET AUTOCOMMIT = 0; in InnoDB for testing purposes, and not precisely for transactions.

In MyISAM you do not have START TRANSACTION;. In this engine, use SET AUTOCOMMIT = 0; for transactions. Commit with COMMIT; or SET AUTOCOMMIT = 1; (Difference explained in MyISAM example commentary below). You can do transactions this way in InnoDB too.

Source: http://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_autocommit

Examples of general use transactions:

/* InnoDB */
START TRANSACTION;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

COMMIT; /* SET AUTOCOMMIT = 1 might not set AUTOCOMMIT to its previous state */

/* MyISAM */
SET AUTOCOMMIT = 0;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

SET AUTOCOMMIT = 1; /* COMMIT statement instead would not restore AUTOCOMMIT to 1 */

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

This happened to me because I enabled usb debug previously on another pc. So to mke it work on a second pc I had to disable usb debugging and re-enable it while connected to the second pc and it worked.

CardView Corner Radius

I wrote a drawable lib to custom round corner position, it looks like this:

example.png

You can get this lib at here:

https://github.com/mthli/Slice

java.lang.IllegalArgumentException: View not attached to window manager

I too get this error sometimes when I dismiss dialog and finish activity from onPostExecute method. I guess sometimes activity gets finished before dialog successfully dismisses.

Simple, yet effective solution that works for me

@Override
protected void onPostExecute(MyResult result) {
    try {
        if ((this.mDialog != null) && this.mDialog.isShowing()) {
            this.mDialog.dismiss();
        }
    } catch (final IllegalArgumentException e) {
        // Handle or log or ignore
    } catch (final Exception e) {
        // Handle or log or ignore
    } finally {
        this.mDialog = null;
    }  
}

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

Basically, you just have to remove that constraint from the associated view. For instance, if is the height constraint giving warning, just remove it from your view; it will not affect the view.

How to use Google App Engine with my own naked domain (not subdomain)?

[Update April 2016] This answer is now outdated, custom naked domain mapping is supported, see Lawrence Mok's answer.

I have figured it out!

First off: it is impossible to link something like mydomain.com with your appspot app. This is considered a naked domain, which is not supported by Google App Engine (anymore). Strictly speaking, the answer to my question has to be "impossible". Read on...

All you can do is add subdomains pointing to your app, e.g myappid.mydomain.com. The key to get your top level domain linked to your app is to realize that www is a subdomain like any other!

myappid.mydomain.com is treated exactly the same as www.mydomain.com!

Here are the steps:

  1. Go to appengine.google.com, open your app
  2. Administration > Versions > Add Domain... (your domain has to be linked to your Google Apps account, follow the steps to do that including the domain verification.)
  3. Go to www.google.com/a/yourdomain.com
  4. Dashboard > your app should be listed here. Click on it.
  5. myappid settings page > Web address > Add new URL
  6. Simply enter www and click Add
  7. Using your domain hosting provider's web interface, add a CNAME for www for your domain and point to ghs.googlehosted.com

Now you have www.mydomain.com linked to your app.

I wished this would have been more obvious in the documentation...Good luck!

Is it a bad practice to use break in a for loop?

I disagree!

Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.

I think it makes more sense to have your checks at the top of your for loop like so

for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}

or if you need to process the row first

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}

This way you can write a function to perform everything and make much cleaner code.

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

Or if your condition is complicated you can move that code out too!

for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)

C++ compiling on Windows and Linux: ifdef switch

No, these defines are compiler dependent. What you can do, use your own set of defines, and set them on the Makefile. See this thread for more info.

how can I enable PHP Extension intl?

Use phpinfo() function to find php.ini file path, open php.ini file. Here search extension=php_intl.dll then remove semi-colon (;) beginning of that line.

After removing semi-colon (;) restart you webserver (apache).

How to use external ".js" files

Note :- Do not use script tag in external JavaScript file.

<html>
<head>

</head>
<body>
    <p id="cn"> Click on the button to change the light button</p>
    <button type="button" onclick="changefont()">Click</button>

     <script src="external.js"></script>
</body>

External Java Script file:-

        function changefont()
            {

                var x = document.getElementById("cn");
                x.style.fontSize = "25px";           
                x.style.color = "red"; 
            }

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Make sure you have run the MongoDB's Service before you want to connect the console.

run and start the server:

$ sudo mongod

then:

$ mongo
...
>

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT a.* FROM orders a INNER JOIN (SELECT course,MAX(id) as id FROM orders WHERE admission_id=".$id." GROUP BY course ) AS b ON a.course = b.course AND a.id = b.id

With the Above Query you will get unique records with where condition

Difference between TCP and UDP?

TCP establishes a connection before the actual data transmission takes place, UDP does not. In this way, UDP can provide faster delivery. Applications like DNS, time server access, therefore, use UDP.

Unlike UDP, TCP uses congestion control. It responses to the network load. Unlike UDP, it slows down when network congestion is imminent. So, applications like multimedia preferring constant throughput might go for UDP.

Besides, UDP is unreliable, it doesn't react on packet losses. So loss sensitive applications like multimedia transmission prefer UDP. However, TCP is a reliable protocol, so, applications that require reliability such as web transfer, email, file download prefer TCP.

Besides, in today's internet UDP is not as welcoming as TCP due to middle boxes. Some applications like skype fall down to TCP when UDP connection is assumed to be blocked.

How to check if a subclass is an instance of a class at runtime?

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommended one):

if (view instanceof B)

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Simple:

go in the root folder of the project when this happens and run:

gem install shutup
shutup

This will find the process currently running, kill it and clean up the pid file

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

How to get overall CPU usage (e.g. 57%) on Linux

You can try:

top -bn1 | grep "Cpu(s)" | \
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
           awk '{print 100 - $1"%"}'

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

How do I check to see if a value is an integer in MySQL?

for me the only thing that works is:

CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT
RETURN SIN REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';

from kevinclark all other return useless stuff for me in case of 234jk456 or 12 inches

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

How to embed a SWF file in an HTML page?

The best approach to embed a SWF into an HTML page is to use SWFObject.

It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content.

It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page.

An example from the documentation:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  <head>
    <title>SWFObject dynamic embed - step 3</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="swfobject.js"></script>

    <script type="text/javascript">
        swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
    </script>

  </head>
  <body>
    <div id="myContent">
      <p>Alternative content</p>
    </div>
  </body>
</html>

A good tool to use along with this is the SWFObject HTML and JavaScript generator. It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters.

It Is highly recommended and very simple to use.

Angular HTML binding

The way to dynamically add elements to DOM, as explained on Angular 2 doc, is by using ViewContainerRef class from @Angular/core.

What you have to do is to declare a directive that will implement ViewContainerRef and act like a placeholder on your DOM.

Directive

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appInject]'
})
export class InjectDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

Then, in the template where you want to inject the component:

HTML

<div class="where_you_want_to_inject">    
  <ng-template appInject></ng-template>
</div>

Then, from the injected component code, you will inject the component containing the HTML you want:

import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  @ViewChild(InjectDirective) injectComp: InjectDirective;

  constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
  }

  public addComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.createComponent(componentFactory);
  }

  public removeComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.remove();
  }

}

I added a fully working demo app on Angular 2 dynamically add component to DOM demo

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(), But with assertThrows your assertion will pass even if the thrown exception is of child type.

This is because, JUnit 5 checks exception type by calling Class.isIntance(..), Class.isInstance(..) will return true even if the exception thrown is of the child types.

The workaround for this is to assert on Class:

Throwable throwable =  assertThrows(Throwable.class, () -> {
    service.readFile("sampleFile.txt");
});
assertEquals(FileNotFoundException.class, throwable.getClass());

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

How to validate array in Laravel?

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

How to make sure you don't get WCF Faulted state exception?


Update:

This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.


Original post

This is Microsoft's recommended way to handle WCF client calls:

For more detail see: Expected Exceptions

try
{
    ...
    double result = client.Add(value1, value2);
    ...
    client.Close();
}
catch (TimeoutException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}
catch (CommunicationException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}

Additional information

So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:

c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client

Download the sample: C# or VB

Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.

How to make background of table cell transparent

You can try :

  @media print {
    .table td,
    .table th {
        background-color: transparent !important;
        -webkit-print-color-adjust: exact !important;

    }
}

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

PHP json_encode json_decode UTF-8

Work for me :)

function jsonEncodeArray( $array ){
    array_walk_recursive( $array, function(&$item) { 
       $item = utf8_encode( $item ); 
    });
    return json_encode( $array );
}

How to remove duplicate values from an array in PHP

//Find duplicates 

$arr = array( 
    'unique', 
    'duplicate', 
    'distinct', 
    'justone', 
    'three3', 
    'duplicate', 
    'three3', 
    'three3', 
    'onlyone' 
);

$unique = array_unique($arr); 
$dupes = array_diff_key( $arr, $unique ); 
    // array( 5=>'duplicate', 6=>'three3' 7=>'three3' )

// count duplicates

array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )

Avoid line break between html elements

There are several ways to prevent line breaks in content. Using &nbsp; is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.

The most robust alternative is to use nobr markup, which is nonstandard but universally supported and works even when CSS is disabled:

<td><nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</nobr></td>

(You can, but need not, use &nbsp; instead of spaces in this case.)

Another way is the nowrap attribute (deprecated/obsolete, but still working fine, except for some rare quirks):

<td nowrap><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

Then there’s the CSS way, which works in CSS enabled browsers and needs a bit more code:

<style>
.nobr { white-space: nowrap }
</style>
...
<td class=nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

The remote server returned an error: (407) Proxy Authentication Required

In following code, we don't need to hard code the credentials.

service.Proxy = WebRequest.DefaultWebProxy;
service.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
service.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

How to create a directive with a dynamic template in AngularJS?

If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Scenario 1

In client application (application is not web application, e.g may be swing app)

private static ApplicationContext context = new  ClassPathXmlApplicationContext("test-client.xml");

context.getBean(name);

No need of web.xml. ApplicationContext as container for getting bean service. No need for web server container. In test-client.xml there can be Simple bean with no remoting, bean with remoting.

Conclusion: In Scenario 1 applicationContext and DispatcherServlet are not related.

Scenario 2

In a server application (application deployed in server e.g Tomcat). Accessed service via remoting from client program (e.g Swing app)

Define listener in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

At server startup ContextLoaderListener instantiates beans defined in applicationContext.xml.

Assuming you have defined the following in applicationContext.xml:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml.

Conclusion: In Scenario 2 applicationContext and DispatcherServlet are not related.

Scenario 3

In a web application with spring MVC.

In web.xml define:

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

When Tomcat starts, beans defined in springweb-servlet.xml are instantiated. DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for springweb . In our case springweb is FrameworkServlet.

Conclusion: In Scenario 3 applicationContext and DispatcherServlet are not related.

Scenario 4

In web application with spring MVC. springweb-servlet.xml for servlet and applicationContext.xml for accessing the business service within the server program or for accessing DB service in another server program.

In web.xml the following are defined:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

At server startup, ContextLoaderListener instantiates beans defined in applicationContext.xml; assuming you have declared herein:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationContext.xml, beans defined in springweb-servlet.xml are instantiated.

So the instantiation order is: the root (application context), then FrameworkServlet.

Now it should be clear why they are important in which scenario.

Copying one structure to another

You can use the following solution to accomplish your goal:

struct student 
{
    char name[20];
    char country[20];
};
void main()
{
    struct student S={"Wolverine","America"};
    struct student X;
    X=S;
    printf("%s%s",X.name,X.country);
}

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

Reload browser window after POST without prompting user to resend POST data

What you probably need to do is redirect the user after the POST / Form Handler script has been ran.

In PHP this is done like so...

<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>

... this should allow you to refresh the page without getting that "Send Data Again" warning.

You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)

Clearing an HTML file upload field via JavaScript

Yes, the upload element is protected from direct manipulation in different browsers. However, you could erase the element from the DOM tree and then insert a new one in its place via JavaScript. That would give you the same result.

Something along the lines of:

$('#container-element').html('<input id="upload-file" type="file"/>');

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

In order to downgrade, i had to recompile from source (MacOS Mojave)

$ wget https://ssl.icu-project.org/files/icu4c/62.1/icu4c-62_1-src.tgz
$ tar xvfz icu4c-62_1-src.tgz
$ cd icu/sources
$ ./configure
$ make
$ make install

How can I trigger an onchange event manually?

MDN suggests that there's a much cleaner way of doing this in modern browsers:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

Switch statement for greater-than/less-than

Updating the accepted answer (can't comment yet). As of 1/12/16 using the demo jsfiddle in chrome, switch-immediate is the fastest solution.

Results: Time resolution: 1.33

   25ms "if-immediate" 150878146 
   29ms "if-indirect" 150878146
   24ms "switch-immediate" 150878146
   128ms "switch-range" 150878146
   45ms "switch-range2" 150878146
   47ms "switch-indirect-array" 150878146
   43ms "array-linear-switch" 150878146
   72ms "array-binary-switch" 150878146

Finished

 1.04 (   25ms) if-immediate
 1.21 (   29ms) if-indirect
 1.00 (   24ms) switch-immediate
 5.33 (  128ms) switch-range
 1.88 (   45ms) switch-range2
 1.96 (   47ms) switch-indirect-array
 1.79 (   43ms) array-linear-switch
 3.00 (   72ms) array-binary-switch

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

100% with what MarkR said. autocommit makes each statement a one statement transaction.

SHOW ENGINE INNODB STATUS should give you some clues as to the deadlock reason. Have a good look at your slow query log too to see what else is querying the table and try to remove anything that's doing a full tablescan. Row level locking works well but not when you're trying to lock all of the rows!

How can I dynamically set the position of view in Android?

For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...).

If you can limit your support to Honeycomb and up you can use the setX(...), setY(...), setLeft(...), setTop(...), etc.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key

One line if-condition-assignment

you can use one of the following:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

Business logic in MVC

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

Black transparent overlay on image hover with only CSS?

You can accomplish this by playing with the opacity of the image and setting the background color of the image to black. By making the image transparent, it will appear darker.

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div> 

CSS:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; background: black; }
.image img { max-width: 100%; max-height: 100%; }
.image img:hover { opacity: .5 }

You might need to set the browser-specific opacity too to make this work in other browsers too.

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Update the 'apache-tomcat-8.5.5\conf\tomcat-users.xml file. uncomment the roles and add/replace the following line.and restart server

tomcat-users.xml file

<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="standard,manager,admin,manager-gui,manager-script"/>

How to stop/terminate a python script from running?

You can also do it if you use the exit() function in your code. More ideally, you can do sys.exit(). sys.exit() which might terminate Python even if you are running things in parallel through the multiprocessing package.

Note: In order to use the sys.exit(), you must import it: import sys

How to create PDFs in an Android app?

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

stringstream, string, and char* conversion confusion

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

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

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

Razor View throwing "The name 'model' does not exist in the current context"

You are likely to use in the code a variable named model.

How to escape braces (curly brackets) in a format string in .NET

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

Python Replace \\ with \

It's because, even in "raw" strings (=strings with an r before the starting quote(s)), an unescaped escape character cannot be the last character in the string. This should work instead:

'\\ '[0]

git undo all uncommitted or unsaved changes

What I do is

git add . (adding everything)
git stash 
git stash drop

One liner: git add . && git stash && git stash drop

How do format a phone number as a String in Java?

Pattern phoneNumber = Pattern.compile("(\\d{3})(\\d{3})(\\d{4})");
// ...
Matcher matcher = phoneNumber(numberAsLineOf10Symbols);
if (matcher.matches) {
    return "(" + matcher.group(1) + ")-" +matcher.group(2) + "-" + matcher.group(3);
}

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

Just Need to Start MySQL Service after installation:

For Ubuntu:

sudo service mysql start;

For CentOS or RHEL:

sudo service mysqld start;

TypeError: 'str' object cannot be interpreted as an integer

I'm guessing you're running python3, in which input(prompt) returns a string. Try this.

x=int(input('prompt'))
y=int(input('prompt'))

u'\ufeff' in Python string

That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.

Find files containing a given text

find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'

Duplicate Symbols for Architecture arm64

I was able to resolve this error which said "158 duplicate symbols for architecture armv7, 158 duplicate symbols for architecture arm64" --- If this is what you are getting too, then it means you are trying to compile a file which is importing or inheriting a framework or static library having references to C++ code or files. An easy way to handle this would be to change the extension of your .m file to .mm. This is how it gets handled if you are using Objective C, not sure on Swift though.

Also in your build settings - you can update the "other linker flags" to -lc++

How to trigger an event after using event.preventDefault()

as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.

if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)

How do I activate a specific workbook and a specific sheet?

You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:

Sub Test()

Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")

wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54

End Sub

Why not use Double or Float to represent currency?

The result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation. float and double are designed for engineering and scientific calculation and many times doesn’t produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.

    // floating point calculation
    final double amount1 = 2.0;
    final double amount2 = 1.1;
    System.out.println("difference between 2.0 and 1.1 using double is: " + (amount1 - amount2));

    // Use BigDecimal for financial calculation
    final BigDecimal amount3 = new BigDecimal("2.0");
    final BigDecimal amount4 = new BigDecimal("1.1");
    System.out.println("difference between 2.0 and 1.1 using BigDecimal is: " + (amount3.subtract(amount4)));

Output:

difference between 2.0 and 1.1 using double is: 0.8999999999999999
difference between 2.0 and 1.1 using BigDecimal is: 0.9

install cx_oracle for python

If you are trying to install in MAC , just unzip the Oracle client which you downloaded and place it into the folder where you written python scripts. it will start working.

There is too much problem of setting up environmental variables. It worked for me.

Hope this helps.

Thanks

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

Eclipse JPA Project Change Event Handler (waiting)

Don't know why, my Neon Eclipse still having this issue, it doesn't seem to be fixed in Mars version as many people said.

I found that using command is too troublesome, I delete the plugin away via the Eclipse Installation Manager.

Neon: [Help > Installation Details > Installed Software]

Oxygen: [Preferences > Install/Update > Installed Software]

Just select the plugin "Dali Java Persistence Tools -JPA Support" and click "uninstall" will do. Please take note my screen below doesn't have that because I already uninstalled.

enter image description here

How to change line color in EditText

Use android:background property for that edittext. Pass your drawable folder image to it. For example,

android:background="@drawable/abc.png"

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

As an addition to Darin Dimitrov's answer:

If you only want this particular line to use a certain (different from standard) format, you can use in MVC5:

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })

How to count string occurrence in string?

You could try this

let count = s.length - s.replace(/is/g, "").length;

sh: react-scripts: command not found after running npm start

Tried all of the above and nothing worked so I used npm i react-scripts and it worked

getDate with Jquery Datepicker

Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function. In my example I am using "yy-mm-dd", but you can use any format of your choice.

$("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    inline: true,
    minDate: new Date(2010, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    altField: '#datepicker_value',
    onSelect: function(){
        var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
        $('#page_output').html(str_output);
    }
});

Python's equivalent of && (logical-and) in an if-statement

I'm getting an error in the IF conditional. What am I doing wrong?

There reason that you get a SyntaxError is that there is no && operator in Python. Likewise || and ! are not valid Python operators.

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or. Likewise the logical negation operator ! is called not.

So you could just write:

if len(a) % 2 == 0 and len(b) % 2 == 0:

or even:

if not (len(a) % 2 or len(b) % 2):

Some additional information (that might come in handy):

I summarized the operator "equivalents" in this table:

+------------------------------+---------------------+
|  Operator (other languages)  |  Operator (Python)  |
+==============================+=====================+
|              &&              |         and         |
+------------------------------+---------------------+
|              ||              |         or          |
+------------------------------+---------------------+
|              !               |         not         |
+------------------------------+---------------------+

See also Python documentation: 6.11. Boolean operations.

Besides the logical operators Python also has bitwise/binary operators:

+--------------------+--------------------+
|  Logical operator  |  Bitwise operator  |
+====================+====================+
|        and         |         &          |
+--------------------+--------------------+
|         or         |         |          |
+--------------------+--------------------+

There is no bitwise negation in Python (just the bitwise inverse operator ~ - but that is not equivalent to not).

See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.

The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn't evaluated at all.

To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:

>>> def print_and_return(value):
...     print(value)
...     return value

>>> res = print_and_return(False) and print_and_return(True)
False

As you can see only one print statement is executed, so Python really didn't even look at the right operand.

This is not the case for the binary operators. Those always evaluate both operands:

>>> res = print_and_return(False) & print_and_return(True);
False
True

But if the first operand isn't enough then, of course, the second operator is evaluated:

>>> res = print_and_return(True) and print_and_return(False);
True
False

To summarize this here is another Table:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

The True and False represent what bool(left-hand-side) returns, they don't have to be True or False, they just need to return True or False when bool is called on them (1).

So in Pseudo-Code(!) the and and or functions work like these:

def and(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return evaluate(expr2)
    else:
        return left

def or(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return left
    else:
        return evaluate(expr2)

Note that this is pseudo-code not Python code. In Python you cannot create functions called and or or because these are keywords. Also you should never use "evaluate" or if bool(...).

Customizing the behavior of your own classes

This implicit bool call can be used to customize how your classes behave with and, or and not.

To show how this can be customized I use this class which again prints something to track what is happening:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        print('__bool__ called on {!r}'.format(self))
        return bool(self.value)

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

So let's see what happens with that class in combination with these operators:

>>> if Test(True) and Test(False):
...     pass
__bool__ called on Test(True)
__bool__ called on Test(False)

>>> if Test(False) or Test(False):
...     pass
__bool__ called on Test(False)
__bool__ called on Test(False)

>>> if not Test(True):
...     pass
__bool__ called on Test(True)

If you don't have a __bool__ method then Python also checks if the object has a __len__ method and if it returns a value greater than zero. That might be useful to know in case you create a sequence container.

See also 4.1. Truth Value Testing.

NumPy arrays and subclasses

Probably a bit beyond the scope of the original question but in case you're dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool call will raise the dreaded ValueError:

>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In these cases you can use the logical and function from NumPy which performs an element-wise and (or or):

>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False,  True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False,  True,  True])

If you're dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:

>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False,  True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False,  True,  True])

(1)

That the bool call on the operands has to return True or False isn't completely correct. It's just the first operand that needs to return a boolean in it's __bool__ method:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        return self.value

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)

That's because and actually returns the first operand if the first operand evaluates to False and if it evaluates to True then it returns the second operand:

>>> x1
Test(10)
>>> x2
Test(False)

Similarly for or but just the other way around:

>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)

However if you use them in an if statement the if will also implicitly call bool on the result. So these finer points may not be relevant for you.

C++ Singleton design pattern

Has anyone mentioned std::call_once and std::once_flag? Most other approaches - including double checked locking - are broken.

One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.

JS regex: replace all digits in string

You need to add the "global" flag to your regex:

s.replace(new RegExp("[0-9]", "g"), "X")

or, perhaps prettier, using the built-in literal regexp syntax:

.replace(/[0-9]/g, "X")

bash: pip: command not found

It solved my problem by using

sudo easy_install pip

Tool for comparing 2 binary files in Windows

Total Commander also has a binary compare option: go to: File \\Compare by content

ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

How do I print bytes as hexadecimal?

If you want to use C++ streams rather than C functions, you can do the following:

int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };
const int siz_ar = sizeof(ar) / sizeof(int);

for (int i = 0; i < siz_ar; ++i)
    cout << ar[i] << " ";
cout << endl;

for (int i = 0; i < siz_ar; ++i)
    cout << hex << setfill('0') << setw(2) << ar[i] << " ";
cout << endl;

Very simple.

Output:

20 30 40 50 60 70 80 90
14 1e 28 32 3c 46 50 5a 

AngularJS not detecting Access-Control-Allow-Origin header?

It's a bug in chrome for local dev. Try other browser. Then it'll work.

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

Android Material and appcompat Manifest merger failed

If you do not intend to migrate to AndroidX follow the below steps

  1. In terminal type gradlew app:dependencies
  2. After dependencies are shown in the window press Ctrl+f and type androidX
  3. You will find all the dependencies which are using androidx lib internally you may have to downgrade that or use alternative for that to ensure it is no longer using androidX libs internally.

PDO mysql: How to know if insert was successful

PDOStatement->execute() can throw an exception

so what you can do is

try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}

How do I "un-revert" a reverted Git commit?

I had an issue somebody made a revert to master to my branch, but I was needed to be able to merge it again but the problem is that the revert included all my commit. Lets look at that case we created our feature branch from M1 we merge our feature branch in M3 and revert on it in RM3

M1 -> M2 -> M3 -> M4- > RM3 -> M5
 \.         /
  F1->F2 -

How to make the F2 able to merge to M5?

git checkout master
git checkout -b brach-before-revert
git reset --hard M4
git checkout master
git checkout -b new-feature-branch
git reset --hard M1 
git merge --squash brach-before-revert

Mixing C# & VB In The Same Project

You need one project per language. I'm quite confident I saw a tool that merged assemblies, if you find that tool you should be good to go. If you need to use both languages in the same class, you should be able to write half of it in say VB.net and then write the rest in C# by inheriting the VB.net class.

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

PHP: cannot declare class because the name is already in use

I had this problem before and to fix this, Just make sure :

  1. You did not create an instance of this class before
  2. If you call this from a class method, make sure the __destruct is set on the class you called from.

My problem (before) :
I had class : Core, Router, Permissions and Render Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.

Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...

Correct way to initialize HashMap and can HashMap hold different value types?

Eclipse is suggesting you to define generic type so that you can have type safety. You can write

Map m = new HashMap();

which does not ensure type safety but following will ensure type safety

Map<Object,Object> = new HashMap<Object,Object>();

The Object can be any type such as String, Integer etc.

How to simulate "Press any key to continue?"

You can use the getchar routine.

From the above link:

/* getchar example : typewriter */
#include <stdio.h>

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Efficient way to determine number of digits in an integer

/// Determine the number of digits for a 64 bit integer.
/// - Uses at most 5 comparisons.
/// - (cX) 2014 [email protected]
/// - \see http://stackoverflow.com/questions/1489830/#27670035
/**  #d == Number length vs Number of comparisons == #c
     \code
         #d | #c   #d | #c     #d | #c   #d | #c
         ---+---   ---+---     ---+---   ---+---
         20 | 5    15 | 5      10 | 5     5 | 5
         19 | 5    14 | 5       9 | 5     4 | 5
         18 | 4    13 | 4       8 | 4     3 | 4
         17 | 4    12 | 4       7 | 4     2 | 4
         16 | 4    11 | 4       6 | 4     1 | 4
     \endcode
*/
unsigned NumDigits64bs(uint64_t x) {
    return // Num-># Digits->[0-9] 64->bits bs->Binary Search
    ( x >= 10000000000ul // [11-20] [1-10]
    ?
        ( x >= 1000000000000000ul // [16-20] [11-15]
        ?   // [16-20]
            ( x >= 100000000000000000ul // [18-20] [16-17]
            ?   // [18-20]
                ( x >= 1000000000000000000ul // [19-20] [18]
                ? // [19-20]
                    ( x >=  10000000000000000000ul // [20] [19]
                    ?   20
                    :   19
                    )
                : 18
                )
            :   // [16-17]
                ( x >=  10000000000000000ul // [17] [16]
                ?   17
                :   16
                )
            )
        :   // [11-15]
            ( x >= 1000000000000ul // [13-15] [11-12]
            ?   // [13-15]
                ( x >= 10000000000000ul // [14-15] [13]
                ? // [14-15]
                    ( x >=  100000000000000ul // [15] [14]
                    ?   15
                    :   14
                    )
                : 13
                )
            :   // [11-12]
                ( x >=  100000000000ul // [12] [11]
                ?   12
                :   11
                )
            )
        )
    :   // [1-10]
        ( x >= 100000ul // [6-10] [1-5]
        ?   // [6-10]
            ( x >= 10000000ul // [8-10] [6-7]
            ?   // [8-10]
                ( x >= 100000000ul // [9-10] [8]
                ? // [9-10]
                    ( x >=  1000000000ul // [10] [9]
                    ?   10
                    :    9
                    )
                : 8
                )
            :   // [6-7]
                ( x >=  1000000ul // [7] [6]
                ?   7
                :   6
                )
            )
        :   // [1-5]
            ( x >= 100ul // [3-5] [1-2]
            ?   // [3-5]
                ( x >= 1000ul // [4-5] [3]
                ? // [4-5]
                    ( x >=  10000ul // [5] [4]
                    ?   5
                    :   4
                    )
                : 3
                )
            :   // [1-2]
                ( x >=  10ul // [2] [1]
                ?   2
                :   1
                )
            )
        )
    );
}

overlay a smaller image on a larger image python OpenCv

When attempting to write to the destination image using any of these answers above and you get the following error:

ValueError: assignment destination is read-only

A quick potential fix is to set the WRITEABLE flag to true.

img.setflags(write=1)

Break a previous commit into multiple commits

If you have this:

A - B <- mybranch

Where you have committed some content in commit B:

/modules/a/file1
/modules/a/file2
/modules/b/file3
/modules/b/file4

But you want to split B into C - D, and get this result:

A - C - D <-mybranch

You can divide the content like this for example (content from different directories in different commits)...

Reset the branch back to the commit before the one to split:

git checkout mybranch
git reset --hard A

Create first commit (C):

git checkout B /modules/a
git add -u
git commit -m "content of /modules/a"

Create second commit (D):

git checkout B /modules/b
git add -u
git commit -m "content of /modules/b"

How to run a command as a specific user in an init script?

Adding this answer as I had to lookup multiple places to achieve my use case. I had a script that runs on startup. This script runs process as a specific (passwordless) user and is running on multiple linux flavors. Here are options on different flavors: (I have taken java as target process for example)

1. RHEL / CentOS 6:

source /etc/rc.d/init.d/functions
daemon --user=myUser $JAVA_HOME/bin/java

2. RHEL 7 / SUSE12 / other linux flavors where systemd is used:

In your systemd unit file add:

User=myUser

3. Suse 11:

/sbin/startproc -u myUser $JAVA_HOME/bin/java

Installing OpenCV on Windows 7 for Python 2.7

One thing that needs to be mentioned. You have to use the x86 version of Python 2.7. OpenCV doesn't support Python x64. I banged my head on this for a bit until I figured that out.

That said, follow the steps in Abid Rahman K's answer. And as Antimony said, you'll need to do a 'from cv2 import cv'

jquery - is not a function error

When converting an ASP.Net webform prototype to a MVC site I got these errors:

TypeError: $(...).accordion is not a function
$("#accordion").accordion(


$('#dialog').dialog({
TypeError: $(...).dialog is not a function

It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml

@Scripts.Render("~/bundles/jquery")

Comment it out to see if the errors go away. Then fix it in the BundlesConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

How do I put an already-running process under nohup?

On my AIX system, I tried

nohup -p  processid>

This worked well. It continued to run my process even after closing terminal windows. We have ksh as default shell so the bg and disown commands didn't work.

C# SQL Server - Passing a list to a stored procedure

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

How to find the Target *.exe file of *.appref-ms

I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".

I couldn't seem to find the location in the application reference file in my case...

How do you get the Git repository's name in some Git repository?

Repo full name:

git config --get remote.origin.url | grep -Po "(?<=git@github\.com:)(.*?)(?=.git)"

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

I have also come across this issue whilst upgrading from Java 1.6_29 to 1.7.

Alarmingly, my customer has discovered a setting in the Java control panel which resolves this.

In the Advanced Tab you can check 'Use SSL 2.0 compatible ClientHello format'.

This seems to resolve the issue.

We are using Java applets in an Internet Explorer browser.

Hope this helps.

How to get value by class name in JavaScript or jquery?

If you get the the text inside the element use

Text()

$(".element-classname").text();

In your code:

$('.HOEnZb').text();

if you want get all the data including html Tags use:

html()

 $(".element-classname").html();

In your code:

$('.HOEnZb').html();

Hope it helps:)

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

I encountered another problem that returns the same error.

Single quote issue

I used a json string with single quotes :

{
    'property': 1
}

But json.loads accepts only double quotes for json properties :

{
    "property": 1
}

Final comma issue

json.loads doesn't accept a final comma:

{
  "property": "text", 
  "property2": "text2",
}

Solution: ast to solve single quote and final comma issues

You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :

import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json

# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}

Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.

Python documentation warned us of using large/complex string :

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

json.dumps with single quotes

To use json.dumps with single quotes easily you can use this code:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

ast documentation

ast Python 3 doc

ast Python 2 doc

Tool

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

I hope it helps.

Scroll to bottom of div with Vue.js

  1. Use ref attribute on DOM element for reference
<div class="content scrollable" ref="msgContainer">
    <!-- content -->
</div>
  1. You need to setup a WATCH
  data() {
    return {
      count: 5
    };
  },
  watch: {
    count: function() {
      this.$nextTick(function() {
        var container = this.$refs.msgContainer;
        container.scrollTop = container.scrollHeight + 120;
      });
    }
  }
  1. Ensure you're using proper CSS
.scrollable {
  overflow: hidden;
  overflow-y: scroll;
  height: calc(100vh - 20px);
}

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\