Programs & Examples On #Montage

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How to find the Windows version from the PowerShell command line

I am refining one of the answers

I reached this question while trying to match the output from winver.exe:

Version 1607 (OS Build 14393.351)

I was able to extract the build string with:

,((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name BuildLabEx).BuildLabEx -split '\.') | % {  $_[0..1] -join '.' }  

Result: 14393.351

Updated: Here is a slightly simplified script using regex

(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

How to remove multiple indexes from a list at the same time?

If you can use numpy, then you can delete multiple indices:

>>> import numpy as np
>>> a = np.arange(10)
>>> np.delete(a,(1,3,5))
array([0, 2, 4, 6, 7, 8, 9])

and if you use np.r_ you can combine slices with individual indices:

>>> np.delete(a,(np.r_[0:5,7,9]))
array([5, 6, 8])

However, the deletion is not in place, so you have to assign to it.

Convert php array to Javascript

you can convert php arrays into javascript using php's json_encode function

<?php $phpArray = array(
          0 => 001-1234567, 
          1 => 1234567, 
          2 => 12345678, 
          3 => 12345678,
          4 => 12345678,
          5 => 'AP1W3242',
          6 => 'AP7X1234',
          7 => 'AS1234',
          8 => 'MH9Z2324', 
          9 => 'MX1234', 
          10 => 'TN1A3242',
          11 => 'ZZ1234'
    )
?>
<script type="text/javascript">

    var jArray= <?php echo json_encode($phpArray ); ?>;

    for(var i=0;i<12;i++){
        alert(jArray[i]);
    }

 </script>

For loop in multidimensional javascript array

You can do something like this:

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

for(var i = 0; i < cubes.length; i++) {
    var cube = cubes[i];
    for(var j = 0; j < cube.length; j++) {
        display("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

Working jsFiddle:

The output of the above:

cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9

Joining two table entities in Spring Data JPA

For a typical example of employees owning one or more phones, see this wikibook section.

For your specific example, if you want to do a one-to-one relationship, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

and in CacheMedia model you need to add:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Or if you prefer to do a @OneToMany and @ManyToOne relation, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

and in CacheMedia model you need to add:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

Does svn have a `revert-all` command?

You could do:

svn revert -R .

This will not delete any new file not under version control. But you can easily write a shell script to do that like:

for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

Can anyone explain me StandardScaler?

After applying StandardScaler(), each column in X will have mean of 0 and standard deviation of 1.

Formulas are listed by others on this page.

Rationale: some algorithms require data to look like this (see sklearn docs).

What REALLY happens when you don't free after malloc?

I think that your two examples are actually only one: the free() should occur only at the end of the process, which as you point out is useless since the process is terminating.

In you second example though, the only difference is that you allow an undefined number of malloc(), which could lead to running out of memory. The only way to handle the situation is to check the return code of malloc() and act accordingly.

Delete from a table based on date

Delete data that is 30 days and older

   DELETE FROM Table
   WHERE DateColumn < GETDATE()- 30

jQuery get the location of an element relative to window

Try the bounding box. It's simple:

var leftPos  = $("#element")[0].getBoundingClientRect().left   + $(window)['scrollLeft']();
var rightPos = $("#element")[0].getBoundingClientRect().right  + $(window)['scrollLeft']();
var topPos   = $("#element")[0].getBoundingClientRect().top    + $(window)['scrollTop']();
var bottomPos= $("#element")[0].getBoundingClientRect().bottom + $(window)['scrollTop']();

Remove directory from remote repository after adding them to .gitignore

As per my Answer here: How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple steps.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want

.gitignore file will be look like this

/FolderName

remove directory

Finding which process was killed by Linux OOM killer

Try this so you don't need to worry about where your logs are:

dmesg -T | egrep -i 'killed process'

-T - readable timestamps

UITableViewCell, show delete button on swipe

Also, this can be achieved in SWIFT using the method as follows

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete){
        testArray.removeAtIndex(indexPath.row)
        goalsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

How to add a new line in textarea element?

I've found String.fromCharCode(13, 10) helpful when using view engines. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:

viewHelper.js

exports.replaceNewline = function(input) {
    var newline = String.fromCharCode(13, 10);
    return input.replaceAll('\\n', newline);
}

EJS

<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>

Renders

<textarea>Blah
blah
blah</textarea>

replaceAll:

String.prototype.replaceAll = function (find, replace) {
    var result = this;
    do {
        var split = result.split(find);
        result = split.join(replace);
    } while (split.length > 1);
    return result;
};

How to find distinct rows with field in list using JPA and Spring?

Have you tried rewording your query like this?

@Query("SELECT DISTINCT p.name FROM People p WHERE p.name NOT IN ?1")
List<String> findNonReferencedNames(List<String> names);

Note, I'm assuming your entity class is named People, and not people.

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

python ignore certificate validation urllib2

According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)

if you need opener, just added this context like:

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))

NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.

How to remove "href" with Jquery?

If you wanted to remove the href, change the cursor and also prevent clicking on it, this should work:

$("a").attr('href', '').css({'cursor': 'pointer', 'pointer-events' : 'none'});

Matrix multiplication using arrays

My code is super easy and works for any order of matrix

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter No. of rows in matrix 1 : ");
    int arows = sc.nextInt();
    System.out.println(" Enter No. of columns in matrix 1 : ");
    int acols = sc.nextInt();
    System.out.println(" Enter No. of rows in matrix 2 : ");
    int brows = sc.nextInt();
    System.out.println(" Enter No. of columns in matrix 2 : ");
    int bcols = sc.nextInt();
    if (acols == brows) {
        System.out.println(" Enter elements of matrix 1 ");
        int a[][] = new int[arows][acols];
        int b[][] = new int[brows][bcols];
        for (int i = 0; i < arows; i++) {
            for (int j = 0; j < acols; j++) {
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println(" Enter elements of matrix 2 ");
        for (int i = 0; i < brows; i++) {
            for (int j = 0; j < bcols; j++) {
                b[i][j] = sc.nextInt();
            }
        }
        System.out.println(" The Multiplied matrix is : ");
        int sum = 0;
        int c[][] = new int[arows][bcols];
        for (int i = 0; i < arows; i++) {
            for (int j = 0; j < bcols; j++) {
                for (int k = 0; k < brows; k++) {
                    sum = sum + a[i][k] * b[k][j];
                    c[i][j] = sum;
                }

                System.out.print(c[i][j] + " ");
                sum = 0;
            }
            System.out.println();
        }
    } else {
        System.out.println("Order of matrix in invalid");
    }
}

Go to Matching Brace in Visual Studio?

Note: It also works for #if / #elif / #endif matching. The caret must be on the #.

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib

In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib was somehow triggered automatically.

Fixed by manually adding the non-versioned filename to:

<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>

and blacklisting the ...vc120-mt-sgd-1_55.lib in

<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>

How to find all occurrences of an element in a list

If you are using Python 2, you can achieve the same functionality with this:

f = lambda my_list, value:filter(lambda x: my_list[x] == value, range(len(my_list)))

Where my_list is the list you want to get the indexes of, and value is the value searched. Usage:

f(some_list, some_element)

How to change package name of Android Project in Eclipse?

Goto the Src folder of your Android project, and open the Java file.

Change the package OldName.android.widget to newName.android.widget.

It gives you an error like this

The declared package "newName.android.widget" does not match the expected package "OLDName.android.widget.

To fix this problem, select Move filename.Java to Newname.android.widget and delete the old package folder.

Next step: Go to AndroidManifest.xml and change package="OldName.android.widget" to package="newName.android.widget".

Check if a class is derived from a generic class

JaredPar,

This did not work for me if I pass typeof(type<>) as toCheck. Here's what I changed.

static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
          if (cur.IsGenericType && generic.GetGenericTypeDefinition() == cur.GetGenericTypeDefinition()) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}

Plugin with id 'com.google.gms.google-services' not found

simply add "classpath 'com.google.gms:google-services:3.0.0'" to android/build.gradle to look like this

buildscript {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.0.0'

       // NOTE: Do not place your application dependencies here; they belong
       // in the individual module build.gradle files

    }
}

and also add "apply plugin: 'com.google.gms.google-services'" to the end of file in android/app/build.gradle to look like this

apply plugin: 'com.google.gms.google-services'

Determine direct shared object dependencies of a Linux binary?

The objdump tool can tell you this information. If you invoke objdump with the -x option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".

For example running objdump -x /usr/lib/libXpm.so.4 on my system gives the following information in the "Dynamic Section":

Dynamic Section:
  NEEDED               libX11.so.6
  NEEDED               libc.so.6
  SONAME               libXpm.so.4
  INIT                 0x0000000000002450
  FINI                 0x000000000000e0e8
  GNU_HASH             0x00000000000001f0
  STRTAB               0x00000000000011a8
  SYMTAB               0x0000000000000470
  STRSZ                0x0000000000000813
  SYMENT               0x0000000000000018
  PLTGOT               0x000000000020ffe8
  PLTRELSZ             0x00000000000005e8
  PLTREL               0x0000000000000007
  JMPREL               0x0000000000001e68
  RELA                 0x0000000000001b38
  RELASZ               0x0000000000000330
  RELAENT              0x0000000000000018
  VERNEED              0x0000000000001ad8
  VERNEEDNUM           0x0000000000000001
  VERSYM               0x00000000000019bc
  RELACOUNT            0x000000000000001b

The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4 on my system just needs libX11.so.6 and libc.so.6.

It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.

Export and Import all MySQL databases at one time

Based on these answers I've made script which backups all databases into separate files, but then compress them into one archive with date as name.

This will not ask for password, can be used in cron. To store password in .my.cnf check this answer https://serverfault.com/a/143587/62749

Made also with comments for those who are not very familiar with bash scripts.

#!/bin/bash

# This script will backup all mysql databases into 
# compressed file named after date, ie: /var/backup/mysql/2016-07-13.tar.bz2

# Setup variables used later

# Create date suffix with "F"ull date format
suffix=$(date +%F)
# Retrieve all database names except information schemas. Use sudo here to skip root password.
dbs=$(sudo mysql --defaults-extra-file=/root/.my.cnf --batch --skip-column-names -e "SHOW DATABASES;" | grep -E -v "(information|performance)_schema")
# Create temporary directory with "-d" option
tmp=$(mktemp -d)
# Set output dir here. /var/backups/ is used by system, 
# so intentionally used /var/backup/ for user backups.
outDir="/var/backup/mysql"
# Create output file name
out="$outDir/$suffix.tar.bz2"

# Actual script

# Check if output directory exists
if [ ! -d "$outDir" ];then
  # Create directory with parent ("-p" option) directories
  sudo mkdir -p "$outDir"
fi

# Loop through all databases
for db in $dbs; do
  # Dump database to temporary directory with file name same as database name + sql suffix
  sudo mysqldump --defaults-extra-file=/root/.my.cnf --databases "$db" > "$tmp/$db.sql"
done

# Go to tmp dir
cd $tmp

# Compress all dumps with bz2, discard any output to /dev/null
sudo tar -jcf "$out" * > "/dev/null"

# Cleanup
cd "/tmp/"
sudo rm -rf "$tmp"

Convert from ASCII string encoded in Hex to plain ASCII?

Here's my solution when working with hex integers and not hex strings:

def convert_hex_to_ascii(h):
    chars_in_reverse = []
    while h != 0x0:
        chars_in_reverse.append(chr(h & 0xFF))
        h = h >> 8

    chars_in_reverse.reverse()
    return ''.join(chars_in_reverse)

print convert_hex_to_ascii(0x7061756c)

Regex to match string containing two names in any order

You can do:

\bjack\b.*\bjames\b|\bjames\b.*\bjack\b

Why is the minidlna database not being refreshed?

In summary, the most reliable way to have MiniDLNA rescan all media files is by issuing the following set of commands:

$ sudo minidlnad -R
$ sudo service minidlna restart

Client-side script to rescan server

However, every so often MiniDLNA will be running on a server. Here is a client-side script to request a rescan on such a server:

#!/usr/bin/env bash
ssh -t server.on.lan 'sudo minidlnad -R && sudo service minidlna restart'

Adding an onclicklistener to listview (android)

list.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

python capitalize first letter only

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

Converting Array to List

Old way but still working!

 int[] values = {1,2,3,4};
 List<Integer> list = new ArrayList<>(values.length);

 for(int valor : values) {
     list.add(valor);
 }

How to convert a Collection to List?

Use streams:

someCollection.stream().collect(Collectors.toList())

Should I use string.isEmpty() or "".equals(string)?

One thing you might want to consider besides the other issues mentioned is that isEmpty() was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.

Check for null variable in Windows batch

To test for the existence of a command line paramater, use empty brackets:

IF [%1]==[] echo Value Missing

or

IF [%1] EQU [] echo Value Missing

The SS64 page on IF will help you here. Under "Does %1 exist?".

You can't set a positional parameter, so what you should do is do something like

SET MYVAR=%1

You can then re-set MYVAR based on its contents.

reducing number of plot ticks

When a log scale is used the number of major ticks can be fixed with the following command

import matplotlib.pyplot as plt

....

plt.locator_params(numticks=12)
plt.show()

The value set to numticks determines the number of axis ticks to be displayed.

Credits to @bgamari's post for introducing the locator_params() function, but the nticks parameter throws an error when a log scale is used.

How does setTimeout work in Node.JS?

setTimeout(callback,t) is used to run callback after at least t millisecond. The actual delay depends on many external factors like OS timer granularity and system load.

So, there is a possibility that it will be called slightly after the set time, but will never be called before.

A timer can't span more than 24.8 days.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.

Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!

Google should probably have a caveat saying you may also need JRE OR JDK

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

What is bootstrapping?

As the question is answered. For web develoment. I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link

In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes.

hope it will help someone who learning web application development.

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

Custom Date/Time formatting in SQL Server

If it's something more specific like DateKey (yyyymmdd) that you need for dimensional models, I suggest something without any casts/converts:

DECLARE @DateKeyToday int = (SELECT 10000 * DATEPART(yy,GETDATE()) + 100 * DATEPART(mm,GETDATE()) + DATEPART(dd,GETDATE()));
PRINT @DateKeyToday

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

C++ catching all exceptions

it is possible to do this by writing:

try
{
  //.......
}
catch(...) // <<- catch all
{
  //.......
}

But there is a very not noticeable risk here: you can not find the exact type of error that has been thrown in the try block, so use this kind of catch when you are sure that no matter what the type of exception is, the program must persist in the way defined in the catch block.

How to instantiate, initialize and populate an array in TypeScript?

A simple solution could be:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

Using android.support.v7.widget.CardView in my project (Eclipse)

I was able to work it out only after adding those two TOGETHER:

dependencies {
...
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
...
}

in my build.gradle (Module:app) file

and then press the sync now button

Separating class code into a header and cpp file

A2DD.h

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);

  int getSum();
};

A2DD.cpp

  A2DD::A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int A2DD::getSum()
  {
    return gx + gy;
  }

The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.

And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.

How to generate Javadoc from command line

Oracle provides some simple examples:

http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC

Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.

mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net

SQL Server: Null VS Empty String

NULL is a non value, like undefined. '' is a empty string with 0 characters.
The value of a string in database depends of your value in your UI, but generally, it's an empty string '' if you specify the parameter in your query or stored procedure.

How to get the absolute coordinates of a view

My utils function for get view location, it will return a Point object with x value and y value

public static Point getLocationOnScreen(View view){
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    return new Point(location[0], location[1]);
}

Using

Point viewALocation = getLocationOnScreen(viewA);

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Redis: How to access Redis log file

You can also login to the redis-cli and use the MONITOR command to see what queries are happening against Redis.

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

How to measure elapsed time in Python?

I made a library for this, if you want to measure a function you can just do it like this


from pythonbenchmark import compare, measure
import time

a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]

@measure
def myFunction(something):
    time.sleep(0.4)

@measure
def myOptimizedFunction(something):
    time.sleep(0.2)

myFunction(input)
myOptimizedFunction(input)

https://github.com/Karlheinzniebuhr/pythonbenchmark

Finding rows containing a value (or values) in any column

Here's a dplyr option:

library(dplyr)

# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))

# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))                                                                                                     

how to align img inside the div to the right?

<p>
  <img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
  Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci. 
  <br style="clear: both;" />
</p>

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

Create a root password for PHPMyAdmin

On linux (debian 9) after resetting the mysql(Maria DB) root password, you just have to edit the phpmyadmin db config file located at /etc/phpmyadmin/config-db.php

gedit /etc/phpmyadmin/config-db.php (as root)

How to use a typescript enum value in an Angular2 ngSwitch statement

This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template

  statusEnum: typeof StatusEnum = StatusEnum;

What happened to console.log in IE8?

console.log is only available after you have opened the Developer Tools (F12 to toggle it open and closed). Funny thing is that after you've opened it, you can close it, then still post to it via console.log calls, and those will be seen when you reopen it. I'm thinking that is a bug of sorts, and may be fixed, but we shall see.

I'll probably just use something like this:

function trace(s) {
  if ('console' in self && 'log' in console) console.log(s)
  // the line below you might want to comment out, so it dies silent
  // but nice for seeing when the console is available or not.
  else alert(s)
}

and even simpler:

function trace(s) {
  try { console.log(s) } catch (e) { alert(s) }
}

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

An alternative to using LINQ:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

I have found using HashSet<T> is quicker for lists of up to ~ 6,000 integers compared with:

var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Container(
        alignment: Alignment.centerLeft,
        child: Text(
          reminder['title'],
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        child: Text(
          reminder['Date'],
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    ],
  ),
);
}

Can vue-router open a link in a new tab?

This worked for me-

let routeData = this.$router.resolve(
{
  path: '/resources/c-m-communities', 
  query: {'dataParameter': 'parameterValue'}
});
window.open(routeData.href, '_blank');

I modified @Rafael_Andrs_Cspedes_Basterio answer

How can I export Excel files using JavaScript?

Similar answer posted here.

Link for working example

var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var result = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);

Main libraries required -

<script src="http://alasql.org/console/alasql.min.js"></script> 
<script src="http://alasql.org/console/xlsx.core.min.js"></script> 

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

How to insert a character in a string at a certain position?

In most use-cases, using a StringBuilder (as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.

/**
 * Insert the 'insert' String at the index 'position' into the 'target' String.
 * 
 * ````
 * insertAt("AC", 0, "") -> "AC"
 * insertAt("AC", 1, "xxx") -> "AxxxC"
 * insertAt("AB", 2, "C") -> "ABC
 * ````
 */
public static String insertAt(final String target, final int position, final String insert) {
    final int targetLen = target.length();
    if (position < 0 || position > targetLen) {
        throw new IllegalArgumentException("position=" + position);
    }
    if (insert.isEmpty()) {
        return target;
    }
    if (position == 0) {
        return insert.concat(target);
    } else if (position == targetLen) {
        return target.concat(insert);
    }
    final int insertLen = insert.length();
    final char[] buffer = new char[targetLen + insertLen];
    target.getChars(0, position, buffer, 0);
    insert.getChars(0, insertLen, buffer, position);
    target.getChars(position, targetLen, buffer, position + insertLen);
    return new String(buffer);
}

Event system in Python

We use an EventHook as suggested from Michael Foord in his Event Pattern:

Just add EventHooks to your classes with:

class MyBroadcaster()
    def __init__():
        self.onChange = EventHook()

theBroadcaster = MyBroadcaster()

# add a listener to the event
theBroadcaster.onChange += myFunction

# remove listener from the event
theBroadcaster.onChange -= myFunction

# fire event
theBroadcaster.onChange.fire()

We add the functionality to remove all listener from an object to Michaels class and ended up with this:

class EventHook(object):

    def __init__(self):
        self.__handlers = []

    def __iadd__(self, handler):
        self.__handlers.append(handler)
        return self

    def __isub__(self, handler):
        self.__handlers.remove(handler)
        return self

    def fire(self, *args, **keywargs):
        for handler in self.__handlers:
            handler(*args, **keywargs)

    def clearObjectHandlers(self, inObject):
        for theHandler in self.__handlers:
            if theHandler.im_self == inObject:
                self -= theHandler

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

JSON_UNESCAPED_UNICODE is available on PHP Version 5.4 or later.
The following code is for Version 5.3.

UPDATED

  • html_entity_decode is a bit more efficient than pack + mb_convert_encoding.
  • (*SKIP)(*FAIL) skips backslashes itself and specified characters by JSON_HEX_* flags.

 

function raw_json_encode($input, $flags = 0) {
    $fails = implode('|', array_filter(array(
        '\\\\',
        $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
        $flags & JSON_HEX_AMP ? 'u0026' : '',
        $flags & JSON_HEX_APOS ? 'u0027' : '',
        $flags & JSON_HEX_QUOT ? 'u0022' : '',
    )));
    $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
    $callback = function ($m) {
        return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
    };
    return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}

A Space between Inline-Block List Items

I have seen this and answered on it before:

After further research I have discovered that inline-block is a whitespace dependent method and is dependent on the font setting. In this case 4px is rendered.

To avoid this you could run all your lis together in one line, or block the end tags and begin tags together like this:

<ul>
        <li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li>
</ul>

Example here.


As mentioned by other answers and comments, the best practice for solving this is to add font-size: 0; to the parent element:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

This is better for HTML readability (avoiding running the tags together etc). The spacing effect is because of the font's spacing setting, so you must reset it for the inlined elements and set it again for the content within.

Set UILabel line spacing

I've found 3rd Party Libraries Like this one:

https://github.com/Tuszy/MTLabel

To be the easiest solution.

jQuery selector for id starts with specific text

Use jquery starts with attribute selector

$('[id^=editDialog]')

Alternative solution - 1 (highly recommended)

A cleaner solution is to add a common class to each of the divs & use

$('.commonClass').

But you can use the first one if html markup is not in your hands & cannot change it for some reason.

Alternative solution - 2 (not recommended if n is a large number) (as per @Mihai Stancu's suggestion)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.

select dept names who have more than 2 employees whose salary is greater than 1000

My main advice would be to steer clear of the HAVING clause (see below):

WITH HighEarners AS
     ( SELECT EmpId, DeptId
         FROM EMPLOYEE
        WHERE Salary > 1000 ), 
     DeptmentHighEarnerTallies AS 
     ( SELECT DeptId, COUNT(*) AS HighEarnerTally
         FROM HighEarners
        GROUP 
           BY DeptId )
SELECT DeptName
  FROM DEPARTMENT NATURAL JOIN DeptmentHighEarnerTallies
 WHERE HighEarnerTally > 2;

The very early SQL implementations lacked derived tables and HAVING was a workaround for one of its most obvious drawbacks (how to select on the result of a set function from the SELECT clause). Once derived tables had become a thing, the need for HAVING went away. Sadly, HAVING itself didn't go away (and never will) because nothing is ever removed from standard SQL. There is no need to learn HAVING and I encourage fledgling coders to avoid using this historical hangover.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Free c# QR-Code generator

You can look at Open Source QR Code Library or messagingtoolkit-qrcode. I have not used either of them so I can not speak of their ease to use.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

I found a particular edge case where I was using the tini init in an alpine container, but since I was not using the statically linked version, and Alpine uses musl libc rather than GNU LibC library installed by default, it was crashing with the very same error message.

Had I understood this and also taken time to read the documentation properly, I would have found Tini Static, which upon changing to, resolved my problem.

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

getResourceAsStream() vs FileInputStream

I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).

File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.

Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.

MVC: How to Return a String as JSON

You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

And then return it's instance:

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

In postgresql all foreign keys must reference a unique key in the parent table, so in your bar table you must have a unique (name) index.

See also http://www.postgresql.org/docs/9.1/static/ddl-constraints.html#DDL-CONSTRAINTS-FK and specifically:

Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint.

Emphasis mine.

This project references NuGet package(s) that are missing on this computer

In my case it had to do with the Microsoft.Build.Bcl version. My nuget package version was 1.0.21, but my project files were still pointing to version 1.0.14

So I changed my .csproj files from:

  <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
   <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
  </Target>

to:

 <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
  <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />

And the build was working again.

I want to calculate the distance between two points in Java

Unlike maths-on-paper notation, most programming languages (Java included) need a * sign to do multiplication. Your distance calculation should therefore read:

distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Or alternatively:

distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));

Getting SyntaxError for print with keyword argument end=' '

Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.

print("foo" % bar, end=" ")

in Python 2.x is identical to

print ("foo" % bar, end=" ")

or

print "foo" % bar, end=" "

i.e. as a call to print with a tuple as argument.

That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.

The correct idiom in Python 2.x for end=" " is:

print "foo" % bar,

(note the final comma, this makes it end the line with a space rather than a linebreak)

If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.

Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:

from __future__ import print_function

The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.

How to serve an image using nodejs

2016 Update

Examples with Express and without Express that actually work

This question is over 5 years old but every answer has some problems.

TL;DR

Scroll down for examples to serve an image with:

  1. express.static
  2. express
  3. connect
  4. http
  5. net

All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers

Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers

Introduction

After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.

First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.

Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.

A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.

If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.

In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, preformant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.

After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.

Minimum functionality

Every example serves files from the public directory and supports the minumum functionality of:

  • MIME types for most common files
  • serves HTML, JS, CSS, plain text and images
  • serves index.html as a default directory index
  • responds with error codes for missing files
  • no path traversal vulnerabilities
  • no race conditions while reading files

I tested every version on Node versions 4, 5, 6 and 7.

express.static

This version uses the express.static built-in middleware of the express module.

This example has the most functionality and the least amount of code.

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

express

This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.

This example has simple path traversal countermeasures and supports a limited set of most common MIME types.

var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.get('*', function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        return res.status(403).end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.set('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.set('Content-Type', 'text/plain');
        res.status(404).end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

connect

This version uses the connect module which is a one level of abstraction lower than express.

This example has similar functionality to the express version but using slightly lower-lever APIs.

var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.use(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

http

This version uses the http module which is the lowest-level API for HTTP in Node.

This example has similar functionality to the connect version but using even more lower-level APIs.

var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

net

This version uses the net module which is the lowest-level API for TCP sockets in Node.

This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.

var path = require('path');
var net = require('net');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = net.createServer(function (con) {
    var input = '';
    con.on('data', function (data) {
        input += data;
        if (input.match(/\n\r?\n\r?/)) {
            var line = input.split(/\n/)[0].split(' ');
            var method = line[0], url = line[1], pro = line[2];
            var reqpath = url.toString().split('?')[0];
            if (method !== 'GET') {
                var body = 'Method not implemented';
                con.write('HTTP/1.1 501 Not Implemented\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
            if (file.indexOf(dir + path.sep) !== 0) {
                var body = 'Forbidden';
                con.write('HTTP/1.1 403 Forbidden\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var type = mime[path.extname(file).slice(1)] || 'text/plain';
            var s = fs.readFile(file, function (err, data) {
                if (err) {
                    var body = 'Not Found';
                    con.write('HTTP/1.1 404 Not Found\n');
                    con.write('Content-Type: text/plain\n');
                    con.write('Content-Length: '+body.length+'\n\n');
                    con.write(body);
                    con.destroy();
                } else {
                    con.write('HTTP/1.1 200 OK\n');
                    con.write('Content-Type: '+type+'\n');
                    con.write('Content-Length: '+data.byteLength+'\n\n');
                    con.write(data);
                    con.destroy();
                }
            });
        }
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

Download examples

I posted all of the examples on GitHub with more explanation.

Examples with express.static, express, connect, http and net:

Other project using only express.static:

Tests

Test results are available on Travis:

Everything is tested on Node versions 4, 5, 6, and 7.

See also

Other related answers:

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.

How to Call Controller Actions using JQuery in ASP.NET MVC

In response to the above post I think it needs this line instead of your line:-

var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' &param2='+value2

Or else you send the actual strings value1 and value2 to the controller.

However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.


Here is a working solution. For the cshtml page:-

   <button type="button" onclick="ButtonClick();"> Call &raquo;</button>

<script>
    function ButtonClick()
    {
        callControllerMethod2("1", "2");
    }
    function callControllerMethod2(value1, value2)
    {
        var response = null;
        $.ajax({
            async: true,
            url: "Logging/SubMenu_Click?param1=" + value1 + " &param2=" + value2,
            cache: false,
            dataType: "json",
            success: function (data) { receiveResponse(data); }
        });
    }
    function receiveResponse(response)
    {
        if (response != null)
        {
            for (var i = 0; i < response.length; i++)
            {
                alert(response[i].Data);
            }
        }
    }
</script>

And for the controller:-

public class A
{
    public string Id { get; set; }
    public string Data { get; set; }

}
public JsonResult SubMenu_Click(string param1, string param2)
{
    A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
    return Json(arr , JsonRequestBehavior.AllowGet);
}

You can see the time changing each time it is called, so there is no caching of the values...

Java Compare Two Lists

Are these really lists (ordered, with duplicates), or are they sets (unordered, no duplicates)?

Because if it's the latter, then you can use, say, a java.util.HashSet<E> and do this in expected linear time using the convenient retainAll.

    List<String> list1 = Arrays.asList(
        "milan", "milan", "iga", "dingo", "milan"
    );
    List<String> list2 = Arrays.asList(
        "hafil", "milan", "dingo", "meat"
    );

    // intersection as set
    Set<String> intersect = new HashSet<String>(list1);
    intersect.retainAll(list2);
    System.out.println(intersect.size()); // prints "2"
    System.out.println(intersect); // prints "[milan, dingo]"

    // intersection/union as list
    List<String> intersectList = new ArrayList<String>();
    intersectList.addAll(list1);
    intersectList.addAll(list2);
    intersectList.retainAll(intersect);
    System.out.println(intersectList);
    // prints "[milan, milan, dingo, milan, milan, dingo]"

    // original lists are structurally unmodified
    System.out.println(list1); // prints "[milan, milan, iga, dingo, milan]"
    System.out.println(list2); // prints "[hafil, milan, dingo, meat]"

What happens to C# Dictionary<int, int> lookup if the key does not exist?

int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

How do you declare an object array in Java?

It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.

Calculating distance between two points (Latitude, Longitude)

In addition to the previous answers, here is a way to calculate the distance inside a SELECT:

CREATE FUNCTION Get_Distance
(   
    @La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE 
AS
RETURN 
    -- Distance in Meters
    SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
    AS Distance
GO

Usage:

select Distance
from Place P1,
     Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)

Scalar functions also work but they are very inefficient when computing large amount of data.

I hope this might help someone.

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Path}} {{.Args}} ({{.Id}})" $(docker ps -a -q)

That will display the command path and arguments, similar to docker ps.

Stop all active ajax requests in jQuery

I found it too easy for multiple requests.

step1: define a variable at top of page:

  xhrPool = []; // no need to use **var**

step2: set beforeSend in all ajax requests:

  $.ajax({
   ...
   beforeSend: function (jqXHR, settings) {
        xhrPool.push(jqXHR);
    },
    ...

step3: use it whereever you required:

   $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
    });

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Having that:

public interface ITerm
{
    string Name { get; }
}

public class Value : ITerm...

public class Variable : ITerm...

public class Query
{
   public IList<ITerm> Terms { get; }
...
}

I managed conversion trick implementing that:

public class TermConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var field = value.GetType().Name;
        writer.WriteStartObject();
        writer.WritePropertyName(field);
        writer.WriteValue((value as ITerm)?.Name);
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var properties = jsonObject.Properties().ToList();
        var value = (string) properties[0].Value;
        return properties[0].Name.Equals("Value") ? (ITerm) new Value(value) : new Variable(value);
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof (ITerm) == objectType || typeof (Value) == objectType || typeof (Variable) == objectType;
    }
}

It allows me to serialize and deserialize in JSON like:

string JsonQuery = "{\"Terms\":[{\"Value\":\"This is \"},{\"Variable\":\"X\"},{\"Value\":\"!\"}]}";
...
var query = new Query(new Value("This is "), new Variable("X"), new Value("!"));
var serializeObject = JsonConvert.SerializeObject(query, new TermConverter());
Assert.AreEqual(JsonQuery, serializeObject);
...
var queryDeserialized = JsonConvert.DeserializeObject<Query>(JsonQuery, new TermConverter());

NPM doesn't install module dependencies

happens with old node version. use latest version of node like this:

$ nvm use 8.0
$ rm -rf node_modules
$ npm install
$ npm i somemodule

edit: also make sure you save.
eg: npm install yourmoduleName --save

HTML input arrays

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>

Append a tuple to a list - what's the difference between two ways?

I believe tuple() takes a list as an argument For example,

tuple([1,2,3]) # returns (1,2,3)

see what happens if you wrap your array with brackets

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

How to represent matrices in python

Python doesn't have matrices. You can use a list of lists or NumPy

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Making a Bootstrap table column fit to content

Kind of an old question, but I arrived here looking for this. I wanted the table to be as small as possible, fitting to it's contents. The solution was to simply set the table width to an arbitrary small number (1px for example). I even created a CSS class to handle it:

.table-fit {
    width: 1px;
}

And use it like so:

<table class="table table-fit">

Example: JSFiddle

ROW_NUMBER() in MySQL

I always end up following this pattern. Given this table:

+------+------+
|    i |    j |
+------+------+
|    1 |   11 |
|    1 |   12 |
|    1 |   13 |
|    2 |   21 |
|    2 |   22 |
|    2 |   23 |
|    3 |   31 |
|    3 |   32 |
|    3 |   33 |
|    4 |   14 |
+------+------+

You can get this result:

+------+------+------------+
|    i |    j | row_number |
+------+------+------------+
|    1 |   11 |          1 |
|    1 |   12 |          2 |
|    1 |   13 |          3 |
|    2 |   21 |          1 |
|    2 |   22 |          2 |
|    2 |   23 |          3 |
|    3 |   31 |          1 |
|    3 |   32 |          2 |
|    3 |   33 |          3 |
|    4 |   14 |          1 |
+------+------+------------+

By running this query, which doesn't need any variable defined:

SELECT a.i, a.j, count(*) as row_number FROM test a
JOIN test b ON a.i = b.i AND a.j >= b.j
GROUP BY a.i, a.j

Hope that helps!

How to check if mod_rewrite is enabled in php?

Actually, just because a module is loaded, it does not necessarily mean that the directives has been enabled in the directory you are placing the .htaccess. What you probably need is to know: Does rewriting work? The only way to find out for sure is to do an actual test: Put some test files on the server and request it with HTTP.

Good news: I created a library for doing exactly this (detecting various .htaccess capabilities). With this library, all you need to do is this:

require 'vendor/autoload.php';
use HtaccessCapabilityTester\HtaccessCapabilityTester;

$hct = new HtaccessCapabilityTester($baseDir, $baseUrl);
if ($hct->rewriteWorks()) {    
    // rewriting works
}

(instead of $baseDir and $baseUrl, you must provide the path to where the test files are going to be put and a corresponding URL to where they can be reached)

If you just want to know if the module is loaded, you can do the following:

if ($hct->moduleLoaded('rewrite')) {    
    // mod_rewrite is loaded (tested in a real .htaccess by using the "IfModule" directive)
}

The library is available here: https://github.com/rosell-dk/htaccess-capability-tester

How to convert JSON to string?

Try to Use JSON.stringify

Regards

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

How to change options of <select> with jQuery?

if we update <select> constantly and we need to save previous value :

var newOptions = {
    'Option 1':'value-1',
    'Option 2':'value-2'
};

var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
   $el.append($('<option></option>').attr('value', value).text(key));
   if (value === prevValue){
       $el.val(value);
   }
});
$el.trigger('change');

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How to toggle font awesome icon on click?

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});

Demo: http://jsfiddle.net/Zcn2u/

In R, how to find the standard error of the mean?

y <- mean(x, na.rm=TRUE)

sd(y) for standard deviation var(y) for variance.

Both derivations use n-1 in the denominator so they are based on sample data.

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

jquery draggable: how to limit the draggable area?

Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV

buildDraggable = function() {
    $( "#handle" ).draggable({
    containment: '#thumbnail',
    drag: function(event) {
        var top = $(this).position().top;
        var left = $(this).position().left;

        ICZoom.panImage(top, left);
    },
});

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

how to return index of a sorted list?

You can do this with numpy's argsort method if you have numpy available:

>>> import numpy
>>> vals = numpy.array([2,3,1,4,5])
>>> vals
array([2, 3, 1, 4, 5])
>>> sort_index = numpy.argsort(vals)
>>> sort_index
array([2, 0, 1, 3, 4])

If not available, taken from this question, this is the fastest method:

>>> vals = [2,3,1,4,5]
>>> sorted(range(len(vals)), key=vals.__getitem__)
[2, 0, 1, 3, 4]

How to add an existing folder with files to SVN?

Let's say I have code in the directory ~/local_dir/myNewApp, and I want to put it under 'https://svn.host/existing_path/myNewApp' (while being able to ignore some binaries, vendor libraries, etc.).

  1. Create an empty folder in the repository svn mkdir https://svn.host/existing_path/myNewApp
  2. Go to the parent directory of the project, cd ~/local_dir
  3. Check out the empty directory over your local folder. Don't be afraid - the files you have locally will not be deleted. svn co https://svn.host/existing_path/myNewApp. If your folder has a different name locally than in the repository, you must specify it as an additional argument.
  4. You can see that svn st will now show all your files as ?, which means that they are not currently under revision control
  5. Perform svn add on files you want to add to the repository, and add others to svn:ignore. You may find some useful options with svn help add, for example --parents or --depth empty, when you want selectively add only some files/folders.
  6. Commit with svn ci

Cannot attach the file *.mdf as database

I had the same error. Weird thing was, I had one new project form scratch, there it worked perfectly and another, much bigger project, where I always ran into that error message.

The perfecrtly working project (nearly) always creates the database (indluding the files) automatically. It can be any command, read, write, update. The files get created. Of course it uses

DropCreateDatabaseIfModelChanges

There is only one case, when it gets troubled: IF the mdf is auto-created and you delete the mdf and log file. Then that was about it. Say good-bye to your autocreation...

The only way I found to fix it was like mentioned:

sqllocaldb stop v11.0 & sqllocaldb delete v11.0

After that, everything is back to normal (and all other Databases handled by LocalDB also gone!).

EDIT: That was not true. I just tried it and the v11.0 gets automatically recreated and all mdfs stay available. I have not tried with "non file based" LocalDBs.

The confusing thing is, I also got this error if something else was wrong. So my suggestion is, if you want to make sure your DB-Setup is sound and solid: Create a new solution/project from scratch, use the most basic DB commands (Add an entity, show all entities, delete all entities) and see if it works.

If YES, the problem is somewhere in the abyss of VS2013 config and versioning and nuget and stuff.

IF NO, you have a problem with your LocalDB installation.

For anyone who really wants to understand what's going on in EF (and I am still not sure if I do :-) ) http://odetocode.com/Blogs/scott/archive/2012/08/14/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx

P.S.: Nudge me if you need the running example project.

Difference between OData and REST web services

UPDATE Warning, this answer is extremely out of date now that OData V4 is available.


I wrote a post on the subject a while ago here.

As Franci said, OData is based on Atom Pub. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process.

The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response. It is what REST people call out-of-band information and introduces hidden coupling between the client and server.

The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. This metadata can be discovered at a fixed endpoint called $metadata. Again, the client needs to know this in advance, it cannot be discovered.

Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.

doGet and doPost in Servlets

The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.

What is the volatile keyword useful for?

From oracle documentation page, the need for volatile variable arises to fix memory consistency issues:

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

As explained in Peter Parker answer, in absence of volatile modifier, each thread's stack may have their own copy of variable. By making the variable as volatile, memory consistency issues have been fixed.

Have a look at jenkov tutorial page for better understanding.

Have a look at related SE question for some more details on volatile & use cases to use volatile:

Difference between volatile and synchronized in Java

One practical use case:

You have many threads, which need to print current time in a particular format for example : java.text.SimpleDateFormat("HH-mm-ss"). Yon can have one class, which converts current time into SimpleDateFormat and updated the variable for every one second. All other threads can simply use this volatile variable to print current time in log files.

How can I get a side-by-side diff when I do "git diff"?

This may be a somewhat limited solution, but does the job using the system's diff command without external tools:

diff -y  <(git show from-rev:the/file/path) <(git show to-rev:the/file/path)
  • filter just the change lines use --suppress-common-lines (if your diff supports the option).
  • no colors in this case, just the usual diff markers
  • can tweak the column width --width=term-width; in Bash can get the width as $COLUMNS or tput cols.

This can be wrapped into a helper git-script too for more convenience, for example, usage like this:

git diffy the/file/path --from rev1 --to rev2

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

Is it possible to run selenium (Firefox) web driver without a GUI?

Chrome now has a headless mode:

op = webdriver.ChromeOptions()
op.add_argument('--headless')
driver = webdriver.Chrome(options=op)

Forgot Oracle username and password, how to retrieve?

  1. Open Command Prompt/Terminal and type:

    sqlplus / as SYSDBA

  2. SQL prompt will turn up. Now type:

    ALTER USER existing_account_name IDENTIFIED BY new_password ACCOUNT UNLOCK;

  3. Voila! You've unlocked your account.

Function in JavaScript that can be called only once

Replace it with a reusable NOOP (no operation) function.

// this function does nothing
function noop() {};

function foo() {
    foo = noop; // swap the functions

    // do your thing
}

function bar() {
    bar = noop; // swap the functions

    // do your thing
}

WARNING: Can't verify CSRF token authenticity rails

if someone needs help related with Uploadify and Rails 3.2 (like me when I googled this post), this sample app may be helpful: https://github.com/n0ne/Uploadify-Carrierwave-Rails-3.2.3/blob/master/app/views/pictures/index.html.erb

also check the controller solution in this app

Tab space instead of multiple non-breaking spaces ("nbsp")?

It's much cleaner to use CSS. Try padding-left:5em or margin-left:5em as appropriate instead.

Place a button right aligned

This would solve it.

<input type="button" value="Text Here..." style="float: right;">

Good luck with your code!

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

Download pdf file using jquery ajax

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });

Free space in a CMD shell

A possible solution:

dir|find "bytes free"

a more "advanced solution", for Windows Xp and beyond:

wmic /node:"%COMPUTERNAME%" LogicalDisk Where DriveType="3" Get DeviceID,FreeSpace|find /I "c:"

The Windows Management Instrumentation Command-line (WMIC) tool (Wmic.exe) can gather vast amounts of information about about a Windows Server 2003 as well as Windows XP or Vista. The tool accesses the underlying hardware by using Windows Management Instrumentation (WMI). Not for Windows 2000.


As noted by Alexander Stohr in the comments:

  • WMIC can see policy based restrictions as well. (even if 'dir' will still do the job),
  • 'dir' is locale dependent.

How to duplicate sys.stdout to a log file?

As described elsewhere, perhaps the best solution is to use the logging module directly:

import logging

logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
logging.info('this should to write to the log file')

However, there are some (rare) occasions where you really want to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.

This is a way of redirecting stdout and stderr away from the shell using the logging module:

import logging, sys

class LogFile(object):
    """File-like object to log text using the `logging` module."""

    def __init__(self, name=None):
        self.logger = logging.getLogger(name)

    def write(self, msg, level=logging.INFO):
        self.logger.log(level, msg)

    def flush(self):
        for handler in self.logger.handlers:
            handler.flush()

logging.basicConfig(level=logging.DEBUG, filename='mylog.log')

# Redirect stdout and stderr
sys.stdout = LogFile('stdout')
sys.stderr = LogFile('stderr')

print 'this should to write to the log file'

You should only use this LogFile implementation if you really cannot use the logging module directly.

Select multiple columns using Entity Framework

You either want to select an anonymous type:

var dataset2 = from recordset 
               in entities.processlists 
               where recordset.ProcessName == processname 
               select new 
               {
                recordset.ServerName, 
                recordset.ProcessID, 
                recordset.Username
               };

But you cannot cast that to another type, so I guess you want something like this:

var dataset2 = from recordset 
               in entities.processlists 
               where recordset.ProcessName == processname 

               // Select new concrete type
               select new PInfo
               {
                ServerName = recordset.ServerName, 
                ProcessID = recordset.ProcessID, 
                Username = recordset.Username
               };

getting the ng-object selected with ng-change

This might give you some ideas

.NET C# View Model

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

How can I get current location from user in iOS

In iOS 6, the

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

is deprecated.

Use following code instead

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}

For iOS 6~8, the above method is still necessary, but you have to handle authorization.

_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
    [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
    //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
   ) {
     // Will open an confirm dialog to get user's approval 
    [_locationManager requestWhenInUseAuthorization]; 
    //[_locationManager requestAlwaysAuthorization];
} else {
    [_locationManager startUpdatingLocation]; //Will update location immediately 
}

This is the delegate method which handle user's authorization

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
    case kCLAuthorizationStatusNotDetermined: {
        NSLog(@"User still thinking..");
    } break;
    case kCLAuthorizationStatusDenied: {
        NSLog(@"User hates you");
    } break;
    case kCLAuthorizationStatusAuthorizedWhenInUse:
    case kCLAuthorizationStatusAuthorizedAlways: {
        [_locationManager startUpdatingLocation]; //Will update location immediately
    } break;
    default:
        break;
    }
}

PHP - iterate on string characters

For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

$string = "a sample string for testing";
$char = $string[4] // equals to m

I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):

$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m

This method is going to be faster cause we are using a real array and not assuming one to be an array.

Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

Using string[i]
0.24960017204285 Seconds

Using str_split
0.18720006942749 Seconds

Which means the second method is way faster.

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

How do I get a substring of a string in Python?

One example seems to be missing here: full (shallow) copy.

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

This is a common idiom for creating a copy of sequence types (not of interned strings), [:]. Shallow copies a list, see Python list slice syntax used for no obvious reason.

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

How do you share constants in NodeJS modules?

As an alternative, you can group your "constant" values in a local object, and export a function that returns a shallow clone of this object.

var constants = { FOO: "foo" }

module.exports = function() {
  return Object.assign({}, constants)
}

Then it doesn't matter if someone re-assigns FOO because it will only affect their local copy.

Delete all duplicate rows Excel vba

There's a RemoveDuplicates method that you could use:

Sub DeleteRows()

    With ActiveSheet
        Set Rng = Range("A1", Range("B1").End(xlDown))
        Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    End With

End Sub

How to right-align and justify-align in Markdown?

Specific to your usage of a Jupyter Notebook: the ability to specify table column alignment should return in a future release. (Current releases default to right-aligned everywhere.)

From PR #4130:

Allow markdown tables to specify their alignment with the :--, :--:, --: syntax while still allowing --- to default to right alignment.

This reverts a previous change (part of #2534) that stripped the alignment information from the rendered HTML coming out of the marked renderer. To be clear this does not change the right alignment default but does bring back support for overriding this alignment per column by using the gfm table alignment syntax.

...

how to change text in Android TextView

@user264892

I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.

So instead of:

String Status = "Asking Server...";
txtStatus.setText(Status);

try:

String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);

or:

String Status = "Asking Server...";    
txtStatus.setText("" + Status);

or, since your string is not dynamic, even better:

txtStatus.setText("AskingServer...");

Opening PDF String in new window with javascript

This one worked for me.

window.open("data:application/octet-stream;charset=utf-16le;base64,"+data64);

This one worked too

 let a = document.createElement("a");
 a.href = "data:application/octet-stream;base64,"+data64;
 a.download = "documentName.pdf"
 a.click();

how to set radio option checked onload with jQuery

Note this behavior when getting radio input values:

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

Install .ipa to iPad with or without iTunes

  • Goto http://buildtry.com

  • Upload .ipa (iOS) or .apk (Android) file

  • Copy and Share the link with testers

  • Open the link in iOS or Android device browser and click Install

Convert a space delimited string to list

Use string's split() method.

states.split()

Adding author name in Eclipse automatically to existing files

To old files I don't know how to do it... I think you will need a script to go thru all files and add the header.

To change the new ones you can do this.

Go to Eclipse menu bar

  1. Window menu.
  2. Preferences
  3. search for Templates
  4. go to Code templates
  5. click on +code
  6. Click on New Java files
  7. Click Edit
  8. add

/**
${user}
*/

And it's done every new File will have your name on it !

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

What exactly is nullptr?

When you have a function that can receive pointers to more than one type, calling it with NULL is ambiguous. The way this is worked around now is very hacky by accepting an int and assuming it's NULL.

template <class T>
class ptr {
    T* p_;
    public:
        ptr(T* p) : p_(p) {}

        template <class U>
        ptr(U* u) : p_(dynamic_cast<T*>(u)) { }

        // Without this ptr<T> p(NULL) would be ambiguous
        ptr(int null) : p_(NULL)  { assert(null == NULL); }
};

In C++11 you would be able to overload on nullptr_t so that ptr<T> p(42); would be a compile-time error rather than a run-time assert.

ptr(std::nullptr_t) : p_(nullptr)  {  }

Curl GET request with json parameter

This should work :

  curl -i -H "Accept: application/json" 'server:5050/a/c/getName{"param0":"pradeep"}'

use option -i instead of x.

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

How to encode URL to avoid special characters in Java?

Here is my solution which is pretty easy:

Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)

String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
    review = URLEncoder.encode(review,"utf-8");
    review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;

Telegram Bot - how to get a group chat id?

Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.

If you don't have telethon, run this:

pip install telethon

If you don't have a registered app with telegram, register one: enter image description here The link is this: https://my.telegram.org/

Then run the following code:

from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name

client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')

dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
                    i += 1  # 1-based index
                    print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))

You may want to send a message to your group so the group show up in top of the list.

Git merge two local branches

Here's a clear picture:

Assuming we have branch-A and branch-B

We want to merge branch-B into branch-A

on branch-B -> A: switch to branch-A

on branch-A: git merge branch-B

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.

public static void main(string[] args)
{
List names = new List();

names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);

string stringResult = names.Find( name => name.Equals(“Garima”));
}

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

How do I calculate the MD5 checksum of a file in Python?

In regards to your error and what's missing in your code. m is a name which is not defined for getmd5() function.

No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)

First, you are not using hashlib.md5.hexdigest() method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:

>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'

However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:

>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'

As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.

A simple solution could be something like that:

# Import hashlib library (md5 method is part of it)
import hashlib

# File to check
file_name = 'filename.exe'

# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'  

# Open,close, read file and calculate MD5 on its contents 
with open(file_name) as file_to_check:
    # read contents of the file
    data = file_to_check.read()    
    # pipe contents of the file through
    md5_returned = hashlib.md5(data).hexdigest()

# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
    print "MD5 verified."
else:
    print "MD5 verification failed!."

Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.

Best of luck.

ITextSharp HTML to PDF?

2020 UPDATE:

Converting HTML to PDF is very simple to do now. All you have to do is use NuGet to install itext7 and itext7.pdfhtml. You can do this in Visual Studio by going to "Project" > "Manage NuGet Packages..."

Make sure to include this dependency:

using iText.Html2pdf;

Now literally just paste this one liner and you're done:

HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));

If you're running this example in visual studio, your html file should be in the /bin/Debug directory.

If you're interested, here's a good resource. Also, note that itext7 is licensed under AGPL.

Download File Using jQuery

See here for a similar post on using jQuery to clear forms: Resetting a multi-stage form with jQuery

You may also be running into an issue where the values are being repopulated by the struts value stack. In other words, you submit your form, do whatever in the action class, but do not clear the related field values in the action class. In this scenario the form would appear to maintain the values you previously submitted. If you are persisting these in some way, just null each field value in your action class after persisting and prior to returning SUCCESS.

Running python script inside ipython

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

Display Bootstrap Modal using javascript onClick

A JavaScript function must first be made that holds what you want to be done:

function print() { console.log("Hello World!") }

and then that function must be called in the onClick method from inside an element:

<a onClick="print()"> ... </a>

You can learn more about modal interactions directly from the Bootstrap 3 documentation found here: http://getbootstrap.com/javascript/#modals

Your modal bind is also incorrect. It should be something like this, where "myModal" = ID of element:

$('#myModal').modal(options)

In other words, if you truly want to keep what you already have, put a "#" in front GSCCModal and see if that works.

It is also not very wise to have an onClick bound to a div element; something like a button would be more suitable.

Hope this helps!

Sys is undefined

Development Environment:
  • Dev-Env: VS 2012
  • FX: 4.0/4.5
  • Implementations: Master(ScriptManager + UpdatePanel/Timer) + Content (UpdatePanel)
  • Patterns: PageRouting.

Disclaimer:

If all the web.config solutions do not work for you and you have implemented PageRouting (IIS 7+), then the code snippet below will solve your problems.

Background:

Dont mean to Highjack this question but had the same problem as everyone else and implemented 100% of the suggestions here, with minor modifications for .Net 4.0/4.5, and none of them worked for me.

In my situation i had implemented Page Routing which was ghosting my problem. Basically it would work for about 20, or so, debug runs and then BAM would error out with the Sys is undefined error.

After reviewing a couple other posts, that got to talking about the Clean-URL logic, i remembered that i had done PageRouting setup's.

Here is the resource i used to build my patterns: Page Routing

My one-liner code fixed my VS2012 Debugging problem:

rts.Ignore("{resource}.axd/{*pathInfo}")    'Ignores any Resource cache references, used heavily in AJAX interactions.

Activating Anaconda Environment in VsCode

Simply use

  1. shift + cmd + P
  2. Search Select Interpreter

pyhton : Select Interpreter

  1. Select it and it will show you the list of your virtual environment created via conda and other python versions

Activating conda virtual environment

  1. select the environment and you are ready to go.

Quoting the 'Select and activate an environment' docs

Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.

TCPDF output without saving file

Use I for "inline" to send the PDF to the browser, opposed to F to save it as a file.

$pdf->Output('name.pdf', 'I');

UICollectionView - Horizontal scroll, horizontal layout?

1st approach

What about using UIPageViewController with an array of UICollectionViewControllers? You'd have to fetch proper number of items in each UICollectionViewController, but it shouldn't be hard. You'd get exactly the same look as the Springboard has.

2nd approach

I've thought about this and in my opinion you have to set:

self.collectionView.pagingEnabled = YES;

and create your own collection view layout by subclassing UICollectionViewLayout. From the custom layout object you can access self.collectionView, so you'll know what is the size of the collection view's frame, numberOfSections and numberOfItemsInSection:. With that information you can calculate cells' frames (in prepareLayout) and collectionViewContentSize. Here're some articles about creating custom layouts:

3rd approach

You can do this (or an approximation of it) without creating the custom layout. Add UIScrollView in the blank view, set paging enabled in it. In the scroll view add the a collection view. Then add to it a width constraint, check in code how many items you have and set its constant to the correct value, e.g. (self.view.frame.size.width * numOfScreens). Here's how it looks (numbers on cells show the indexPath.row): https://www.dropbox.com/s/ss4jdbvr511azxz/collection_view.mov If you're not satisfied with the way cells are ordered, then I'm afraid you'd have to go with 1. or 2.

SVN icon overlays not showing properly

I encountered same problem when I upgraded from Windows 7 to 10. Eventually I have to re-install SVN and reboot the system and it worked. However, I have to manually upgrade each SVN directory to new SVN 1.8 format (it showed up automatically on explorer on right click to upgrade the directory to latest version). Hope this helps.

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

Random color generator

Yet another random color generator:

var randomColor;
randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000 (randomColor is a float)
randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF (randomColor is an integer)
randomColor = randomColor.toString(16); // hex representation randomColor
randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
randomColor = "#" + randomColor; // # added

Transpose/Unzip Function (inverse of zip)?

While numpy arrays and pandas may be preferrable, this function imitates the behavior of zip(*args) when called as unzip(args).

Allows for generators, like the result from zip in Python 3, to be passed as args as it iterates through values.

def unzip(items, cls=list, ocls=tuple):
    """Zip function in reverse.

    :param items: Zipped-like iterable.
    :type  items: iterable

    :param cls: Container factory. Callable that returns iterable containers,
        with a callable append attribute, to store the unzipped items. Defaults
        to ``list``.
    :type  cls: callable, optional

    :param ocls: Outer container factory. Callable that returns iterable
        containers. with a callable append attribute, to store the inner
        containers (see ``cls``). Defaults to ``tuple``.
    :type  ocls: callable, optional

    :returns: Unzipped items in instances returned from ``cls``, in an instance
        returned from ``ocls``.
    """
    # iter() will return the same iterator passed to it whenever possible.
    items = iter(items)

    try:
        i = next(items)
    except StopIteration:
        return ocls()

    unzipped = ocls(cls([v]) for v in i)

    for i in items:
        for c, v in zip(unzipped, i):
            c.append(v)

    return unzipped

To use list cointainers, simply run unzip(zipped), as

unzip(zip(["a","b","c"],[1,2,3])) == (["a","b","c"],[1,2,3])

To use deques, or other any container sporting append, pass a factory function.

from collections import deque

unzip([("a",1),("b",2)], deque, list) == [deque(["a","b"]),deque([1,2])]

(Decorate cls and/or main_cls to micro manage container initialization, as briefly shown in the final assert statement above.)

How can I write variables inside the tasks file in ansible

I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache
  vars:
    url: czxcxz
  shell: wget {{url}} 

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Oracle - How to create a materialized view with FAST REFRESH and JOINS

To start with, from the Oracle Database Data Warehousing Guide:

Restrictions on Fast Refresh on Materialized Views with Joins Only

...

  • Rowids of all the tables in the FROM list must appear in the SELECT list of the query.

This means that your statement will need to look something like this:

CREATE MATERIALIZED VIEW MV_Test
  NOLOGGING
  CACHE
  BUILD IMMEDIATE 
  REFRESH FAST ON COMMIT 
  AS
    SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID 
    FROM TPM_PROJECTVERSION V,
         TPM_PROJECT P 
    WHERE P.PROJECTID = V.PROJECTID

Another key aspect to note is that your materialized view logs must be created as with rowid.

Below is a functional test scenario:

CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));

CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;

CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));

CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;

CREATE MATERIALIZED VIEW foo_bar
  NOLOGGING
  CACHE
  BUILD IMMEDIATE
  REFRESH FAST ON COMMIT  AS SELECT foo.foo, 
                                    bar.bar, 
                                    foo.ROWID AS foo_rowid, 
                                    bar.ROWID AS bar_rowid 
                               FROM foo, bar
                              WHERE foo.foo = bar.foo;

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Reading Data From Database and storing in Array List object

Try creating new instance of customer every time e.g.

         while (rs.next()) {

        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));
        customer.setName(rs.getString("name"));

        customer.setAddress(rs.getString("address"));
        customer.setPhone(rs.getString("phone"));
        customer.setEmail(rs.getString("email"));
        customer.setBountPoints(rs.getInt("bonuspoint"));
        customer.setTotalsale(rs.getInt("totalsale"));

        customers.add(customer);


    }

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

We use

wsdlLocation = "WEB-INF/wsdl/WSDL.wsdl"

In other words, use a path relative to the classpath.

I believe the WSDL may be needed at runtime for validation of messages during marshal/unmarshal.

Testing socket connection in Python

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

How can I read command line parameters from an R script?

FYI: there is a function args(), which retrieves the arguments of R functions, not to be confused with a vector of arguments named args

Styling HTML5 input type number

Unfortunately in HTML 5 the 'pattern' attribute is linked to only 4-5 attributes. However if you are willing to use a "text" field instead and convert to number later, this might help you;

This limits an input from 1 character (numberic) to 3.

<input name=quantity type=text pattern='[0-9]{1,3}'>

The CSS basically allows for confirmation with an "Thumbs up" or "Down".

Example 1

Example 2

Is there a list of Pytz Timezones?

In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.

pytz.construct("UTC-07:00")

which gives you Canada/Pacific timezone.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.

This is normally more an issue with ToMany than ToOnes. For example,

Select e from Employee e 
join fetch e.phones p 
where p.areaCode = '613'

This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.

Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

If you want to use default mailtrip.io you don't need to modify mail.php file.

  1. Create account on mailtrip.io
  2. Go to Inboxes > My Inbox > SMTP Settings > Integration Laravel
  3. Modify .env file and replace all nulls of correct credentials:
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
  1. Run:
php artisan config:cache

If you are using Gmail there is an instruction for Gmail: https://stackoverflow.com/a/64582540/7082164

What Regex would capture everything from ' mark to the end of a line?

https://regex101.com/r/Jjc2xR/1

/(\w*\(Hex\): w*)(.*?)(?= |$)/gm

I'm sure this one works, it will capture de hexa serial in the badly structured text multilined bellow

     Space Reservation: disabled
         Serial Number: wCVt1]IlvQWv
   Serial Number (Hex): 77435674315d496c76515776
               Comment: new comment

I'm a eternal newbie in regex but I'll try explain this one

(\w*(Hex): w*) : Find text in line where string contains "Hex: "

(.*?) This is the second captured text and means everything after

(?= |$) create a limit that is the space between = and the |

So with the second group, you will have the value

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}