Programs & Examples On #Notnull

This tag refers to an object or type that is not null (none).

How do I check if a SQL Server text column is empty?

SELECT * FROM TABLE
WHERE ISNULL(FIELD, '')=''

SQL Column definition : default value and not null redundant?

In other words, doesn't DEFAULT render NOT NULL redundant ?

No, it is not redundant. To extended accepted answer. For column col which is nullable awe can insert NULL even when DEFAULT is defined:

CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);

-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);

+-----+------+
| ID  | COL  |
+-----+------+
|   1 | null |
+-----+------+

Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL:

CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL); 

INSERT INTO t2(id, col) VALUES(1, NULL);

+-----+-----+
| ID  | COL |
+-----+-----+
|  1  |  10 |
+-----+-----+

Here we tried to insert NULL but get default instead.

db<>fiddle demo

ON NULL

If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.

When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.

MySQL SELECT only not null values

Select * from your_table 
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;

The only disadvantage of this approach is that you can only compare 5 columns, after that the result will always be false, so I do compare only the fields that can be NULL.

insert a NOT NULL column to an existing table

This worked for me, can also be "borrowed" from the design view, make changes -> right click -> generate change script.

BEGIN TRANSACTION
GO
ALTER TABLE dbo.YOURTABLE ADD
    YOURCOLUMN bit NOT NULL CONSTRAINT DF_YOURTABLE_YOURCOLUMN DEFAULT 0
GO
COMMIT

Headers and client library minor version mismatch

I ran into the same issue on centos7. Removing php-mysql and installing php-mysqlnd fixed the problem. Thanks Carlos Buenosvinos Zamora for your suggestion.

Here are my commands on centos7 just in case this can be of help to anybody as most of the answers here are based on Debian/Ubuntu.

To find the installed php-mysql package

yum list installed | grep mysql

To remove the installed php-mysql package

yum remove php55w-mysql.x86_64

To install php-mysqlnd

yum install php-mysqlnd.x86_64

Removing all script tags from html with JS Regular Expression

You can do this without a regular expression. Simply cast your HTML string to an HTML node using document.createElement(), find all scripts with element.getElementsByTagName('script'), and then just remove() them!

Fun fact: SO's demo does not like it when you create an element with a <script> tag! The snippet below will not run, but it does work at: Full Working Demo at JSBin.com.

_x000D_
_x000D_
var el = document.createElement( 'html' );
el.innerHTML = "<p>Valid paragraph.</p><p>Another valid paragraph.</p><script>Dangerous scripting!!!</script><p>Last final paragraph.</p>";

var scripts = el.getElementsByTagName( 'script' ); // Live NodeList of your anchor elements

for(var i = 0; i < scripts.length; i++) {
  var script = scripts[i];
  script.remove();
}

console.log(el.innerHTML);
_x000D_
_x000D_
_x000D_

This is a much cleaner solution than a regex, imho.

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

Since this is the first Google result for 'pandas new column from others', here's a simple example:

import pandas as pd

# make a simple dataframe
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df
#    a  b
# 0  1  3
# 1  2  4

# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0    4
# 1    6

# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
#    a  b  c
# 0  1  3  4
# 1  2  4  6

If you get the SettingWithCopyWarning you can do it this way also:

fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'

Source: https://stackoverflow.com/a/12555510/243392

And if your column name includes spaces you can use syntax like this:

df = df.assign(**{'some column name': col.values})

And here's the documentation for apply, and assign.

Edittext change border color with shape.xml

i use as following for over come this matter

edittext_style.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
        android:color="#c8c8c8"/>
<corners android:radius="0dp" />

And applied as bellow

<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextName"
            android:background="@drawable/edit_text_style"/>

try like this..

Remove characters from a String in Java

Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"

If the suffix does not exist in the string, it just returns the original

var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"

You can also check out removePrefix and removeSurrounding which are similar

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

The following is my understanding var reading answer above and google.

# coding:utf-8
r"""
@update: 2017-01-09 14:44:39
@explain: str, unicode, bytes in python2to3
    #python2 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 7: ordinal not in range(128)
    #1.reload
    #importlib,sys
    #importlib.reload(sys)
    #sys.setdefaultencoding('utf-8') #python3 don't have this attribute.
    #not suggest even in python2 #see:http://stackoverflow.com/questions/3828723/why-should-we-not-use-sys-setdefaultencodingutf-8-in-a-py-script
    #2.overwrite /usr/lib/python2.7/sitecustomize.py or (sitecustomize.py and PYTHONPATH=".:$PYTHONPATH" python)
    #too complex
    #3.control by your own (best)
    #==> all string must be unicode like python3 (u'xx'|b'xx'.encode('utf-8')) (unicode 's disappeared in python3)
    #see: http://blog.ernest.me/post/python-setdefaultencoding-unicode-bytes

    #how to Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
    #http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
"""

from __future__ import print_function
import json

a = {"b": u"??"}  # add u for python2 compatibility
print('%r' % a)
print('%r' % json.dumps(a))
print('%r' % (json.dumps(a).encode('utf8')))
a = {"b": u"??"}
print('%r' % json.dumps(a, ensure_ascii=False))
print('%r' % (json.dumps(a, ensure_ascii=False).encode('utf8')))
# print(a.encode('utf8')) #AttributeError: 'dict' object has no attribute 'encode'
print('')

# python2:bytes=str; python3:bytes
b = a['b'].encode('utf-8')
print('%r' % b)
print('%r' % b.decode("utf-8"))
print('')

# python2:unicode; python3:str=unicode
c = b.decode('utf-8')
print('%r' % c)
print('%r' % c.encode('utf-8'))
"""
#python2
{'b': u'\u4e2d\u6587'}
'{"b": "\\u4e2d\\u6587"}'
'{"b": "\\u4e2d\\u6587"}'
u'{"b": "\u4e2d\u6587"}'
'{"b": "\xe4\xb8\xad\xe6\x96\x87"}'

'\xe4\xb8\xad\xe6\x96\x87'
u'\u4e2d\u6587'

u'\u4e2d\u6587'
'\xe4\xb8\xad\xe6\x96\x87'

#python3
{'b': '??'}
'{"b": "\\u4e2d\\u6587"}'
b'{"b": "\\u4e2d\\u6587"}'
'{"b": "??"}'
b'{"b": "\xe4\xb8\xad\xe6\x96\x87"}'

b'\xe4\xb8\xad\xe6\x96\x87'
'??'

'??'
b'\xe4\xb8\xad\xe6\x96\x87'
"""

How to show a confirm message before delete?

Write this in onclick event of the button:

var result = confirm("Want to delete?");
if (result) {
    //Logic to delete the item
}

Node.js - SyntaxError: Unexpected token import

As of Node.js v12 (and this is probably fairly stable now, but still marked "experimental"), you have a couple of options for using ESM (ECMAScript Modules) in Node.js (for files, there's a third way for evaling strings), here's what the documentation says:

The --experimental-modules flag can be used to enable support for ECMAScript modules (ES modules).

Once enabled, Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.

  • Files ending in .js, or extensionless files, when the nearest parent package.json file contains a top-level field "type" with a value of "module".

  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Node.js will treat as CommonJS all other forms of input, such as .js files where the nearest parent package.json file contains no top-level "type" field, or string input without the flag --input-type. This behavior is to preserve backward compatibility. However, now that Node.js supports both CommonJS and ES modules, it is best to be explicit whenever possible. Node.js will treat the following as CommonJS when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .cjs.

  • Files ending in .js, or extensionless files, when the nearest parent package.json file contains a top-level field "type" with a value of "commonjs".

  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=commonjs.

How do you find out the caller function in JavaScript?

You can use Function.Caller to get the calling function. The old method using argument.caller is considered obsolete.

The following code illustrates its use:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

Notes about obsolete argument.caller: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

Be aware Function.caller is non-standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

Change background color for selected ListBox item

If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.

In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.

Here is a skeleton of how the markup should look:

    <ScrollViewer>
        <ItemsControl>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    ...
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

Copy Image from Remote Server Over HTTP

use

$imageString = file_get_contents("http://example.com/image.jpg");
$save = file_put_contents('Image/saveto/image.jpg',$imageString);

Write objects into file with Node.js

Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:

fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');

The second param is an optional replacer function which you don't need in this case so null works.

The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

How to prevent going back to the previous activity?

Just override the onKeyDown method and check if the back button was pressed.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //Back buttons was pressed, do whatever logic you want
    }

    return false;
}

Android: How to create a Dialog without a title?

Use like this:

Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 

This will remove any title bar from dialog window.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

How to concatenate strings in twig

The "{{ ... }}"-delimiter can also be used within strings:

"http://{{ app.request.host }}"

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

Ubuntu Users:

I had the same problem and I fixed it by installing nodejson my system independent of the gem.

on ubuntu its: sudo apt-get install nodejs

I'm using 64bit ubuntu 11.10

update: From @Galina 's answer below I'm guessing that the latest version of nodejs is required, so @steve98177 your best option on a redhat(or CentOS) box is to install from source code as @Galina did, but as you can't "make/install" on this box ?, I suggest you try to install a fedora rpm(long shot) https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager or find another RH/CentOs box(that you can 'make' on) and create your own rpm and install on original RH box(if old glibc on RH plays nice).

The real issue here(IMHO) is installing Gems that have dependencies on installed packages outside of the ruby environment, is there a way of knowing before installing ? an RFI for Gems or bundler ?


CentOS/RedHat Users:

sudo yum install nodejs

Disable scrolling in webview?

Just use android:focusableInTouchMode="false" on your webView.

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

Send password when using scp to copy files from one server to another

One of the ways to get around login issues with ssh, scp, and sftp (all use the same protocol and sshd server) is to create public/private key pairings.

Some servers may disallow this, but most sites don't. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.

  • On your machine, create your public/private key using ssh-keygen. This can vary from system to system, but the program should lead you through this.
  • When ssh-keygen is finished, you will have a $HOME/.ssh directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts which contains the fingerprints of all known hosts you've logged into. The second will be called either authorized_keys or authorized_keys2 depending upon your implementation.
  • If it's not there already, log into the remote host, and run ssh-keygen there too. This will generate a $HOME/.ssh directory there as well as a private/public key pair. Don't do this if the $HOME/.ssh directory already exists and has a public and private key file. You don't want to regenerate it.
  • On the remote server in the $HOME/.ssh directory, create a file called authorized_keys. In this file, put your public key. This public key is found on your $HOME/.ssh directory on your local machine. It will end with *.pub. Paste the contents of that into authorized_keys. If authorized_keys already exists, paste your public key in the next line.

Now, when you log in using ssh, or you use scp or sftp, you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I've logged into many remote servers as a different user and setup my public key in authorized_keys and have no problems logging directly into that user.

Doing Private Public Key Authentication on Windows

If you use Windows, you will need something that can do ssh. Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can't remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys file.

If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.

How to initialize an array in Kotlin with values?

intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)

Correct way to read a text file into a buffer in C?

char source[1000000];

FILE *fp = fopen("TheFile.txt", "r");
if(fp != NULL)
{
    while((symbol = getc(fp)) != EOF)
    {
        strcat(source, &symbol);
    }
    fclose(fp);
}

There are quite a few things wrong with this code:

  1. It is very slow (you are extracting the buffer one character at a time).
  2. If the filesize is over sizeof(source), this is prone to buffer overflows.
  3. Really, when you look at it more closely, this code should not work at all. As stated in the man pages:

The strcat() function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'.

You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat().

The following are two alternatives to consider using instead.

If you know the maximum buffer size ahead of time:

#include <stdio.h>
#define MAXBUFLEN 1000000

char source[MAXBUFLEN + 1];
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
    if ( ferror( fp ) != 0 ) {
        fputs("Error reading file", stderr);
    } else {
        source[newLen++] = '\0'; /* Just to be safe. */
    }

    fclose(fp);
}

Or, if you do not:

#include <stdio.h>
#include <stdlib.h>

char *source = NULL;
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        long bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}

free(source); /* Don't forget to call free() later! */

Border length smaller than div width?

I added line under under h3 tag like this

<h3 class="home_title">Your title here</h3> 
.home_title{
    display:block;
}
.home_title:after {
    display:block;
    clear:both;
    content : "";
    position: relative;
    left    : 0;
    bottom  : 0;
    max-width:250px;
    height  : 1px;
    width   : 50%;  /* or 100px */
    border-bottom:1px solid #e2000f;
    margin:0 auto;
    padding:4px 0px;
}

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

rsync: difference between --size-only and --ignore-times

The short answer is that --ignore-times does more than its name implies. It ignores both the time and size. In contrast, --size-only does exactly what it says.


The long answer is that rsync has three ways to decide if a file is outdated:

  1. Compare the size of source and destination.
  2. Compare the timestamp of source and destination.
  3. Compare the static checksum of source and destination.

These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.

By default, rsync uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:

  • By using --size-only, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.

  • By using --ignore-times, neither of 1, 2 or 3 is performed. A file is always copied.

  • By using --checksum, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.

How to count no of lines in text file and store the value into a variable using batch script?

I found this solution to work best for creating a log file that maintains itself:

setlocal enabledelayedexpansion
SET /A maxlines= 10
set "cmd=findstr /R /N "^^" "filename.txt" | find /C ":""
 for /f %%a in ('!cmd!') do set linecount=%%a
GOTO NEXT

:NEXT 
 FOR /F %%A IN ("filename.txt") DO ( 
  IF %linecount% GEQ %maxlines% GOTO ExitLoop
  echo %clientname% %Date% %Time% >> "filename.txt")
 EXIT

:ExitLoop
 echo %clientname% %Date% %Time% > "filename.txt"
 EXIT

Environmental variables included are %clientname% the computername of the remote client %Date% is the current date and %Time% the current time. :NEXT is called after getting the number of lines in the file. If the file line count is greater than the %maxlines% variable it goes to the :EXITLOOP where it overwrites the file, creating a new one with the first line of information. if it is less than the %maxlines% variable it simply adds the line to the current file.

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

How to permanently export a variable in Linux?

You have to edit three files to set a permanent environment variable as follow:

  • ~/.bashrc

    When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file:

    export DISPLAY=0
    
  • ~/.profile

    Same as bashrc you have to put the mentioned command line at the end of this file to have your environment variable in every login of your OS.

  • /etc/environment

    If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file:

    DISPLAY=0
    

    Note that in this file you do not have to write export command

Normally you have to restart your computer to apply these changes. But you can apply changes in bashrc and profile by these commands:

$ source ~/.bashrc
$ source ~/.profile

But for /etc/environment you have no choice but restarting (as far as I know)

A Simple Solution

I've written a simple script for these procedures to do all those work. You just have to set the name and value of your environment variable.

#!/bin/bash
echo "Enter variable name: "
read variable_name
echo "Enter variable value: "
read variable_value
echo "adding " $variable_name " to environment variables: " $variable_value
echo "export "$variable_name"="$variable_value>>~/.bashrc
echo $variable_name"="$variable_value>>~/.profile
echo $variable_name"="$variable_value>>/etc/environment
source ~/.bashrc
source ~/.profile
echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"
read restart
case $restart in
    y) sudo shutdown -r 0;;
    n) echo "don't forget to restart your computer manually";;
esac
exit

Save these lines in a shfile then make it executable and just run it!

Get all dates between two dates in SQL Server

You can try this:

    SET LANGUAGE SPANISH

DECLARE @startDate DATE = GETDATE() -- Your start date
DECLARE @endDate DATE = DATEADD(MONTH, 16, GETDATE()) -- Your end date
DECLARE @years INT = YEAR(@endDate) - YEAR(@startDate)

CREATE TABLE #TMP_YEARS (
    [year] INT
)

-- Get all posible years between the start and end date
WHILE @years >= 0
BEGIN
    INSERT INTO #TMP_YEARS
    ([year])
    SELECT YEAR(@startDate) + @years

    SET @years = @years - 1
END

;WITH [days]([day]) AS -- Posible days at a month
(
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL -- days lower than 10
    SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL -- days lower than 20
    SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29 UNION ALL -- days lower than 30
    SELECT 30 UNION ALL SELECT 31 -- days higher 30
),
[months]([month]) AS -- All months at a year
(
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
)
SELECT CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) as [date]
  FROM #TMP_YEARS a
 CROSS JOIN [months] n -- Join all years with all months
 INNER JOIN [days] d on DAY(EOMONTH(CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + CONVERT(VARCHAR, DAY(EOMONTH(CAST(CONVERT(VARCHAR, a.[year]) + '-' + CONVERT(varchar, n.[month]) + '-15' AS DATE)))))) >= d.[day] AND -- The number of the day can't be higher than the last day of the current month and the current year
                      CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) <= ISNULL(@endDate, GETDATE()) AND -- The current date can't be higher than the end date
                      CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) >= ISNULL(@startDate, GETDATE()) -- The current date should be higher than the start date
 ORDER BY a.[year] ASC, n.[month] ASC, d.[day] ASC

The output will be something like this, you can format the date as you like:

2019-01-24
2019-01-25
2019-01-26
2019-01-27
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06
2019-02-07
2019-02-08
2019-02-09
...

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

Does Python have an ordered set?

The ParallelRegression package provides a setList( ) ordered set class that is more method-complete than the options based on the ActiveState recipe. It supports all methods available for lists and most if not all methods available for sets.

Converting string to date in mongodb

Using MongoDB 4.0 and newer

The $toDate operator will convert the value to a date. If the value cannot be converted to a date, $toDate errors. If the value is null or missing, $toDate returns null:

You can use it within an aggregate pipeline as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": {
            "$toDate": "$created_at"
        }
    } }
])

The above is equivalent to using the $convert operator as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$convert": { 
                "input": "$created_at", 
                "to": "date" 
            } 
        }
    } }
])

Using MongoDB 3.6 and newer

You cab also use the $dateFromString operator which converts the date/time string to a date object and has options for specifying the date format as well as the timezone:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$dateFromString": { 
                "dateString": "$created_at",
                "format": "%m-%d-%Y" /* <-- option available only in version 4.0. and newer */
            } 
        }
    } }
])

Using MongoDB versions >= 2.6 and < 3.2

If MongoDB version does not have the native operators that do the conversion, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents. Withing the loop, convert the field to an ISODate object and then update the field using the $set operator, as in the following example where the field is called created_at and currently holds the date in string format:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    db.collection.update(
        {"_id" : doc._id}, 
        {"$set" : {"created_at" : new ISODate(doc.created_at)}}
    ) 
};

For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new ISODate(doc.created_at);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

Using MongoDB 3.2

The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [],
    cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});

cursor.forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );

    if (bulkOps.length === 500) {
        db.collection.bulkWrite(bulkOps);
        bulkOps = [];
    }     
});

if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps);

How to return a specific element of an array?

You code should look like this:

public int getElement(int[] arrayOfInts, int index) {
    return arrayOfInts[index];
}

Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.

What's the scope of a variable initialized in an if statement?

Yes, they're in the same "local scope", and actually code like this is common in Python:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.

In other words, Python does not have block-level scopes. Be careful, though, with examples such as

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

Populate nested array in mongoose

Mongoose 4.5 support this

Project.find(query)
  .populate({ 
     path: 'pages',
     populate: {
       path: 'components',
       model: 'Component'
     } 
  })
  .exec(function(err, docs) {});

And you can join more than one deep level

How to use bootstrap-theme.css with bootstrap 3?

Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.

Removing double quotes from variables in batch file creates problems with CMD environment

This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.

C++11 reverse range-based for-loop

This should work in C++11 without boost:

namespace std {
template<class T>
T begin(std::pair<T, T> p)
{
    return p.first;
}
template<class T>
T end(std::pair<T, T> p)
{
    return p.second;
}
}

template<class Iterator>
std::reverse_iterator<Iterator> make_reverse_iterator(Iterator it)
{
    return std::reverse_iterator<Iterator>(it);
}

template<class Range>
std::pair<std::reverse_iterator<decltype(begin(std::declval<Range>()))>, std::reverse_iterator<decltype(begin(std::declval<Range>()))>> make_reverse_range(Range&& r)
{
    return std::make_pair(make_reverse_iterator(begin(r)), make_reverse_iterator(end(r)));
}

for(auto x: make_reverse_range(r))
{
    ...
}

How to bind event listener for rendered elements in Angular 2?

HostListener should be the proper way to bind event into your component:

@Component({
  selector: 'your-element'
})

export class YourElement {
  @HostListener('click', ['$event']) onClick(event) {
     console.log('component is clicked');
     console.log(event);
  }
}

Cannot open output file, permission denied

This error usually occurs when the IDE has a problem due to a crash or other failure and it still has a hold on the EXE, preventing the user (yourself) from overwriting / deleting the EXE during a rebuild.

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

ElasticSearch: Unassigned Shards, how to fix?

This little bash script will brute force reassign, you may lose data.

NODE="YOUR NODE NAME"
IFS=$'\n'
for line in $(curl -s 'localhost:9200/_cat/shards' | fgrep UNASSIGNED); do
  INDEX=$(echo $line | (awk '{print $1}'))
  SHARD=$(echo $line | (awk '{print $2}'))

  curl -XPOST 'localhost:9200/_cluster/reroute' -d '{
     "commands": [
        {
            "allocate": {
                "index": "'$INDEX'",
                "shard": '$SHARD',
                "node": "'$NODE'",
                "allow_primary": true
          }
        }
    ]
  }'
done

File being used by another process after using File.Create()

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

What is the difference between server side cookie and client side cookie?

HTTP COOKIES

Cookies are key/value pairs used by websites to store state information on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store information on the browser.

Browser request example:

GET /index.html HTTP/1.1
Host: www.example.com

Example answer from the server:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest  of the response

Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.

GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*

SESSIONS: Server side cookies

Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.

Examples of usage

You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...

Pros and Cons

Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.

Cookie Pros:

  • scalability: all the data is stored in the browser so each request can go through a load balancer to different webservers and you have all the information needed to fullfill the request;
  • they can be accessed via javascript on the browser;
  • not being on the server they will survive server restarts;
  • RESTful: requests don't depend on server state

Cookie Cons:

Session Pros:

  • generally easier to use, in PHP there's probably not much difference.
  • unlimited storage

Session Cons:

  • more difficult to scale
  • on web server restarts you can lose all sessions or not depending on the implementation
  • not RESTful

Vim 80 column layout concerns

You can try this to set the window size to allow 80 characters of actual text. This still doesn't work with vertical splits though.

let &co=80 + &foldcolumn + (&number || &relativenumber ? &numberwidth : 0)

This requires vim 7+, 7.3 for relativenumber.

What is the difference between single and double quotes in SQL?

I use this mnemonic:

  • Single quotes are for strings (one thing)
  • Double quotes are for tables names and column names (two things)

This is not 100% correct according to the specs, but this mnemonic helps me (human being).

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

How do I use hexadecimal color strings in Flutter?

import 'package:flutter/material.dart';
class HexToColor extends Color{
  static _hexToColor(String code) {
    return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
  }
  HexToColor(final String code) : super(_hexToColor(code));
}

Import the new class and use it like this HexToColor('#F2A03D')

top nav bar blocking top content of the page

As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:

<style> 
    body {
        padding-top: 60px;
    }
</style>

Like so:

<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    body {
        padding-top: 60px;
    }
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />

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

This can be caused by a bum applicationhost.config entry.

Stop IIS Express if it's running (right-click the light-blue scroll-thingy icon in the Windows System Tray; Exit).

Go to your project's Properties > Web, and check that the Project Url is correct. In case of an https url, make sure it includes a port number in the valid range. A correct URL could be: https://localhost:44300/. Now press the "Create Virtual Directory"-button next to the URL. This adds a new entry to applicationhost.config.

Start the project again and hopefully you will no longer get the error.

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

What is the difference between attribute and property?

In Java (or other languages), using Property/Attribute depends on usage:

  • Property used when value doesn't change very often (usually used at startup or for environment variable)

  • Attributes is a value (object child) of an Element (object) which can change very often/all the time and be or not persistent

ping response "Request timed out." vs "Destination Host unreachable"

Destination Host Unreachable

This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.

If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.

If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.

Request Timed Out

This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.

For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx

How to open .dll files to see what is written inside?

you are better off with a decompiler like redgates .net reflector or jetbrains resharper decompiler. there are open source ones also like

http://www.jetbrains.com/decompiler/

http://ilspy.net/

Adding to a vector of pair

Read the following documentation:

http://cplusplus.com/reference/std/utility/make_pair/

or

http://en.cppreference.com/w/cpp/utility/pair/make_pair

I think that will help. Those sites are good resources for C++, though the latter seems to be the preferred reference these days.

ASP.NET MVC - Set custom IIdentity or IPrincipal

As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

So in your code behind you can simply access:

User.FirstName or User.LastName

What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?

Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles, User.Tasks, User.HasPath(int) , User.Settings.Timeout and many other nice things)

How to remove provisioning profiles from Xcode

For XCode 9.3, the following steps worked for me.

  1. Go to Applications > Utilities > Keychain Access
  2. Under the login option on the left panel, find Apple Worldwide Developer Relations Certification Authority. Double click to get the options under it.
  3. Under the Trust option, change the When using this certificate option to Always trust .
  4. Exit the keychain access window, quit Xcode and restart Xcode. Rebuild the application. It should work now.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

UPDATE 11/22/2013 - this is the latest WebApi package:

Install-Package Microsoft.AspNet.WebApi

Original answer (this is an older WebApi package)

Install-Package AspNetWebApi

More details.

Java Object Null Check for method

Inside your for-loop, just add the following line:

if(books[i] != null) {
     total += books[i].getPrice();
}

Android Studio - local path doesn't exist

I solved this problem by stopping the gradle deamon by typing ./gradlew -stop into the terminal

How to specify legend position in matplotlib in graph coordinates

According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.

Checking length of dictionary object

Count and show keys in a dictionary (run in console):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

function size_dict(d){c=0; for (i in d) ++c; return c}

How to get the name of the current Windows user in JavaScript

Working for me on IE:

<script type="text/javascript">
  var WinNetwork = new ActiveXObject("WScript.Network");
  document.write(WinNetwork.UserName);
</script>

...but ActiveX controls needs to be on in security settings.

Overriding !important style

If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.

See this page with information on how to create a user style

Convert categorical data in pandas dataframe

For converting categorical data in column C of dataset data, we need to do the following:

from sklearn.preprocessing import LabelEncoder 
labelencoder= LabelEncoder() #initializing an object of class LabelEncoder
data['C'] = labelencoder.fit_transform(data['C']) #fitting and transforming the desired categorical column.

Center div on the middle of screen

Your code is correct you just used .div instead of div

HTML

<div class="ui grid container">
<div class="ui center aligned three column grid">
  <div class="column">
  </div>
  <div class="column">
    </div>
  </div>

CSS

div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}

Check out this Fiddle

How do you post data with a link

I would just use a value in the querystring to pass the required information to the next page.

Modulo operator with negative values

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

How to detect if a browser is Chrome using jQuery?

userAgent can be changed. for more robust, use the global variable specified by chrome

$.browser.chrome = (typeof window.chrome === "object");

java.util.Date to XMLGregorianCalendar

A one line example using Joda-Time library:

XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(new DateTime().toGregorianCalendar());

Credit to Nicolas Mommaerts from his comment in the accepted answer.

The transaction manager has disabled its support for remote/network transactions

In case others have the same issue:

I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.

How to get PID of process I've just started within java program?

If portability is not a concern, and you just want to get the pid on Windows without a lot of hassle while using code that is tested and known to work on all modern versions of Windows, you can use kohsuke's winp library. It is also available on Maven Central for easy consumption.

Process process = //...;
WinProcess wp = new WinProcess(process);
int pid = wp.getPid();

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

1 = false and 0 = true?

It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Accessing a Dictionary.Keys Key through a numeric index

You could always do this:

string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]

But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys on MSDN is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

How do you use variables in a simple PostgreSQL script?

I've came across some other documents which they use \set to declare scripting variable but the value is seems to be like constant value and I'm finding for way that can be acts like a variable not a constant variable.

Ex:

\set Comm 150

select sal, sal+:Comm from emp

Here sal is the value that is present in the table 'emp' and comm is the constant value.

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

Enforcing the type of the indexed members of a Typescript object?

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

Rerouting stdin and stdout from C

I think you're looking for something like freopen()

How to use Git?

this is my blog on git and its for beginners who want to get started on git. https://techxposers.com/git-for-beginners/

What is the easiest way to initialize a std::vector with hardcoded elements?

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How to code a very simple login system with java

Map<String, String> d = new HashMap<>();

void input(String u, String p, String e) {
    read();
    if (e.equals("login")) login(u, p);
    else if (e.equals("register")) register(u, p);
    write();
}

void read() {
    d = new HashMap<>();
    String s = "";
    try {
        s = new String(Files.readAllBytes(Paths.get("data.txt")));
    }catch(IOException e) {
        e.printStackTrace();
    }
    String [] pairs = s.split("\n");
    for (int i = 0; i < pairs.length; i++) {
        d.put(pairs[i].split(",")[0], pairs[i].split(",")[1]);
    }
}

void write() {
    try (FileWriter m = new FileWriter("data.txt")) {
        for (Map.Entry<String, String> entry : d.entrySet()) {
            m.write(entry.getKey() + "," + entry.getValue() + "\n");    
        }
        m.close();
    }catch (IOException e) {
        e.printStackTrace();
    }
}

boolean login(String u, String p) {
    return (d.get(u).equals(p)) ? true : false;
}

boolean register(String u, String p) {
    if (d.containsKey(u)) return false;
    d.put(u, p);
    return true;
}

How to do multiple arguments to map function where one remains the same in python?

Map can contain multiple arguments, the standard way is

map(add, a, b)

In your question, it should be

map(add, a, [2]*len(a))

Add a CSS border on hover without moving the element

Try this it might solve your problem.

Css:

.item{padding-top:1px;}

.jobs .item:hover {
    background: #e1e1e1;
    border-top: 1px solid #d0d0d0;
    padding-top:0;
}

HTML:

<div class="jobs">
    <div class="item">
        content goes here
    </div>
</div>

See fiddle for output: http://jsfiddle.net/dLDNA/

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Limiting only to Swagger related resources:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");

Unsupported major.minor version 52.0 when rendering in Android Studio

Make sure to do a clean build after changing a version of Java. As it turns out Android Studio does some work when you switch the JDK but doesn't clean the workspace and creates confusion ¯\_(?)_/¯

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

How to sort a Collection<T>?

Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }

Clear MySQL query cache without restarting server

In my system (Ubuntu 12.04) I found RESET QUERY CACHE and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

and then reset the query cache in mysql client:

RESET QUERY CACHE;

How do you close/hide the Android soft keyboard using Java?

Just call the below method it will hide your keyboard if its showing.

public void hideKeyboard() {
    try {
        InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputmanager != null) {
            inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    } catch (Exception var2) {
    }

}

How to programmatically add controls to a form in VB.NET

Dim numberOfButtons As Integer
Dim buttons() as Button

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Redim buttons(numberOfbuttons)
    for counter as integer = 0 to numberOfbuttons
        With buttons(counter)
           .Size = (10, 10)
           .Visible = False
           .Location = (55, 33 + counter*13)
           .Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
           'any other property
        End With
        '
    next
End Sub

If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.

If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:

AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked 

then create

Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
     'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub

when you call: objectYouCall.numberOfButtons = initial_value_from_main_program

response_yes_or_no_or_other = objectYouCall.ShowDialog()

For radio buttons, textboxes, same story, different ending.

How to create an installer for a .net Windows Service using Visual Studio

In the service project do the following:

  1. In the solution explorer double click your services .cs file. It should bring up a screen that is all gray and talks about dragging stuff from the toolbox.
  2. Then right click on the gray area and select add installer. This will add an installer project file to your project.
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). You should then setup the properties as you need such as service name and user that it should run as.

Now you need to make a setup project. The best thing to do is use the setup wizard.

  1. Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard

    a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer

  2. On the second step select "Create a Setup for a Windows Application."

  3. On the 3rd step, select "Primary output from..."

  4. Click through to Finish.

Next edit your installer to make sure the correct output is included.

  1. Right click on the setup project in your Solution Explorer.
  2. Select View > Custom Actions. (In VS2008 it might be View > Editor > Custom Actions)
  3. Right-click on the Install action in the Custom Actions tree and select 'Add Custom Action...'
  4. In the "Select Item in Project" dialog, select Application Folder and click OK.
  5. Click OK to select "Primary output from..." option. A new node should be created.
  6. Repeat steps 4 - 5 for commit, rollback and uninstall actions.

You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name, Title, Manufacturer, etc...

Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.

SyntaxError: Cannot use import statement outside a module

in the package.json write { "type": "module" }

it fixed my problem, I had the same problem

JUnit Testing Exceptions

Though @Test(expected = MyException.class) and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:

@Test public void yourTest() {
  try {
    systemUnderTest.doStuff();
    fail("MyException expected.");
  } catch (MyException expected) {

    // Though the ExpectedException rule lets you write matchers about
    // exceptions, it is sometimes useful to inspect the object directly.

    assertEquals(1301, expected.getMyErrorCode());
  }

  // In both @Test(expected=...) and ExpectedException code, the
  // exception-throwing line will be the last executed line, because Java will
  // still traverse the call stack until it reaches a try block--which will be
  // inside the JUnit framework in those cases. The only way to prevent this
  // behavior is to use your own try block.

  // This is especially useful to test the state of the system after the
  // exception is caught.

  assertTrue(systemUnderTest.isInErrorState());
}

Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final methods.

DLL load failed error when importing cv2

This error can be caused by missing the following dll enter image description here

To have this dll install: https://www.microsoft.com/en-us/software-download/mediafeaturepack as already explained above

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How can building a heap be O(n) time complexity?

It would be O(n log n) if you built the heap by repeatedly inserting elements. However, you can create a new heap more efficiently by inserting the elements in arbitrary order and then applying an algorithm to "heapify" them into the proper order (depending on the type of heap of course).

See http://en.wikipedia.org/wiki/Binary_heap, "Building a heap" for an example. In this case you essentially work up from the bottom level of the tree, swapping parent and child nodes until the heap conditions are satisfied.

How to check sbt version?

From within the sbt shell

sbt:venkat> about
[info] This is sbt 1.3.3
...

403 Forbidden vs 401 Unauthorized HTTP responses

These are the meanings:

401: User not (correctly) authenticated, the resource/page require authentication

403: User authenticated, but his role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators

How can I get the behavior of GNU's readlink -f on a Mac?

Since my work is used by people with non-BSD Linux as well as macOS, I've opted for using these aliases in our build scripts (sed included since it has similar issues):

##
# If you're running macOS, use homebrew to install greadlink/gsed first:
#   brew install coreutils
#
# Example use:
#   # Gets the directory of the currently running script
#   dotfilesDir=$(dirname "$(globalReadlink -fm "$0")")
#   alias al='pico ${dotfilesDir}/aliases.local'
##

function globalReadlink () {
  # Use greadlink if on macOS; otherwise use normal readlink
  if [[ $OSTYPE == darwin* ]]; then
    greadlink "$@"
  else
    readlink "$@"
  fi
}

function globalSed () {
  # Use gsed if on macOS; otherwise use normal sed
  if [[ $OSTYPE == darwin* ]]; then
    gsed "$@"
  else
    sed "$@"
  fi
}

Optional check you could add to automatically install homebrew + coreutils dependencies:

if [[ "$OSTYPE" == "darwin"* ]]; then
  # Install brew if needed
  if [ -z "$(which brew)" ]; then 
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"; 
  fi
  # Check for coreutils
  if [ -z "$(brew ls coreutils)" ]; then
    brew install coreutils
  fi
fi

I suppose to be truly "global" it needs to check others...but that probably comes close to the 80/20 mark.

NOT IN vs NOT EXISTS

If the execution planner says they're the same, they're the same. Use whichever one will make your intention more obvious -- in this case, the second.

Way to create multiline comments in Bash?

Here's how I do multiline comments in bash.

This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.

Running that example will produce this output:

foo {
./example: line 5: fn: command not found
foo }
can't happen

How to convert Moment.js date to users local timezone?

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();

From there you can use any of the functions you might expect:

var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...

Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

var localDate = moment("2015-01-30T10:00:00Z");

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

Finding moving average from data points in Python

As numpy.convolve is pretty slow, those who need a fast performing solution might prefer an easier to understand cumsum approach. Here is the code:

cumsum_vec = numpy.cumsum(numpy.insert(data, 0, 0)) 
ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width

where data contains your data, and ma_vec will contain moving averages of window_width length.

On average, cumsum is about 30-40 times faster than convolve.

PHP: Inserting Values from the Form into MySQL

<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");

?>



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
 //$("form").submit(function(e){

     $("#btn1").click(function(e){
     e.preventDefault();
    // alert('here');
        $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');

    });
    //}
});
</script>

</head>

<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>

<tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
<tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){


move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);

                     $fname = $_FILES['e5']['name'][$key];
                     $imgarryimp[]=$fname;
                     //echo $fname;

                     if(strlen($fname)>0)
                      {
                         $img = $fname;
                      }
                      $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
}
exit;





                      // echo $values;exit;
                      //foreach($_POST['e1'] as $row) 
    //{ 

    $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
    //}
    //exit;


}
?>

</form>

<table>
<?php 
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>

</body>
</html>

Check if my SSL Certificate is SHA1 or SHA2

Update: The site below is no longer running because, as they say on the site:

As of January 1, 2016, no publicly trusted CA is allowed to issue a SHA-1 certificate. In addition, SHA-1 support was removed by most modern browsers and operating systems in early 2017. Any new certificate you get should automatically use a SHA-2 algorithm for its signature.

Legacy clients will continue to accept SHA-1 certificates, and it is possible to have requested a certificate on December 31, 2015 that is valid for 39 months. So, it is possible to see SHA-1 certificates in the wild that expire in early 2019.

Original answer:

You can also use https://shaaaaaaaaaaaaa.com/ - set up to make this particular task easy. The site has a text box - you type in your site domain name, click the Go button and it then tells you whether the site is using SHA1 or SHA2.

Background

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

ValueError when checking if variable is None or numpy.array

You can see if object has shape or not

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

This will show you past and previous time formats like '2 days ago' '10 minutes from now' and you can pass it either a Date object, a numeric timestamp or a date string

_x000D_
_x000D_
function time_ago(time) {_x000D_
_x000D_
  switch (typeof time) {_x000D_
    case 'number':_x000D_
      break;_x000D_
    case 'string':_x000D_
      time = +new Date(time);_x000D_
      break;_x000D_
    case 'object':_x000D_
      if (time.constructor === Date) time = time.getTime();_x000D_
      break;_x000D_
    default:_x000D_
      time = +new Date();_x000D_
  }_x000D_
  var time_formats = [_x000D_
    [60, 'seconds', 1], // 60_x000D_
    [120, '1 minute ago', '1 minute from now'], // 60*2_x000D_
    [3600, 'minutes', 60], // 60*60, 60_x000D_
    [7200, '1 hour ago', '1 hour from now'], // 60*60*2_x000D_
    [86400, 'hours', 3600], // 60*60*24, 60*60_x000D_
    [172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2_x000D_
    [604800, 'days', 86400], // 60*60*24*7, 60*60*24_x000D_
    [1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2_x000D_
    [2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7_x000D_
    [4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2_x000D_
    [29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4_x000D_
    [58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2_x000D_
    [2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12_x000D_
    [5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2_x000D_
    [58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100_x000D_
  ];_x000D_
  var seconds = (+new Date() - time) / 1000,_x000D_
    token = 'ago',_x000D_
    list_choice = 1;_x000D_
_x000D_
  if (seconds == 0) {_x000D_
    return 'Just now'_x000D_
  }_x000D_
  if (seconds < 0) {_x000D_
    seconds = Math.abs(seconds);_x000D_
    token = 'from now';_x000D_
    list_choice = 2;_x000D_
  }_x000D_
  var i = 0,_x000D_
    format;_x000D_
  while (format = time_formats[i++])_x000D_
    if (seconds < format[0]) {_x000D_
      if (typeof format[2] == 'string')_x000D_
        return format[list_choice];_x000D_
      else_x000D_
        return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;_x000D_
    }_x000D_
  return time;_x000D_
}_x000D_
_x000D_
var aDay = 24 * 60 * 60 * 1000;_x000D_
console.log(time_ago(new Date(Date.now() - aDay)));_x000D_
console.log(time_ago(new Date(Date.now() - aDay * 2)));
_x000D_
_x000D_
_x000D_

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

error: package com.android.annotations does not exist

For me it was an old version of npm.

Run npm install npm@latest -g and then npm install

Is there a Google Chrome-only CSS hack?

I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...

.style {
color: green;
(-bracket-:hack;
    color: red;
);
}

From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

How to add facebook share button on my website?

Share Dialog without requiring Facebook login

You can Trigger a Share Dialog using the FB.ui function with the share method parameter to share a link. This dialog is available in the Facebook SDKs for JavaScript, iOS, and Android by performing a full redirect to a URL.

You can trigger this call:

FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/', // Link to share
}, function(response){});

You can also include open graph meta tags on the page at this URL to customise the story that is shared back to Facebook.

Note that response.error_message will appear only if someone using your app has authenticated your app with Facebook Login.

Also you can directly share link with call by having Javascript Facebook SDK.

https://www.facebook.com/dialog/share&app_id=145634995501895&display=popup&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer

https://www.facebook.com/dialog/share&app_id={APP_ID}&display=popup&href={LINK_TO_SHARE}&redirect_uri={REDIRECT_AFTER_SHARE}
  • app_id => Your app's unique identifier. (Required.)

  • redirect_uri => The URL to redirect to after a person clicks a button on the dialog. Required when using URL redirection.

  • display => Determines how the dialog is rendered.

If you are using the URL redirect dialog implementation, then this will be a full page display, shown within Facebook.com. This display type is called page. If you are using one of our iOS or Android SDKs to invoke the dialog, this is automatically specified and chooses an appropriate display type for the device. If you are using the Facebook SDK for JavaScript, this will default to a modal iframe type for people logged into your app or async when using within a game on Facebook.com, and a popup window for everyone else. You can also force the popup or page types when using the Facebook SDK for JavaScript, if necessary. Mobile web apps will always default to the touch display type. share Parameters

  • href => The link attached to this post. Required when using method share. Include open graph meta tags in the page at this URL to customize the story that is shared.

Python Request Post with param data

Set data to this:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

How to deploy correctly when using Composer's develop / production switch?

Now require-dev is enabled by default, for local development you can do composer install and composer update without the --dev option.

When you want to deploy to production, you'll need to make sure composer.lock doesn't have any packages that came from require-dev.

You can do this with

composer update --no-dev

Once you've tested locally with --no-dev you can deploy everything to production and install based on the composer.lock. You need the --no-dev option again here, otherwise composer will say "The lock file does not contain require-dev information".

composer install --no-dev

Note: Be careful with anything that has the potential to introduce differences between dev and production! I generally try to avoid require-dev wherever possible, as including dev tools isn't a big overhead.

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

Hidden Features of Xcode

Key bindings to Xcode actions

I also adore the "re-indent". True there is no default shortcut, but you can add one from the Text Key Bindings tab of the Key Bindings preference pane.

Which is a time-saver all on its own. Just lookup your favorite actions and add/edit keyboard shortcuts!

One set of defaults I do find handy are the CMD+" and CMD+' to add/remove vertical splits. Hold down option for these and now you have the same for horizontal. But if these gestures don't work for you, you can always change them.

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How can I delete all cookies with JavaScript?

This is a function we are using in our application and it is working fine.

delete cookie: No argument method

function clearListCookies()
{   
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++)
    {   
        var spcook =  cookies[i].split("=");
        deleteCookie(spcook[0]);
    }
    function deleteCookie(cookiename)
    {
        var d = new Date();
        d.setDate(d.getDate() - 1);
        var expires = ";expires="+d;
        var name=cookiename;
        //alert(name);
        var value="";
        document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
    }
    window.location = ""; // TO REFRESH THE PAGE
}

Edit: This will delete the cookie by setting it to yesterday's date.

What's the right way to create a date in Java?

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

So, I ran into this same issue. The problem I was having here was that my database wasn't properly synced. Simple problems always seem to cause the most angst...

To sync your django db, from within your app directory, within terminal, type:

$ python manage.py syncdb

Edit: Note that if you are using django-south, running the '$ python manage.py migrate' command may also resolve this issue.

Happy coding!

Apache shutdown unexpectedly

Stop the IIS service. It should work then

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Remove stubborn underline from link

As others pointed out, it seems like you can't override nested text-decoration styles... BUT you can change the text-decoration-color.

As a hack, I changed the color to be transparent:

text-decoration-color: transparent;

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Perl one-liner would be a simple version of Maxim's solution

perl -MList::Util=shuffle -e 'print shuffle(<STDIN>);' < myfile

How do I see the extensions loaded by PHP?

  <?php 
      echo "<pre>";
      print_r(get_loaded_extensions());
      echo "<pre/>";
 ?>

Powershell folder size of folders without listing Subdirectories

This is something I wind up looking for repeatedly, even though I wrote myself a nice little function a while ago. So, I figured others might benefit from having it and maybe I'll even find it here, myself. hahaha

It's pretty simple to paste into your script and use. Just pass it a folder object.

I think it requires PowerShell 3 just because of the -directory flag on the Get-ChildItem command, but I'm sure it can be easily adapted, if need be.

function Get-TreeSize ($folder = $null)
{
    #Function to get recursive folder size
    $result = @()
    $folderResult = "" | Select-Object FolderPath, FolderName, SizeKB, SizeMB, SizeGB, OverThreshold

    $contents  = Get-ChildItem $folder.FullName -recurse -force -erroraction SilentlyContinue -Include * | Where-Object {$_.psiscontainer -eq $false} | Measure-Object -Property length -sum | Select-Object sum
    $sizeKB = [math]::Round($contents.sum / 1000,3)   #.ToString("#.##")
    $sizeMB = [math]::Round($contents.sum / 1000000,3)   #.ToString("#.##")
    $sizeGB = [math]::Round($contents.sum / 1000000000,3)   #.ToString("#.###")

    $folderResult.FolderPath = $folder.FullName
    $folderResult.FolderName = $folder.BaseName
    $folderResult.SizeKB = $sizeKB
    $folderresult.SizeMB = $sizeMB
    $folderresult.SizeGB = $sizeGB
    $result += $folderResult

    return $result
} 


#Use the function like this for a single directory
$topDir = get-item "C:\test"
Get-TreeSize ($topDir)

#Use the function like this for all top level folders within a direcotry
#$topDir = gci -directory "\\server\share\folder"
$topDir = Get-ChildItem -directory "C:\test"
foreach ($folderPath in $topDir) {Get-TreeSize $folderPath}  

How to make git mark a deleted and a new file as a file move?

Do the move and the modify in separate commits.

How do I create a master branch in a bare Git repository?

You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

Prepare a dummy directory:

$ rm -rf /tmp/empty_directory
$ mkdir  /tmp/empty_directory

Create the master branch without a parent (works even on a completely empty repo):

$ cd your-bare-repository.git

$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master'                  <--- abort if "master" already exists

Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 

$ git branch
* master

Clean up the directory, it is still empty.

$ rmdir  /tmp/empty_directory

Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

jQuery form input select by id

You can just target the id directly:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

var value = $('#a #b').val();

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

Getting the IP address of the current machine using Java

This could be a bit tricky in the most general case.

On the face of it, InetAddress.getLocalHost() should give you the IP address of this host. The problem is that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable outside of your machine or your LAN. For example, they could be IP addresses for virtual network devices, private network IP addresses, and so on.

What this means is that the IP address returned by InetAddress.getLocalHost() might not be the right one to use.

How can you deal with this?

  • One approach is to use NetworkInterface.getNetworkInterfaces() to get all of the known network interfaces on the host, and then iterate over each NI's addresses.
  • Another approach is to (somehow) get the externally advertized FQDN for the host, and use InetAddress.getByName() to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?)
  • A variation of the previous is to get the preferred FQDN from a config file or a command line parameter.
  • Another variation is to get the preferred IP address from a config file or a command line parameter.

In summary, InetAddress.getLocalHost() will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with "complicated" networking.


I am able to get all the IP addresses associated all Network Interfaces, but how do i distinguish them?

  • Any address in the range 127.xxx.xxx.xxx is a "loopback" address. It is only visible to "this" host.
  • Any address in the range 192.168.xxx.xxx is a private (aka site local) IP address. These are reserved for use within an organization. The same applies to 10.xxx.xxx.xxx addresses, and 172.16.xxx.xxx through 172.31.xxx.xxx.
  • Addresses in the range 169.254.xxx.xxx are link local IP addresses. These are reserved for use on a single network segment.
  • Addresses in the range 224.xxx.xxx.xxx through 239.xxx.xxx.xxx are multicast addresses.
  • The address 255.255.255.255 is the broadcast address.
  • Anything else should be a valid public point-to-point IPv4 address.

In fact, the InetAddress API provides methods for testing for loopback, link local, site local, multicast and broadcast addresses. You can use these to sort out which of the IP addresses you get back is most appropriate.

Add column with constant value to pandas dataframe

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

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

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

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

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

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

Note for object columns

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

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

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

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

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

df.assign(new='y')

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

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

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

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

Multiple column assignment

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

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

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

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Android Viewpager as Image Slide Gallery

enter code here   public Timer timer;
public TimerTask task;
public ImageView slidingimage;

private int[] IMAGE_IDS = {
        R.drawable.home_banner1, R.drawable.home_banner2, R.drawable.home_banner3
    };

enter code here   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

     final Handler mHandler = new Handler();

        // Create runnable for posting
        final Runnable mUpdateResults = new Runnable() {
            public void run() {

                AnimateandSlideShow();

            }
        };
        int delay = 2000; // delay for 1 sec.

        int period = 2000; // repeat every 4 sec.

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {

             mHandler.post(mUpdateResults);

        }

        }, delay, period);

enter code here     private void AnimateandSlideShow() {

        slidingimage = (ImageView)findViewById(R.id.banner);
        slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);

        currentimageindex++;

        Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);

          slidingimage.startAnimation(rotateimage);

    }

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

How to always show the vertical scrollbar in a browser?

Just use CSS.

body {
  overflow-y: scroll;
}

This application has no explicit mapping for /error

Do maven clean or clean verify and try to run it.The instances has to be cleaned before deploying the another project. It worked for me. I tried it for 2 days to understand this.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

git checkout all the files

If you are at the root of your working directory, you can do git checkout -- . to check-out all files in the current HEAD and replace your local files.

You can also do git reset --hard to reset your working directory and replace all changes (including the index).

How to attach a file using mail command on Linux?

With mailx you can do:

mailx -s "My Subject"  -a ./mail_att.csv -S [email protected]  [email protected] < ./mail_body.txt

This worked great on our GNU Linux servers, but unfortunately my dev environment is Mac OsX which only has a crummy old BSD version of mailx. Normally I use Coreutils to get better versions of unix commands than the Mac BSD ones, but mailx is not in Coreutils.

I found a solution from notpeter in an unrelated thread (https://serverfault.com/questions/196001/using-unix-mail-mailx-with-a-modern-mail-server-imap-instead-of-mbox-files) which was to download the Heirloom mailx OSX binary package from http://www.tramm.li/iWiki/HeirloomNotes.html. It has a more featured mailx which can handle the above command syntax.

(Apologies for poor cross linking linking or attribution, I'm new to the site.)

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
    {
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
            Math.Cos(longitudeDifferenceInRadians));

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
    }

    private static double ToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

How to return the output of stored procedure into a variable in sql server

With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)

From this: 
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)

To this:
declare @t table(id int) 
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)

Variable name as a string in Javascript

I needed this, don't want to use objects, and came up with the following solution, turning the question around.

Instead of converting the variable name into a string, I convert a string into a variable.

This only works if the variable name is known of course.

Take this:

var height = 120;
testAlert(height);

This should display:

height: 120

This can be done like this:

function testAlert(ta)
{
    a = window[ta];
    alert(ta + ': ' + a); 
}

var height = 120;
testAlert("height");
// displays: height: 120

So I use the string "height" and turn that into a variable height using the window[] command.

Where can I get a list of Countries, States and Cities?

geonames.org has an api and a data dump of worldwide geographical places.

Python: No acceptable C compiler found in $PATH when installing python

sudo apt install build-essential is the command

But if you get the "the package can be found" kind of error, Run

  • sudo apt update first
  • then sudo apt install build-essential

This worked for me.

How to set standard encoding in Visual Studio

The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.

I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:

Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/

The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".

Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.

Good tool to visualise database schema?

ER/Studio by Embarcadero is one of the costlier ones, but the hierarchical mode it present is by far the best one for understanding database models. It makes query writing the easiest task in the world.

It also is incredible with normalization, denormalization, warehousing, documentation, etc.

The downside is that it is a pretty expensive tool especially when you go multiplatform.

What is the difference between compileSdkVersion and targetSdkVersion?

compileSdkVersion

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.

targetSdkVersion

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.

For example, as the documentation states:

For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...

The Android OS, at runtime, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.

For all practical purposes, most apps are going to want to set targetSdkVersion to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion, it defaults to the minSdkVersion.

RESTful URL design for search

RESTful does not recommend using verbs in URL's /cars/search is not restful. The right way to filter/search/paginate your API's is through Query Parameters. However there might be cases when you have to break the norm. For example, if you are searching across multiple resources, then you have to use something like /search?q=query

You can go through http://saipraveenblog.wordpress.com/2014/09/29/rest-api-best-practices/ to understand the best practices for designing RESTful API's

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

How to import local packages in go?

Import paths are relative to your $GOPATH and $GOROOT environment variables. For example, with the following $GOPATH:

GOPATH=/home/me/go

Packages located in /home/me/go/src/lib/common and /home/me/go/src/lib/routers are imported respectively as:

import (
    "lib/common"
    "lib/routers"
)

Print the data in ResultSet along with column names

For those who wanted more better version of the resultset printing as util class This was really helpful for printing resultset and does many things from a single util... thanks to Hami Torun!

In this class printResultSet uses ResultSetMetaData in a generic way have a look at it..


import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public final class DBTablePrinter {

    /**
     * Column type category for CHAR, VARCHAR
     * and similar text columns.
     */
    public static final int CATEGORY_STRING = 1;
    /**
     * Column type category for TINYINT, SMALLINT,
     * INT and BIGINT columns.
     */
    public static final int CATEGORY_INTEGER = 2;
    /**
     * Column type category for REAL, DOUBLE,
     * and DECIMAL columns.
     */
    public static final int CATEGORY_DOUBLE = 3;
    /**
     * Column type category for date and time related columns like
     * DATE, TIME, TIMESTAMP etc.
     */
    public static final int CATEGORY_DATETIME = 4;
    /**
     * Column type category for BOOLEAN columns.
     */
    public static final int CATEGORY_BOOLEAN = 5;
    /**
     * Column type category for types for which the type name
     * will be printed instead of the content, like BLOB,
     * BINARY, ARRAY etc.
     */
    public static final int CATEGORY_OTHER = 0;
    /**
     * Default maximum number of rows to query and print.
     */
    private static final int DEFAULT_MAX_ROWS = 10;
    /**
     * Default maximum width for text columns
     * (like a VARCHAR) column.
     */
    private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * {@link #DEFAULT_MAX_ROWS} and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     */
    public static void printTable(Connection conn, String tableName) {
        printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     * @param maxRows   Number of max. rows to query and print
     */
    public static void printTable(Connection conn, String tableName, int maxRows) {
        printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * maxStringColWidth will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn              Database connection object (java.sql.Connection)
     * @param tableName         Name of the database table
     * @param maxRows           Number of max. rows to query and print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
        if (conn == null) {
            System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
            return;
        }
        if (tableName == null) {
            System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
            return;
        }
        if (tableName.length() == 0) {
            System.err.println("DBTablePrinter Error: Empty table name!");
            return;
        }
        if (maxRows 
     * ResultSet to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
     * to limit the width of text columns.
     *
     * @param rs The ResultSet to print
     */
    public static void printResultSet(ResultSet rs) {
        printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method to print rows of a 
     * ResultSet to standard out using maxStringColWidth
     * to limit the width of text columns.
     *
     * @param rs                The ResultSet to print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printResultSet(ResultSet rs, int maxStringColWidth) {
        try {
            if (rs == null) {
                System.err.println("DBTablePrinter Error: Result set is null!");
                return;
            }
            if (rs.isClosed()) {
                System.err.println("DBTablePrinter Error: Result Set is closed!");
                return;
            }
            if (maxStringColWidth  columns = new ArrayList(columnCount);

            // List of table names. Can be more than one if it is a joined
            // table query
            List tableNames = new ArrayList(columnCount);

            // Get the columns and their meta data.
            // NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
            for (int i = 1; i  maxStringColWidth) {
                                value = value.substring(0, maxStringColWidth - 3) + "...";
                            }
                            break;
                    }

                    // Adjust the column width
                    c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
                    c.addValue(value);
                } // END of for loop columnCount
                rowCount++;

            } // END of while (rs.next)

            /*
            At this point we have gone through meta data, get the
            columns and created all Column objects, iterated over the
            ResultSet rows, populated the column values and adjusted
            the column widths.
            We cannot start printing just yet because we have to prepare
            a row separator String.
             */

            // For the fun of it, I will use StringBuilder
            StringBuilder strToPrint = new StringBuilder();
            StringBuilder rowSeparator = new StringBuilder();

            /*
            Prepare column labels to print as well as the row separator.
            It should look something like this:
            +--------+------------+------------+-----------+  (row separator)
            | EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME |  (labels row)
            +--------+------------+------------+-----------+  (row separator)
             */

            // Iterate over columns
            for (Column c : columns) {
                int width = c.getWidth();

                // Center the column label
                String toPrint;
                String name = c.getLabel();
                int diff = width - name.length();

                if ((diff % 2) == 1) {
                    // diff is not divisible by 2, add 1 to width (and diff)
                    // so that we can have equal padding to the left and right
                    // of the column label.
                    width++;
                    diff++;
                    c.setWidth(width);
                }

                int paddingSize = diff / 2; // InteliJ says casting to int is redundant.

                // Cool String repeater code thanks to user102008 at stackoverflow.com

                String padding = new String(new char[paddingSize]).replace("\0", " ");

                toPrint = "| " + padding + name + padding + " ";
                // END centering the column label

                strToPrint.append(toPrint);

                rowSeparator.append("+");
                rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
            }

            String lineSeparator = System.getProperty("line.separator");

            // Is this really necessary ??
            lineSeparator = lineSeparator == null ? "\n" : lineSeparator;

            rowSeparator.append("+").append(lineSeparator);

            strToPrint.append("|").append(lineSeparator);
            strToPrint.insert(0, rowSeparator);
            strToPrint.append(rowSeparator);

            StringJoiner sj = new StringJoiner(", ");
            for (String name : tableNames) {
                sj.add(name);
            }

            String info = "Printing " + rowCount;
            info += rowCount > 1 ? " rows from " : " row from ";
            info += tableNames.size() > 1 ? "tables " : "table ";
            info += sj.toString();

            System.out.println(info);

            // Print out the formatted column labels
            System.out.print(strToPrint.toString());

            String format;

            // Print out the rows
            for (int i = 0; i 
     * Integers should not be truncated so column widths should
     * be adjusted without a column width limit. Text columns should be
     * left justified and can be truncated to a max. column width etc...

*

* See also: * java.sql.Types * * @param type Generic SQL type * @return The category this type belongs to */ private static int whichCategory(int type) { switch (type) { case Types.BIGINT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return CATEGORY_INTEGER; case Types.REAL: case Types.DOUBLE: case Types.DECIMAL: return CATEGORY_DOUBLE; case Types.DATE: case Types.TIME: case Types.TIME_WITH_TIMEZONE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: return CATEGORY_DATETIME; case Types.BOOLEAN: return CATEGORY_BOOLEAN; case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.CHAR: case Types.NCHAR: return CATEGORY_STRING; default: return CATEGORY_OTHER; } } /** * Represents a database table column. */ private static class Column { /** * Column label. */ private String label; /** * Generic SQL type of the column as defined in * * java.sql.Types * . */ private int type; /** * Generic SQL type name of the column as defined in * * java.sql.Types * . */ private String typeName; /** * Width of the column that will be adjusted according to column label * and values to be printed. */ private int width = 0; /** * Column values from each row of a ResultSet. */ private List values = new ArrayList(); /** * Flag for text justification using String.format. * Empty string ("") to justify right, * dash (-) to justify left. * * @see #justifyLeft() */ private String justifyFlag = ""; /** * Column type category. The columns will be categorised according * to their column types and specific needs to print them correctly. */ private int typeCategory = 0; /** * Constructs a new Column with a column label, * generic SQL type and type name (as defined in * * java.sql.Types * ) * * @param label Column label or name * @param type Generic SQL type * @param typeName Generic SQL type name */ public Column(String label, int type, String typeName) { this.label = label; this.type = type; this.typeName = typeName; } /** * Returns the column label * * @return Column label */ public String getLabel() { return label; } /** * Returns the generic SQL type of the column * * @return Generic SQL type */ public int getType() { return type; } /** * Returns the generic SQL type name of the column * * @return Generic SQL type name */ public String getTypeName() { return typeName; } /** * Returns the width of the column * * @return Column width */ public int getWidth() { return width; } /** * Sets the width of the column to width * * @param width Width of the column */ public void setWidth(int width) { this.width = width; } /** * Adds a String representation (value) * of a value to this column object's {@link #values} list. * These values will come from each row of a * * ResultSet * of a database query. * * @param value The column value to add to {@link #values} */ public void addValue(String value) { values.add(value); } /** * Returns the column value at row index i. * Note that the index starts at 0 so that getValue(0) * will get the value for this column from the first row * of a * ResultSet. * * @param i The index of the column value to get * @return The String representation of the value */ public String getValue(int i) { return values.get(i); } /** * Returns the value of the {@link #justifyFlag}. The column * values will be printed using String.format and * this flag will be used to right or left justify the text. * * @return The {@link #justifyFlag} of this column * @see #justifyLeft() */ public String getJustifyFlag() { return justifyFlag; } /** * Sets {@link #justifyFlag} to "-" so that * the column value will be left justified when printed with * String.format. Typically numbers will be right * justified and text will be left justified. */ public void justifyLeft() { this.justifyFlag = "-"; } /** * Returns the generic SQL type category of the column * * @return The {@link #typeCategory} of the column */ public int getTypeCategory() { return typeCategory; } /** * Sets the {@link #typeCategory} of the column * * @param typeCategory The type category */ public void setTypeCategory(int typeCategory) { this.typeCategory = typeCategory; } } }

This is the scala version of doing this... which will print column names and data as well in a generic way...

def printQuery(res: ResultSet): Unit = {
    val rsmd = res.getMetaData
    val columnCount = rsmd.getColumnCount
    var rowCnt = 0
    val s = StringBuilder.newBuilder
    while (res.next()) {

      s.clear()
      if (rowCnt == 0) {
        s.append("| ")
        for (i <- 1 to columnCount) {
          val name = rsmd.getColumnName(i)
          s.append(name)
          s.append("| ")
        }
        s.append("\n")
      }
      rowCnt += 1
      s.append("| ")
      for (i <- 1 to columnCount) {
        if (i > 1)
          s.append(" | ")
        s.append(res.getString(i))
      }
      s.append(" |")
      System.out.println(s)
    }
    System.out.println(s"TOTAL: $rowCnt rows")
  }

WCF timeout exception detailed investigation

from: http://www.codeproject.com/KB/WCF/WCF_Operation_Timeout_.aspx

To avoid this timeout error, we need to configure the OperationTimeout property for Proxy in the WCF client code. This configuration is something new unlike other configurations such as Send Timeout, Receive Timeout etc., which I discussed early in the article. To set this operation timeout property configuration, we have to cast our proxy to IContextChannel in WCF client application before calling the operation contract methods.

installing urllib in Python3.6

urllib is a standard library, you do not have to install it. Simply import urllib

How to remove margin space around body or clear default css styles

try removing the padding/margins from the body tag.

body{
padding:0px;
margin:0px;
}

How to read/write arbitrary bits in C/C++

int x = 0xFF;   //your number - 11111111

How do I for example read a 3 bit integer value starting at the second bit

int y = x & ( 0x7 << 2 ) // 0x7 is 111
                         // and you shift it 2 to the left

How to convert string date to Timestamp in java?

Use capital HH to get hour of day format, instead of am/pm hours

Centering a div block without the width

<div class="outer">
   <div class="target">
      <div class="filler">
      </div>
   </div>
</div>

.outer{
   width:100%;
   height: 100px;
}

.target{
   position: absolute;
   width: auto;
   height: 100px;
   left: 50%;
   transform: translateX(-50%);
}

.filler{
   position:relative;
   width:150px;
   height:20px;
}

If the target element is absolutely positioned, you can center it by moving it 50% in one direction (left: 50%) and then transforming it 50% in the opposition direction (transform:translateX(-50%)). This works without defining the target element's width (or with width:auto). The parent element's position can be static, absolute, relative, or fixed.

Testing if a site is vulnerable to Sql Injection

The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.

Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

When to use pthread_exit() and when to use pthread_join() in Linux?

The pthread_exit() API

as has been already remarked, is used for the calling thread termination. After a call to that function a complicating clean up mechanism is started. When it completes the thread is terminated. The pthread_exit() API is also called implicitly when a call to the return() routine occurs in a thread created by pthread_create(). Actually, a call to return() and a call to pthread_exit() have the same impact, being called from a thread created by pthread_create().

It is very important to distinguish the initial thread, implicitly created when the main() function starts, and threads created by pthread_create(). A call to the return() routine from the main() function implicitly invokes the exit() system call and the entire process terminates. No thread clean up mechanism is started. A call to the pthread_exit() from the main() function causes the clean up mechanism to start and when it finishes its work the initial thread terminates.

What happens to the entire process (and to other threads) when pthread_exit() is called from the main() function depends on the PTHREAD implementation. For example, on IBM OS/400 implementation the entire process is terminated, including other threads, when pthread_exit() is called from the main() function. Other systems may behave differently. On most modern Linux machines a call to pthread_exit() from the initial thread does not terminate the entire process until all threads termination. Be careful using pthread_exit() from main(), if you want to write a portable application.

The pthread_join() API

is a convenient way to wait for a thread termination. You may write your own function that waits for a thread termination, perhaps more suitable to your application, instead of using pthread_join(). For example, it can be a function based on waiting on conditional variables.

I would recommend for reading a book of David R. Butenhof “Programming with POSIX Threads”. It explains the discussed topics (and more complicated things) very well (although some implementation details, such as pthread_exit usage in the main function, not always reflected in the book).

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Javascript objects: get parent

Just in keeping the parent value in child attribute

var Foo = function(){
    this.val= 4;
    this.test={};
    this.test.val=6;
    this.test.par=this;
}

var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);

What's the best UML diagramming tool?

Violet

Free, and very easy to use.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
         else:
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")


         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/Firefox.app %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/Safari.app %s")
         navigator.open_new(url)

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

Sorting an Array of int using BubbleSort

This isn't the bubble sort algorithm, you need to repeat until you have nothing to swap :

public void sortArray(int[] x) {//go through the array and sort from smallest to highest
  for(;;) {
      boolean s = false;
      for(int i=1; i<x.length; i++) {
         int temp=0;
         if(x[i-1] > x[i]) {
            temp = x[i-1];
            x[i-1] = x[i];
            x[i] = temp;
            s = true;
         }
      }
      if (!s) return;
  }
}

Find the unique values in a column and then sort them

You can also use the drop_duplicates() instead of unique()

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a

append multiple values for one key in a dictionary

You would be best off using collections.defaultdict (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list).

So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.

A quick example using your data:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.

Batch program to to check if process exists

Try this:

@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

JWT (JSON Web Token) automatic prolongation of expiration

An alternative solution for invalidating JWTs, without any additional secure storage on the backend, is to implement a new jwt_version integer column on the users table. If the user wishes to log out or expire existing tokens, they simply increment the jwt_version field.

When generating a new JWT, encode the jwt_version into the JWT payload, optionally incrementing the value beforehand if the new JWT should replace all others.

When validating the JWT, the jwt_version field is compared alongside the user_id and authorisation is granted only if it matches.

Amazon products API - Looking for basic overview and information

Your post contains several questions, so I'll try to answer them one at a time:

  1. The API you're interested in is the Product Advertising API (PA). It allows you programmatic access to search and retrieve product information from Amazon's catalog. If you're having trouble finding information on the API, that's because the web service has undergone two name changes in recent history: it was also known as ECS and AAWS.
  2. The signature process you're referring to is the same HMAC signature that all of the other AWS services use for authentication. All that's required to sign your requests to the Product Advertising API is a function to compute a SHA-1 hash and and AWS developer key. For more information, see the section of the developer documentation on signing requests.
  3. As far as I know, there is no support for retrieving RSS feeds of products or tags through PA. If anyone has information suggesting otherwise, please correct me.
  4. Either the REST or SOAP APIs should make your use case very straight forward. Amazon provides a fairly basic "getting started" guide available here. As well, you can view the complete API developer documentation here.

Although the documentation is a little hard to find (likely due to all the name changes), the PA API is very well documented and rather elegant. With a modicum of elbow grease and some previous experience in calling out to web services, you shouldn't have any trouble getting the information you need from the API.

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

How to find char in string and get all the indexes?

def find_offsets(haystack, needle):
    """
    Find the start of all (possibly-overlapping) instances of needle in haystack
    """
    offs = -1
    while True:
        offs = haystack.find(needle, offs+1)
        if offs == -1:
            break
        else:
            yield offs

for offs in find_offsets("ooottat", "o"):
    print offs

results in

0
1
2

How to extract text from an existing docx file using python-docx

It seems that there is no official solution for this problem, but there is a workaround posted here https://github.com/savoirfairelinux/python-docx/commit/afd9fef6b2636c196761e5ed34eb05908e582649

just update this file "...\site-packages\docx\oxml_init_.py"

# add
import re
import sys

# add
def remove_hyperlink_tags(xml):
    if (sys.version_info > (3, 0)):
        xml = xml.decode('utf-8')
    xml = xml.replace('</w:hyperlink>', '')
    xml = re.sub('<w:hyperlink[^>]*>', '', xml)
    if (sys.version_info > (3, 0)):
        xml = xml.encode('utf-8')
    return xml
    
# update
def parse_xml(xml):
    """
    Return root lxml element obtained by parsing XML character string in
    *xml*, which can be either a Python 2.x string or unicode. The custom
    parser is used, so custom element classes are produced for elements in
    *xml* that have them.
    """
    root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
    return root_element

and of course don't forget to mention in the documentation that use are changing the official library

Get encoding of a file in Windows

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.