Programs & Examples On #Orbited

Pre-HTML5 server that implements sockets for web browsers.

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

Iterating through list of list in Python

This traverse generator function can be used to iterate over all the values:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

Convert the values in a column into row names in an existing data frame

in one line

> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])

Passing a variable to a powershell script via command line

Using param to name the parameters allows you to ignore the order of the parameters:

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Capturing "Delete" Keypress with jQuery

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter.

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How can I get the timezone name in JavaScript?

Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone returns IANA timezone name by definition, which is in English.

If you want the timezone's name in current user's language, you can parse it from Date's string representation like so:

_x000D_
_x000D_
function getTimezoneName() {_x000D_
  const today = new Date();_x000D_
  const short = today.toLocaleDateString(undefined);_x000D_
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
  // Trying to remove date from the string in a locale-agnostic way_x000D_
  const shortIndex = full.indexOf(short);_x000D_
  if (shortIndex >= 0) {_x000D_
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
    _x000D_
    // by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
    // trim it from both sides_x000D_
    return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
  } else {_x000D_
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
    return full;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
_x000D_
_x000D_

Tested in Chrome and Firefox.

Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00) instead of a name. But I think it's still readable as a fallback.

P.S. Won't work in IE11, just as the Intl... solution.

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

Getting the exception value in Python

For python2, It's better to use e.message to get the exception message, this will avoid possible UnicodeDecodeError. But yes e.message will be empty for some kind of exceptions like OSError, in which case we can add a exc_info=True to our logging function to not miss the error.
For python3, I think it's safe to use str(e).

Comparing two files in linux terminal

Here is my solution for this :

mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english

What is causing "Unable to allocate memory for pool" in PHP?

This worked for our guys (running a slew of Wordpress sites on the same server).

Changed memory settings in the /etc/php.d/apc.ini file. It was set to 64M, so we doubled it to 128M.

apc.shm_size=128M

Is there a way to compile node.js source files?

You can use the Closure compiler to compile your javascript.

You can also use CoffeeScript to compile your coffeescript to javascript.

What do you want to achieve with compiling?

The task of compiling arbitrary non-blocking JavaScript down to say, C sounds very daunting.

There really isn't that much speed to be gained by compiling to C or ASM. If you want speed gain offload computation to a C program through a sub process.

nginx 502 bad gateway

Similar setup here and looks like it was just a bug in my code. At the start of my app I looked for the offending URL and this worked: echo '<html>test</html>'; exit();

In my case, turns out the problem was an uninitialized variable that only failed under peculiar circumstances.

How can I create download link in HTML?

A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:

<a href="path to resource.name of file">Link</a>

<a href="files/installer.exe">Link to installer</a>

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

SQL Server Group by Count of DateTime Per Hour?

I found this somewhere else. I like this answer!

SELECT [Hourly], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
    FROM table) idat
 GROUP BY [Hourly]

Unexpected character encountered while parsing value

I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string instead to an object or a JObject. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.

So, instead of:

[HttpPost("[action]")]
public object Search([FromBody] string data)

I had to use the more specific:

[HttpPost("[action]")]
public object Search([FromBody] JObject data)

On - window.location.hash - Change?

The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.


Update to keep this answer fresh:

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..
});

The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

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

What is an alternative to execfile in Python 3?

You could write your own function:

def xfile(afile, globalz=None, localz=None):
    with open(afile, "r") as fh:
        exec(fh.read(), globalz, localz)

If you really needed to...

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Quick easy way to migrate SQLite3 to MySQL?

This script is ok except for this case that of course, I've met :

INSERT INTO "requestcomparison_stopword" VALUES(149,'f');
INSERT INTO "requestcomparison_stopword" VALUES(420,'t');

The script should give this output :

INSERT INTO requestcomparison_stopword VALUES(149,'f');
INSERT INTO requestcomparison_stopword VALUES(420,'t');

But gives instead that output :

INSERT INTO requestcomparison_stopword VALUES(1490;
INSERT INTO requestcomparison_stopword VALUES(4201;

with some strange non-ascii characters around the last 0 and 1.

This didn't show up anymore when I commented the following lines of the code (43-46) but others problems appeared:


    line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
    line = line.replace('THIS_IS_TRUE', '1')
    line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
    line = line.replace('THIS_IS_FALSE', '0')

This is just a special case, when we want to add a value being 'f' or 't' but I'm not really comfortable with regular expressions, I just wanted to spot this case to be corrected by someone.

Anyway thanks a lot for that handy script !!!

Delete certain lines in a txt file via a batch file

If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}" should do the trick.

Text size of android design TabLayout tabs

Try the snipped which is mentioned below, it works for me also.

In my layout xml where I have my TabLayout, have added style to the TabLayout like below :

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/MyCustomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed" />

and in my style.xml I have defined the style that is used in my layout xml, check code for styles added below :

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="android:background">YOUR BACKGROUND COLOR</item>
    <item name="tabTextAppearance">@style/MyCustomTabText</item>
    <item name="tabSelectedTextColor">SELECTED TAB TEXT COLOR</item>
    <item name="tabIndicatorColor">SELECTED TAB INDICATOR COLOR</item>
</style>

<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
    <item name="android:textSize">YOUR TEXT SIZE</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@android:color/white</item>
</style>

I hope it will work for you.....

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

krosenvold's answer inspired the following script which does the following:

  • get the dd dump via ssh from a remote server (as gz file)
  • unzip the dump
  • convert it to vmware

the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.

In my environment 2 x Ubuntu 12.04 LTS the steps took:

  • 3 hours to get a 47 GByte disk dump of a 60 GByte partition
  • 20 minutes to unpack to a 60 GByte dd file
  • 45 minutes to create the vmware file
#!/bin/bash
# get a dd disk dump and convert it to vmware
#  see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
#  Author: wf  2014-10-1919

#
# get a dd dump from the given host's given disk and create a compressed
#   image at the given target 
#
#  1: host e.g. somehost.somedomain
#  2: disk e.g. sda
#  3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
  local l_host="$1"
  local l_disk="$2"
  local l_target="$3"
  echo "getting disk dump of $l_disk from $l_host"
  ssh $l_host sudo fdisk -l  | egrep "^/dev/$l_disk"
  if [ $? -ne 0 ]
  then
    echo "device $l_disk does not exist on host $l_host" 1>&2
    exit 1
  else
    if [ ! -f $l_target ]
    then
      ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
    else
      echo "$l_target already exists"
    fi
  fi
}

#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
  l_command="$1"
  l_package="$2"
  echo "checking that $l_command from package $l_package  is installed ..."
  which $l_command
  if [ $? -ne 0 ]
  then
    echo "installing $l_package to make $l_command available ..."
    sudo apt-get install $l_package 
  fi
}

#
# convert the given image to vmware
#  1: the dd dump image
#  2: the vmware image file to convert to
#
vmware_convert() {
  local l_ddimage="$1"
  local l_vmwareimage="$2"
  echo "converting dd image $l_image to vmware $l_vmwareimage"
  #  convert to VMware disk format showing progess
  # see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
  qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}

#
# show usage
#
usage() {
  echo "usage: $0 host device"
  echo "      host: the host to get the disk dump from e.g. frodo.lotr.org"  
  echo "            you need ssh and sudo privileges on that host"
  echo "
  echo "    device: the disk to dump from e.g. sda"
  echo ""
  echo "  examples:
  echo "       $0 frodo.lotr.org sda"
  echo "       $0 gandalf.lotr.org sdb"
  echo ""
  echo "  the needed packages pv and qemu-utils will be installed if not available"
  echo "  you need local sudo rights for this to work"
  exit 1
}

# check arguments
if [ $# -lt 2 ]
then
  usage
fi

# get the command line parameters
host="$1"
disk="$2"

# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
#   .gz the zipped dd
#   .dd the disk dump file
#   .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"

echo "$0 $host/$disk ->  $image"

# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv

# check if dd files was already loaded
#  we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
  getdump $host $disk $image.gz
else
  echo "$image.gz already downloaded"
fi

# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
  echo "uncompressing $image.gz"
  zcat $image.gz | pv -cN zcat > $image.dd
else
  echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
  vmware_convert $image.dd $image.vmdk
else
  echo "vmware image $image.vmdk already converted"
fi

How can one grab a stack trace in C?

There's backtrace(), and backtrace_symbols():

From the man page:

#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
    printf("%s\n", strs[i]);
}
free(strs);
...

One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:

class MyException : public std::exception {

    char ** strs;
    MyException( const std::string & message ) {
         int i, frames = backtrace(callstack, 128);
         strs = backtrace_symbols(callstack, frames);
    }

    void printStackTrace() {
        for (i = 0; i < frames; ++i) {
            printf("%s\n", strs[i]);
        }
        free(strs);
    }
};

...

try {
   throw MyException("Oops!");
} catch ( MyException e ) {
    e.printStackTrace();
}

Ta da!

Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.

How can you create multiple cursors in Visual Studio Code

Multi-word (and multi-line) cursors/selection in VS Code

Multi-word:

Windows / OS X:

  • Ctrl+Shift+L / ?+Shift+L selects all instances of the current highlighted word
  • Ctrl+D / ?+D selects the next instance... and the one after that... etc.

Multi-line:

For multi-line selection, Ctrl+Alt+Down / ?+Alt+Shift+Down will extend your selection or cursor position to the next line. Ctrl+Right / ?+Right will move to the end of each line, no matter how long. To escape the multi-line selection, hit Esc.

See the VS Code keybindings (OS sensitive)

Get a random boolean in python?

I was curious as to how the speed of the numpy answer performed against the other answers since this was left out of the comparisons. To generate one random bool this is much slower but if you wanted to generate many then this becomes much faster:

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.0906 usec per loop
$ python -m timeit -s "import numpy as np" "np.random.randint(2, size=1)"
100000 loops, best of 3: 4.65 usec per loop

$ python -m timeit -s "from random import random" "test = [random() < 0.5 for i in range(1000000)]"
10 loops, best of 3: 118 msec per loop
$ python -m timeit -s "import numpy as np" "test = np.random.randint(2, size=1000000)"
100 loops, best of 3: 6.31 msec per loop

Set up adb on Mac OS X

For Mac users : Step 1: Install the Android Studio

Step2 : Open the terminal and type

cd

Step 3: Type below mentioned command changing the userName:

export PATH=“/Users/{user_name}/Library/Android/sdk/platform-tools”:$PATH

How to count occurrences of a column value efficiently in SQL?

and if data in "age" column has similar records (i.e. many people are 25 years old, many others are 32 and so on), it causes confusion in aligning right count to each student. in order to avoid it, I joined the tables on student ID as well.

SELECT S.id, S.age, C.cnt
FROM Students S 
INNER JOIN (SELECT id, age, count(age) as cnt  FROM Students GROUP BY student,age) 
C ON S.age = C.age *AND S.id = C.id*

Angular 2 filter/search list

Search by multiple fields

Assuming Data:

items = [
  {
    id: 1,
    text: 'First item'
  },
  {
    id: 2,
    text: 'Second item'
  },
  {
    id: 3,
    text: 'Third item'
  }
];

Markup:

<input [(ngModel)]="query">
<div *ngFor="let item of items | search:'id,text':query">{{item.text}}</div>

Pipe:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || []).filter(item => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));

  }
}

One line for everything!

How to fix "containing working copy admin area is missing" in SVN?

I came across this problem when replacing a third party API library with a newer version, and none of the solutions here really worked for me because I wanted to replace the SVN version with the local version. My solution was as follows:

1) Move the offending folder to my home dir, delete it from SVN and commit:

mv foldercausingproblem ~/
svn --force delete foldercausingproblem
svn commit --message "Temporary removing folder with old API"

2) Put the folder back, add it to SVN and commit again:

mv ~/foldercausingproblem ./
svn --force add .
svn commit --message "Finally all working!"

Slightly irritating to have to commit twice, but it seems to have worked fine.

Format date in a specific timezone

.zone() has been deprecated, and you should use utcOffset instead:

// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Pip error: Microsoft Visual C++ 14.0 is required

You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

How to assign more memory to docker container

That 2GB limit you see is the total memory of the VM in which docker runs.

If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:

Docker Preferences

But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.

See this for Mac:

https://docs.docker.com/docker-for-mac/#memory

MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.

For Windows:

https://docs.docker.com/docker-for-windows/#advanced

Memory - Change the amount of memory the Docker for Windows Linux VM uses

How to hide a navigation bar from first ViewController in Swift?

I use a variant of the above, and isolate sections of my app to be embedded in differing NavControllers. This way, i don't have to reset visibility. Very useful in startup sequences, for example.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Look into python wheels to solve your problem. The best part of python wheels is that they let you install C extensions with no compilers. I just installed numpy and scipy using pip in a clean python install and they both worked fine.

How to save an HTML5 Canvas as an image on a server?

Send canvas image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP script:
photo_upload.php

<?php

    $data = $_POST['photo'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
    die;
?>

Checking during array iteration, if the current element is the last element

$myarray = array(
  'test1' => 'foo',
  'test2' => 'bar',
  'test3' => 'baz',
  'test4' => 'waldo'
);

$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);

// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.

$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz

Using HTTPS with REST in Java

Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.

how to print float value upto 2 decimal place without rounding off

The only easy way to do this is to use snprintf to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:

char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);

Can Selenium WebDriver open browser windows silently in the background?

One way to achieve this is by running the browser in headless mode. Another advantage of this is that tests are executed faster.

Please find the code below to set headless mode in the Chrome browser.

package chrome;

public class HeadlessTesting {

    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver",
                "ChromeDriverPath");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");
        options.addArguments("window-size=1200x600");
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://contentstack.built.io");
        driver.get("https://www.google.co.in/");
        System.out.println("title is: " + driver.getTitle());
        File scrFile = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("pathTOSaveFile"));
        driver.quit();
    }
}

Send email using java

It has been quite a while since this has been posted. But as of Nov 13, 2012 I can verify that port 465 still works.

Refer to GaryM's answer on this forum. I hope this helps few more people.

/*
* Created on Feb 21, 2005
*
*/

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleTest {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "" };


    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
            emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully mail to All Users");
    }

    public void sendSSLMessage(String recipients[], String subject,
                               String message, String from) throws MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxx", "xxxxxx");
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
}

pod install -bash: pod: command not found

Sudo-less installation

If you do not want to grant RubyGems admin privileges for this process, you can tell RubyGems to install into your user directory by passing either the --user-install flag to gem install or by configuring the RubyGems environment. The latter is in our opinion the best solution. To do this, create or edit the .profile file in your home directory and add or amend it to include these lines:

export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:$PATH

Note that if you choose to use the --user-install option, you will still have to configure your .profile file to set the PATH or use the command prepended by the full path. You can find out where a gem is installed with gem which cocoapods. E.g.

$ gem install cocoapods --user-install
$ gem which cocoapods
/Users/eloy/.gem/ruby/2.0.0/gems/cocoapods-0.29.0/lib/cocoapods.rb
$ /Users/eloy/.gem/ruby/2.0.0/bin/pod install

Source: https://guides.cocoapods.org/using/getting-started.html

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

Selectors in Objective-C?

From my understanding of the Apple documentation, a selector represents the name of the method that you want to call. The nice thing about selectors is you can use them in cases where the exact method to be called varies. As a simple example, you can do something like:

SEL selec;
if (a == b) {
selec = @selector(method1)
}
else
{
selec = @selector(method2)
};
[self performSelector:selec];

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

Why do I need an IoC container as opposed to straightforward DI code?

I'm with you, Vadim. IoC containers take a simple, elegant, and useful concept, and make it something you have to study for two days with a 200-page manual.

I personally am perplexed at how the IoC community took a beautiful, elegant article by Martin Fowler and turned it into a bunch of complex frameworks typically with 200-300 page manuals.

I try not to be judgemental (HAHA!), but I think that people who use IoC containers are (A) very smart and (B) lacking in empathy for people who aren't as smart as they are. Everything makes perfect sense to them, so they have trouble understanding that many ordinary programmers will find the concepts confusing. It's the curse of knowledge. The people who understand IoC containers have trouble believing that there are people who don't understand it.

The most valuable benefit of using an IoC container is that you can have a configuration switch in one place which lets you change between, say, test mode and production mode. For example, suppose you have two versions of your database access classes... one version which logged aggressively and did a lot of validation, which you used during development, and another version without logging or validation that was screamingly fast for production. It is nice to be able to switch between them in one place. On the other hand, this is a fairly trivial problem easily handled in a simpler way without the complexity of IoC containers.

I believe that if you use IoC containers, your code becomes, frankly, a lot harder to read. The number of places you have to look at to figure out what the code is trying to do goes up by at least one. And somewhere in heaven an angel cries out.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Angular 4 - get input value

If you want to read only one field value, I think, using the template reference variables is the easiest way

Template

<input #phone placeholder="phone number" />

<input type="button" value="Call" (click)="callPhone(phone.value)" />

**Component** 
 
callPhone(phone): void 
{
  
console.log(phone);

}

If you have a number of fields, using the reactive form one of the best ways.

This application has no explicit mapping for /error

All I have done to solve this kind of problem is to mention anotation @Configuration in MVCConfig Class.

Like this one :

package com.example;

/**
 * Created by sartika.s.hasibuan on 1/10/2017.
 */
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

Java unsupported major minor version 52.0

You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.

rails simple_form - hidden field - create?

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

'uint32_t' identifier not found error

You can #include <cstdint>. It's part of C++-standard since 2011.

How do I create a file and write to it?

File reading and writing using input and outputstream:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}

Different color for each bar in a bar chart; ChartJS

As of v2, you can simply specify an array of values to correspond to a color for each bar via the backgroundColor property:

datasets: [{
  label: "My First dataset",
  data: [20, 59, 80, 81, 56, 55, 40],
  backgroundColor: ["red", "blue", "green", "blue", "red", "blue"], 
}],

This is also possible for the borderColor, hoverBackgroundColor, hoverBorderColor.

From the documentation on the Bar Chart Dataset Properties:

Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on.

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

UITapGestureRecognizer - single tap and double tap

UITapGestureRecognizer *singleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSingleTap)] autorelease];
singleTap.numberOfTapsRequired = 1; 
[self.view addGestureRecognizer:singleTap];

UITapGestureRecognizer *doubleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doDoubleTap)] autorelease];
doubleTap.numberOfTapsRequired = 2; 
[self.view addGestureRecognizer:doubleTap];

[singleTap requireGestureRecognizerToFail:doubleTap];

Note: If you are using numberOfTouchesRequired it has to be .numberOfTouchesRequired = 1;

For Swift

let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didPressPartButton))
singleTapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTapGesture)

let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTap))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)

singleTapGesture.require(toFail: doubleTapGesture)

How to get the selected value from RadioButtonList?

Using your radio button's ID, try rb.SelectedValue.

How to upload file using Selenium WebDriver in Java

First make sure that the input element is visible

As stated by Mark Collin in the discussion here:

Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.

Instead you can use:

driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");

myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.

Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">

Object of class stdClass could not be converted to string

In General to get rid of

Object of class stdClass could not be converted to string.

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

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

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

        )

)

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

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

Will give the result as 2

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I had this in VS2015 and my fix was to change the first line in my WebConfig from

<?xml version="1.0" encoding="utf-8"?>

to

<?xml version="1.0"?>

Curious.

How to check if a map contains a key in Go?

As noted by other answers, the general solution is to use an index expression in an assignment of the special form:

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]

This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a bool value is assignable. The first value of the result of this special form will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.

It's important to know that if the indexed map value is nil or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:

m := map[int]string{}
s := m[1] // s will be the empty string ""
var m2 map[int]float64 // m2 is nil!
f := m2[2] // f will be 0.0

fmt.Printf("%q %f", s, f) // Prints: "" 0.000000

Try it on the Go Playground.

So if we know that we don't use the zero value in our map, we can take advantage of this.

For example if the value type is string, and we know we never store entries in the map where the value is the empty string (zero value for the string type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:

m := map[int]string{
    0: "zero",
    1: "one",
}

fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
    m[0] != "", m[1] != "", m[2] != "")

Output (try it on the Go Playground):

Key 0 exists: true
Key 1 exists: true
Key 2 exists: false

In practice there are many cases where we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value nil, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it to nil.

Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition

Getting the zero value of the value type when indexing with a non-existing key also allows us to use maps with bool values conveniently as sets. For example:

set := map[string]bool{
    "one": true,
    "two": true,
}

fmt.Println("Contains 'one':", set["one"])

if set["two"] {
    fmt.Println("'two' is in the set")
}
if !set["three"] {
    fmt.Println("'three' is not in the set")
}

It outputs (try it on the Go Playground):

Contains 'one': true
'two' is in the set
'three' is not in the set

See related: How can I create an array that contains unique strings?

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

Select2() is not a function

For me, select2.min.js file worked instead of select2.full.min.js. I have manually define files which I have copied from dist folder that I got from github page. Also make sure that you have one jQuery(document).ready(...) definition and jquery file imported before select2 file.

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

Generating a random hex color code with PHP

Shortest way:

echo substr(uniqid(),-6); // result: 5ebf06

Detect page change on DataTable

I've not found anything in the API, but one thing you could do is attach an event handler to the standard paginator and detect if it has changed:

$('.dataTables_length select').live('change', function(){
       alert(this.value);
    });

Change the Theme in Jupyter Notebook?

Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:

enter image description here

enter image description here

I hope it helps.

API vs. Webservice

API(Application Programming Interface), the full form itself suggests that its an Interface which allows you to program for your application with the help or support of some other Application's Interface which exposes some sort of functionality which is useful to your application.

E.g showing updated currency exchange rates on your website would need some third party Interface to program against unless you plan to have your own database with currency rates and regular updates to the same. This set of functionality is when already available with some one else and when they want to share it with others they have to have an endpoint to communicate with the others who are interested in such interactions so they deploy it on web by the means of web-services. This end point is nothing but interface of their application which you can program against hence API.

What are the best PHP input sanitizing functions?

You use mysql_real_escape_string() in code similar to the following one.

$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
  mysql_real_escape_string($user),
  mysql_real_escape_string($password)
);

As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:

If binary data is to be inserted, this function must be used.

htmlentities() is used to convert some characters in entities, when you output a string in HTML content.

How to open every file in a folder

Os

You can list all files in the current directory using os.listdir:

import os
for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Glob

Or you can list only some files, depending on the file pattern using the glob module:

import glob
for filename in glob.glob('*.txt'):
   with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Pipe Or you can even use the pipe as you specified using fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

And then use it with piping:

ls -1 | python parse.py

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to calculate the sum of the datatable column in asp.net?

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))
    .ToString();

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )
    .ToString();

Running Node.Js on Android

the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7

It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare

You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.

How do you convert Html to plain text?

HTTPUtility.HTMLEncode() is meant to handle encoding HTML tags as strings. It takes care of all the heavy lifting for you. From the MSDN Documentation:

If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and >, are encoded as &lt; and &gt; for HTTP transmission.

HTTPUtility.HTMLEncode() method, detailed here:

public static void HtmlEncode(
  string s,
  TextWriter output
)

Usage:

String TestString = "This is a <Test String>.";
StringWriter writer = new StringWriter();
Server.HtmlEncode(TestString, writer);
String EncodedString = writer.ToString();

What is %timeit in python?

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

What is the difference between ng-if and ng-show/ng-hide

The ng-if directive removes the content from the page and ng-show/ng-hide uses the CSS display property to hide content.

This is useful in case you want to use :first-child and :last-child pseudo selectors to style.

TypeError: 'NoneType' object is not iterable in Python

It means the value of data is None.

CSS pseudo elements in React

You can use styled components.

Install it with npm i styled-components

import React from 'react';
import styled from 'styled-components';

const YourEffect = styled.div`
  height: 50px;
  position: relative;
  &:after {
    // whatever you want with normal CSS syntax. Here, a custom orange line as example
    content: '';
    width: 60px;
    height: 4px;
    background: orange
    position: absolute;
    bottom: 0;
    left: 0;
  },

const YourComponent = props => {
  return (
    <YourEffect>...</YourEffect>
  )
}

export default YourComponent

how to define ssh private key for servers fetched by dynamic inventory in files

You can simply define the key to use directly when running the command:

ansible-playbook \
        \ # Super verbose output incl. SSH-Details:
    -vvvv \
        \ # The Server to target: (Keep the trailing comma!)
    -i "000.000.0.000," \
        \ # Define the key to use:
    --private-key=~/.ssh/id_rsa_ansible \
        \ # The `env` var is needed if `python` is not available:
    -e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
        \ # Dry–Run:
    --check \
    deploy.yml

Copy/ Paste:

ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml

Create Map in Java

With the newer Java versions (i.e., Java 9 and forwards) you can use :

Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)

generically:

Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)

Bear in mind however that Map.of only works for at most 10 entries, if you have more than 10 entries that you can use :

Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2,  new Point2D.Double(100, 50)), ...);

Get href attribute on jQuery

Use $(this) for get the desire element.

function openAll()
{
     $("tr.b_row").each(function(){
        var a_href = $(this).find('.cpt h2 a').attr('href');
        alert ("Href is: "+a_href);
     });
}

How do I remove newlines from a text file?

You are missing the most obvious and fast answer especially when you need to do this in GUI in order to fix some weird word-wrap.

  • Open gedit

  • Then Ctrl + H, then put in the Find textbox \n and in Replace with an empty space then fill checkbox Regular expression and voila.

Download Excel file via AJAX MVC

I am using Asp.Net WebForm and just I wanna to download a file from server side. There is a lot article but I cannot find just basic answer. Now, I tried a basic way and got it.

That's my problem.

I have to create a lot of input button dynamically on runtime. And I want to add each button to download button with giving an unique fileNumber.

I create each button like this:

_x000D_
_x000D_
fragment += "<div><input type=\"button\" value=\"Create Excel\" onclick=\"CreateExcelFile(" + fileNumber + ");\" /></div>";
_x000D_
_x000D_
_x000D_

Each button call this ajax method.

_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: 'index.aspx/CreateExcelFile',_x000D_
    data: jsonData,_x000D_
    contentType: 'application/json; charset=utf-8',_x000D_
    dataType: 'json',_x000D_
    success: function (returnValue) {_x000D_
      window.location = '/Reports/Downloads/' + returnValue.d;_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

Then I wrote a basic simple method.

[WebMethod]
public static string CreateExcelFile2(string fileNumber)
{
    string filePath = string.Format(@"Form_{0}.xlsx", fileNumber);
    return filePath;
}

I am generating this Form_1, Form_2, Form_3.... And I am going to delete this old files with another program. But if there is a way to just sending byte array to download file like using Response. I wanna to use it.

I hope this will be usefull for anyone.

get current date with 'yyyy-MM-dd' format in Angular 4

If you only want to display then you can use date pipe in HTML like this :

Just Date:

your date | date: 'dd MMM yyyy'

Date With Time:

your date | date: 'dd MMM yyyy hh:mm a'

And if you want to take input only date from new Date() then :

You can use angular formatDate() in ts file like this -

currentDate = new Date();

const cValue = formatDate(currentDate, 'yyyy-MM-dd', 'en-US');

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

The problem it's in this class:

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
    //SpringApplication.run(Application.class, args);
    SpringApplication.run(ScheduledTasks.class, args);
    }
}

The correct way to launch your application is:

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    }
}

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

npm check and update package if needed

npm outdated will identify packages that should be updated, and npm update <package name> can be used to update each package. But prior to [email protected], npm update <package name> will not update the versions in your package.json which is an issue.

The best workflow is to:

  1. Identify out of date packages
  2. Update the versions in your package.json
  3. Run npm update to install the latest versions of each package

Check out npm-check-updates to help with this workflow.

  • Install npm-check-updates
  • Run npm-check-updates to list what packages are out of date (basically the same thing as running npm outdated)
  • Run npm-check-updates -u to update all the versions in your package.json (this is the magic sauce)
  • Run npm update as usual to install the new versions of your packages based on the updated package.json

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

JavaScript: Parsing a string Boolean value?

Why not keep it simple?

var parseBool = function(str) {
    if (typeof str === 'string' && str.toLowerCase() == 'true')
            return true;

    return (parseInt(str) > 0);
}

How do I modify fields inside the new PostgreSQL JSON datatype?

I wrote small function for myself that works recursively in Postgres 9.4. Here is the function (I hope it works well for you):

CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
    result JSONB;
    v RECORD;
BEGIN
    IF jsonb_typeof(val2) = 'null'
    THEN 
        RETURN val1;
    END IF;

    result = val1;

    FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP

        IF jsonb_typeof(val2->v.key) = 'object'
            THEN
                result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
            ELSE
                result = result || jsonb_build_object(v.key, v.value);
        END IF;
    END LOOP;

    RETURN result;
END;
$$ LANGUAGE plpgsql;

Here is sample use:

select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                            jsonb_update                             
---------------------------------------------------------------------
 {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)

As you can see it analyze deep down and update/add values where needed.

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

Make an HTTP request with android

I made this for a webservice to requerst on URL, using a Gson lib:

Client:

public EstabelecimentoList getListaEstabelecimentoPorPromocao(){

        EstabelecimentoList estabelecimentoList  = new EstabelecimentoList();
        try{
            URL url = new URL("http://" +  Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            if (con.getResponseCode() != 200) {
                    throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
            estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
            con.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return estabelecimentoList;
}

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

If it is still not working after giving permissions try running these commands:

mkdir ~/.npm-global

npm config set prefix '~/.npm-global'

export PATH=~/.npm-global/bin:$PATH

source ~/.profile

and finally test with this command

npm install -g jshint

This does not work for Windows.

How to get the element clicked (for the whole document)?

You can find the target element in event.target:

$(document).click(function(event) {
    console.log($(event.target).text());
});

References:

How do I specify local .gem files in my Gemfile?

By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.

org.json.simple cannot be resolved

I was facing same issue in my Spring Integration project. I added below JSON dependencies in pom.xml file. It works for me.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>

A list of versions can be found here: https://mvnrepository.com/artifact/org.json/json

ng: command not found while creating new project using angular-cli

Run below commands:

npm uninstall -g angular-cli

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

alias ng="C:/Users/itaas/.npm-global/ng" ( Location of ng file in npm folder)

And finally run :

ng -v 

Ng-v

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I ran into this same issue on a new install of mysql 5.5 on a mac. I tried to drop the test schema and got an errno 17 message. errno 17 is the error returned by some posix os functions indicating that a file exists where it should not. In the data directory, I found a strange file ".empty":

sh-3.2# ls -la data/test
total 0
drwxr-xr-x   3 _mysql  wheel  102 Apr 15 12:36 .
drwxr-xr-x  11 _mysql  wheel  374 Apr 15 12:28 ..
-rw-r--r--   1 _mysql  wheel    0 Mar 31 10:19 .empty

Once I rm'd the .empty file, the drop database command succeeded.

I don't know where the .empty file came from; as noted, this was a new mysql install. Perhaps something went wrong in the install process.

How do I install opencv using pip?

  1. Open terminal
  2. Run the following command pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org opencv-python.
  3. Hope it will work.

How to initialise a string from NSData in Swift

This is how you should initialize the NSString:

Swift 2.X or older

let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)

Swift 3 or newer:

let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)

This doc explains the syntax.

Read CSV file column by column

I am sorry, but none of these answers provide an optimal solution. If you use a library such as OpenCSV you will have to write a lot of code to handle special cases to extract information from specific columns.

For example, if you have rows with less columns than what you're after, you'll have to write a lot of code to handle it. Using the OpenCSV example:

  CSVReader reader = new CSVReader(new FileReader(strFile));
  String [] nextLine;
  while ((nextLine = reader.readNext()) != null) {
       //let's say you are interested in getting columns 20, 30, and 40
       String[] outputRow = new String[3];
       if(parsedRow.length < 40){
            outputRow[2] = null;
       } else {
            outputRow[2] = parsedRow[40]
       }
       if(parsedRow.length < 30){
            outputRow[1] = null;
       } else {
            outputRow[1] = parsedRow[30]
       }
       if(parsedRow.length < 20){
            outputRow[0] = null;
       } else {
            outputRow[0] = parsedRow[20]
       }

  }

This is a lot of code for a simple requirement. It gets worse if you are trying to get values of columns by name. You should use a more modern parser such as the one provided by uniVocity-parsers.

To reliably and easily get the columns you want, simply write:

CsvParserSettings settings = new CsvParserSettings();
parserSettings.selectIndexes(20, 30, 40);
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

How can I schedule a job to run a SQL query daily?

Here's a sample code:

Exec sp_add_schedule
    @schedule_name = N'SchedulName' 
    @freq_type = 1
    @active_start_time = 08300

How do I move a file from one location to another in Java?

Just add the source and destination folder paths.

It will move all the files and folder from source folder to destination folder.

    File destinationFolder = new File("");
    File sourceFolder = new File("");

    if (!destinationFolder.exists())
    {
        destinationFolder.mkdirs();
    }

    // Check weather source exists and it is folder.
    if (sourceFolder.exists() && sourceFolder.isDirectory())
    {
        // Get list of the files and iterate over them
        File[] listOfFiles = sourceFolder.listFiles();

        if (listOfFiles != null)
        {
            for (File child : listOfFiles )
            {
                // Move files to destination folder
                child.renameTo(new File(destinationFolder + "\\" + child.getName()));
            }

            // Add if you want to delete the source folder 
            sourceFolder.delete();
        }
    }
    else
    {
        System.out.println(sourceFolder + "  Folder does not exists");
    }

Twitter Bootstrap Button Text Word Wrap

You can add these style's and it works just as expected.

.btn {
    white-space:normal !important; 
    word-wrap: break-word; 
    word-break: normal;
}

Looping through all the properties of object php

Before you run the $object through a foreach loop you have to convert it to an array:

$array = (array) $object;  

 foreach($array as $key=>$val){
      echo "$key: $val";
      echo "<br>";
 }

How do I send an HTML Form in an Email .. not just MAILTO

> 2020 Answer = The Easy Way using Google Apps Script (5 Mins)

We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!

Send Email From an HTML Form Without a Backend (Server) via Google!

The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Brief Overview

A. Using the sample script, deploy a Google App Script

Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js

3-script-editor-showing-script

remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.

B. Create your HTML Form and Set the action to the App URL

Using the sample html file: index.html create a basic form.

7-html-form

remember to paste your APP URL into the form action in the HTML form.

C. Test the HTML Form in your Browser

Open the HTML Form in your Browser, Input some data & submit it!

html form

Submit the form. You should see a confirmation that it was sent: form sent

Open the inbox for the email address you set (above)

email received

Done.

Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Use jQuery to hide a DIV when the user clicks outside of it

$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

React JS onClick event handler

Here is how you define a react onClick event handler, which was answering the question title... using es6 syntax

import React, { Component } from 'react';

export default class Test extends Component {
  handleClick(e) {
    e.preventDefault()
    console.log(e.target)
  }

  render() {
    return (
      <a href='#' onClick={e => this.handleClick(e)}>click me</a>
    )
  }
}

How do you use math.random to generate random ints?

As an alternative, if there's not a specific reason to use Math.random(), use Random.nextInt():

import java.util.Random;

Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.

How do I round to the nearest 0.5?

Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.

Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

android - listview get item view by position

workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
        viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
    }
});

Numpy - add row to array

If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:

import numpy as np 
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.

What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.

The limits for int (32 bit) are:

int: –2147483648 to 2147483647 
uint: 0 to 4294967295 

And for long (64 bit):

long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

So, eventually I did that thing that all developers hate doing. I went and checked the server log files and found a report of a syntax error in line n.

tail -n 20 /var/log/apache2/error.log

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

AttributeError: 'DataFrame' object has no attribute

value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:

df['accepted'].value_counts()

It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using

df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Build error: You must add a reference to System.Runtime

i added System.Runtime.dll to bin project and it worked :)

compareTo with primitives -> Integer / int

If you need just logical value (as it almost always is), the following one-liner will help you:

boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);

And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.

This one will do too:

boolean ifIntsEqual = !((Math.abs(a-b)) > 0);

How does bitshifting work in Java?

Shift Operators

The binary 32 bits for 00101011 is

00000000 00000000 00000000 00101011, and the result is:

  00000000 00000000 00000000 00101011   >> 2(times)
 \\                                 \\
  00000000 00000000 00000000 00001010

Shifts the bits of 43 to right by distance 2; fills with highest(sign) bit on the left side.

Result is 00001010 with decimal value 10.

00001010
    8+2 = 10

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Two of them always produce the same answer:

  • COUNT(*) counts the number of rows
  • COUNT(1) also counts the number of rows

Assuming the pk is a primary key and that no nulls are allowed in the values, then

  • COUNT(pk) also counts the number of rows

However, if pk is not constrained to be not null, then it produces a different answer:

  • COUNT(possibly_null) counts the number of rows with non-null values in the column possibly_null.

  • COUNT(DISTINCT pk) also counts the number of rows (because a primary key does not allow duplicates).

  • COUNT(DISTINCT possibly_null_or_dup) counts the number of distinct non-null values in the column possibly_null_or_dup.

  • COUNT(DISTINCT possibly_duplicated) counts the number of distinct (necessarily non-null) values in the column possibly_duplicated when that has the NOT NULL clause on it.

Normally, I write COUNT(*); it is the original recommended notation for SQL. Similarly, with the EXISTS clause, I normally write WHERE EXISTS(SELECT * FROM ...) because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.

What does SQL clause "GROUP BY 1" mean?

It will group by first field in the select clause

Why is my CSS style not being applied?

I also faced this issue. And this how it got resolved!

My css filename was gt.css. I was working on Visual Studio (eg.2017).

  • I went to solution explorer (press Ctrl+Alt+L) and searched gt.css (enter your css filename). Right click on your css filename and then on Bundler and Minifier (4th option curently) and then Re-Bundle file (or directly press Shift+Alt+F).
  • Save any unsaved file, then empty cache and hard reload your web browser.

You can learn more about Bundler and Minifier here.

How to sum a list of integers with java streams?

class Pojo{
    int num;

    public Pojo(int num) {
        super();
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

List<Pojo> list = new ArrayList<Pojo>();
            list.add(new Pojo(1));
            list.add(new Pojo(5));
            list.add(new Pojo(3));
            list.add(new Pojo(4));
            list.add(new Pojo(5));

            int totalSum = list.stream().mapToInt(pojo -> pojo.getNum()).sum();
            System.out.println(totalSum);

Select From all tables - MySQL

You can get all tables that has column "Product" from information_Schema.columns

SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";

Nor create a procedure

delimiter //
CREATE PROCEDURE curdemo()
BEGIN
  DECLARE a varchar(100); 
  DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";
  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO a;

    SELECT * FROM a;

  END LOOP;

  CLOSE cur1;
END;

delimiter ;

call curdemo();

Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

Can I use GDB to debug a running process?

If one want to attach a process, this process must have the same owner. The root is able to attach to any process.

Is there a CSS selector by class prefix?

This is not possible with CSS selectors. But you could use two classes instead of one, e.g. status and important instead of status-important.

is inaccessible due to its protection level

You organized class interface such that public members begin with "my". Therefore you must use only those members. Instead of

myScoreonHole.hole = Console.ReadLine();

you should write

myScoreonHole.myhole = Console.ReadLine();

MYSQL import data from csv using LOAD DATA INFILE

You probably need to set the FIELDS TERMINATED BY ',' or whatever the delimiter happens to be.

For a CSV file, your statement should look like this:

LOAD DATA INFILE 'data.csv' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

python requests get cookies

If you need the path and thedomain for each cookie, which get_dict() is not exposes, you can parse the cookies manually, for instance:

[
    {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
    for c in session.cookies
]

What does ||= (or-equals) mean in Ruby?

unless x x = y end

unless x has a value (it's not nil or false), set it equal to y

is equivalent to

x ||= y

Select multiple value in DropDownList using ASP.NET and C#

Take a look at the ListBox control to allow multi-select.

<asp:ListBox runat="server" ID="lblMultiSelect" SelectionMode="multiple">
            <asp:ListItem Text="opt1" Value="opt1" />
            <asp:ListItem Text="opt2" Value="opt2" />
            <asp:ListItem Text="opt3" Value="opt3" />
</asp:ListBox> 

in the code behind

foreach(ListItem listItem in lblMultiSelect.Items)
    {
       if (listItem.Selected)
       {
          var val = listItem.Value;
          var txt = listItem.Text; 
       }
    }

UITableViewCell Selected Background Color on Multiple Selection

Swift 3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.darkGray
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.clear
}

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Here is Kotlin version.
Thanks you :)

         fun unSafeOkHttpClient() :OkHttpClient.Builder {
            val okHttpClient = OkHttpClient.Builder()
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts:  Array<TrustManager> = arrayOf(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                    override fun getAcceptedIssuers(): Array<X509Certificate>  = arrayOf()
                })

                // Install the all-trusting trust manager
                val  sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                if (trustAllCerts.isNotEmpty() &&  trustAllCerts.first() is X509TrustManager) {
                    okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
                    okHttpClient.hostnameVerifier { _, _ -> true }
                }

                return okHttpClient
            } catch (e: Exception) {
                return okHttpClient
            }
        }

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

How can I create an object and add attributes to it?

Coming to this late in the day but here is my pennyworth with an object that just happens to hold some useful paths in an app but you can adapt it for anything where you want a sorta dict of information that you can access with getattr and dot notation (which is what I think this question is really about):

import os

def x_path(path_name):
    return getattr(x_path, path_name)

x_path.root = '/home/x'
for name in ['repository', 'caches', 'projects']:
    setattr(x_path, name, os.path.join(x_path.root, name))

This is cool because now:

In [1]: x_path.projects
Out[1]: '/home/x/projects'

In [2]: x_path('caches')
Out[2]: '/home/x/caches'

So this uses the function object like the above answers but uses the function to get the values (you can still use (getattr, x_path, 'repository') rather than x_path('repository') if you prefer).

How to create a folder with name as current date in batch (.bat) files

https://stackoverflow.com/a/31789045/1010918 foxidrive's answer helped me get the folder with the date and time I wanted. I would like to share this method here since it worked great for me and I think it could help other people too, regardless of their locale.

rem The four lines below will give you reliable YY DD MM YYYY HH Min Sec MS variables in XP Pro and higher.

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

 set "dirname=%YYYY%-%MM%-%DD% %HH%-%Min%-%Sec%"

 :: remove echo here if you like
 echo "dirName"="%dirName%"

Replace multiple whitespaces with single whitespace in JavaScript string

Here's a non-regex solution (just for fun):

_x000D_
_x000D_
var s = ' a   b   word word. word, wordword word   ';

// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"

// or ES2015:
s = s.split(' ').filter(n => n).join(' '); 
console.log(s); // "a b word word. word, wordword word"
_x000D_
_x000D_
_x000D_

Can even substitute filter(n => n) with .filter(String)

It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.

Big-oh vs big-theta

Bonus: why do people seemingly always use big-oh when talking informally?

Because in big-oh, this loop:

for i = 1 to n do
    something in O(1) that doesn't change n and i and isn't a jump

is O(n), O(n^2), O(n^3), O(n^1423424). big-oh is just an upper bound, which makes it easier to calculate because you don't have to find a tight bound.

The above loop is only big-theta(n) however.

What's the complexity of the sieve of eratosthenes? If you said O(n log n) you wouldn't be wrong, but it wouldn't be the best answer either. If you said big-theta(n log n), you would be wrong.

Can I restore a single table from a full mysql mysqldump file?

Most modern text editors should be able to handle a text file that size, if your system is up to it.

Anyway, I had to do that once very quickly and i didnt have time to find any tools. I set up a new MySQL instance, imported the whole backup and then spit out just the table I wanted.

Then I imported that table into the main database.

It was tedious but rather easy. Good luck.

IF EXISTS before INSERT, UPDATE, DELETE for optimization

That is not useful for just one update/delete/insert.
Possibly adds performance if several operators after if condition.
In last case better write

update a set .. where ..
if @@rowcount > 0 
begin
    ..
end

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

How to give a user only select permission on a database

You could add the user to the Database Level Role db_datareader.

Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

See Books Online for reference:

http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx

You can add a database user to a database role using the following query:

EXEC sp_addrolemember N'db_datareader', N'userName'

Python: read all text file lines in loop

Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the with syntax).

with open('fileName', 'r') as f:
    for line in f:
       if 'str' in line:
           break

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

Android – Listen For Incoming SMS Messages

broadcast implementation on Kotlin:

 private class SmsListener : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d(TAG, "SMS Received!")

        val txt = getTextFromSms(intent?.extras)
        Log.d(TAG, "message=" + txt)
    }

    private fun getTextFromSms(extras: Bundle?): String {
        val pdus = extras?.get("pdus") as Array<*>
        val format = extras.getString("format")
        var txt = ""
        for (pdu in pdus) {
            val smsmsg = getSmsMsg(pdu as ByteArray?, format)
            val submsg = smsmsg?.displayMessageBody
            submsg?.let { txt = "$txt$it" }
        }
        return txt
    }

    private fun getSmsMsg(pdu: ByteArray?, format: String?): SmsMessage? {
        return when {
            SDK_INT >= Build.VERSION_CODES.M -> SmsMessage.createFromPdu(pdu, format)
            else -> SmsMessage.createFromPdu(pdu)
        }
    }

    companion object {
        private val TAG = SmsListener::class.java.simpleName
    }
}

Note: In your manifest file add the BroadcastReceiver-

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add this permission:

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

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

Years later, but for what it's worth - This is simple to do.

  • Just RENAME the C:\xampp directory

  • Install the desired new version of XAMPP

  • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

In Fedora 21 and up, you simply open a terminal and install the Ruby Development files as root.

dnf install ruby-devel

Adding a right click menu to an item

Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).

Hope this helps:

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");

pictureBox1.ContextMenu = cm;

How to take last four characters from a varchar?

Use the RIGHT() function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

How can I change a button's color on hover?

a.button:hover{
    background: #383;  }

works for me but in my case

#buttonClick:hover {
background-color:green;  }

Selecting multiple columns in a Pandas dataframe

If you want to get one element by row index and column name, you can do it just like df['b'][0]. It is as simple as you can imagine.

Or you can use df.ix[0,'b'] - mixed usage of index and label.

Note: Since v0.20, ix has been deprecated in favour of loc / iloc.

Difference between Spring MVC and Spring Boot

Without repeating the same thing in previous answers,
I'm writing this answer for the people who are looking to starting a new project and don't know which is the best framework to startup your project. If you are a beginner to this framework the best thing I prefer is Use spring boot(with STS /Spring Tool Suite). Because it helps a lot. Its do all configurations on its own. Additionally, use Hibernate with spring-boot as a database framework. With this combination, your application will be the best. I can guarantee that with my experiences.

Even this is one of the best frameworks for JEE(in present) this is gonna die in the near future. There are lightweight alternatives coming up. So keep updated with your experience don't stick to one particular framework. The best thing is being fluent in concepts, not in the frameworks.

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

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

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Escape double quotes for JSON in Python

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}

How can I get my Android device country code without using GPS?

For some devices, if the default language is set different (an Indian can set English (US)) then

context.getResources().getConfiguration().locale.getDisplayCountry();

will give the wrong value. So this method is not reliable.

Also, getNetworkCountryIso() method of TelephonyManager will not work on devices which don't have SIM card (Wi-Fi tablets).

If a device doesn't have a SIM card then we can use the time zone to get the country. For countries like India, this method will work.

Sample code used to check the country is India or not.

Use the below values in your constants file

(Constants.INDIA_TIME_ZONE_ID: "asia/calcutta", Constants.NETWORK_INDIA_CODE :"in")

And in your activity, add the following code:

private void checkCountry() {

    TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (telMgr == null)
        return;

    int simState = telMgr.getSimState();

    switch (simState) {

        // If a SIM card is not available then the
        // country is found using the timezone ID
        case TelephonyManager.SIM_STATE_ABSENT:
            TimeZone tz = TimeZone.getDefault();
            String timeZoneId = tz.getID();
            if (timeZoneId.equalsIgnoreCase(Constants.INDIA_TIME_ZONE_ID)) {
               // Do something
            }
            else {
               // Do something
            }
            break;

        // If a SIM card is available then the telephony
        // manager network country information is used
        case TelephonyManager.SIM_STATE_READY:

            if (telMgr != null) {
                String countryCodeValue = tm.getNetworkCountryIso();

                // Check if the network country code is "in"
                if (countryCodeValue.equalsIgnoreCase(Constants.NETWORK_INDIA_CODE)) {
                   // Do something
                }
                else {
                   // Do something
                }
            }
            break;
    }
}

Is there a way to specify which pytest tests to run from a file?

Method 1: Randomly selected tests. Long and ugly.

python -m pytest test/stress/test_performance.py::TestPerformance::test_continuous_trigger test/integration/test_config.py::TestConfig::test_valid_config

Method 2: Use Keyword Expressions.

Note: I am searching by testcase names. Same is applicable to TestClass names.

Case 1: The below will run whichever is found. Since we have used 'OR' .

python -m pytest -k 'test_password_valid or test_no_configuration'

Lets say the two above are actually correct, 2 tests will be run.

Case 2: Now an incorrect name and another correct name.

python -m pytest -k 'test_password_validzzzzzz or test_no_configuration' 

Only one is found and run.

Case 3: If you want all tests to run or no one, then use AND

python -m pytest -k 'test_password_valid and test_no_configuration'

Both will be run if correct or none.

Case 4: Run test only in one folder:

python -m pytest test/project1/integration -k 'test_password_valid or test_no_configuration'

Case 5: Run test from only one file.

python -m pytest test/integration/test_authentication.py -k 'test_password_expiry or test_incorrect_password'

Case 6: Run all tests except the match.

python -m pytest test/integration/test_authentication.py -k 'not  test_incorrect_password'

What is the largest possible heap size with a 64-bit JVM?

The answer clearly depends on the JVM implementation. Azul claim that their JVM

can scale ... to more than a 1/2 Terabyte of memory

By "can scale" they appear to mean "runs wells", as opposed to "runs at all".

Using ffmpeg to change framerate

You may consider using fps filter. It won't change the video playback speed:

ffmpeg -i <input> -filter:v fps=fps=30 <output>

Worked nice for reducing fps from 59.6 to 30.

How to add a second css class with a conditional value in razor MVC 4

You can use String.Format function to add second class based on condition:

<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">

Navigation drawer: How do I set the selected item at startup?

Easiest way is to select it from xml as follows,

<menu>
   <group android:checkableBehavior="single">
         <item
              android:checked="true"
              android:id="@+id/nav_home"
              android:icon="@drawable/nav_home"
              android:title="@string/main_screen_title_home" />

Note the line android:checked="true"

Better way to cast object to int

int i = myObject.myField.CastTo<int>();

Find the closest ancestor element that has a specific class

This does the trick:

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

The while loop waits until el has the desired class, and it sets el to el's parent every iteration so in the end, you have the ancestor with that class or null.

Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement is used here because parentNode would involve more work to make sure that the node is an element.

How to create Select List for Country and States/province in MVC

Thank You All! I am able to to load Select List as per MVC now My Working Code is below:

HTML+MVC Code in View:-

    <tr>
        <th>@Html.Label("Country")</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
    </tr>
    <tr>
        <th>@Html.LabelFor(x=>x.Province)</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
    </tr>

Created a Controller under "UTIL" folder: Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedAvail.Applications.MedProvision.Web.Util
{
    public class SelectListItemHelper
    {
        public static IEnumerable<SelectListItem> GetProvincesList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "California", Value = "B"},
                new SelectListItem{Text = "Alaska", Value = "B"},
                new SelectListItem{Text = "Illinois", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


        public static IEnumerable<SelectListItem> GetCountryList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "United States", Value = "B"},
                new SelectListItem{Text = "Canada", Value = "B"},
                new SelectListItem{Text = "United Kingdom", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


    }
}

And its working COOL now :-)

Thank you!!

How to install PostgreSQL's pg gem on Ubuntu?

This solved the problem for me on Ubuntu 12.04 after every suggestion here had failed.

rvmsudo gem install pg -v '0.12.2' -- --with-pg-lib=/usr/include/postgresql

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Sometimes in order to write less code it is used to have SQL server set fields like date, time and ID on insert by setting the default value for fields to GETDATE() or NEWID().

In such cases Auto Generated Value property of those fields in entity classes should be set to true.

This way you do not need to set values in code (preventing energy consumption!!!) and never see that exception.

Proper MIME type for OTF fonts

As a specific instance of one of the two hard things in computing, it’s interesting to see how the answers to this question have changed since this question was originally posted. Thankfully, the powers that be have brought order to the chaos:


In February this year (2017), the W3C published the Standards Track RFC 8081: The "font" Top-Level Media Type which greatly simplifies the appropriate media types for font files:

This memo serves to register and document the "font" top-level media type, under which subtypes for representation formats for fonts may be registered. This document also serves as a registration application for a set of intended subtypes, which are representative of some existing subtypes already in use, and currently registered under the "application" tree by their separate registrations.

It’s quite a readable document and it describes the historical context (lack of “a registration of formats for font”) which gave rise to the confusing mix of media types and sub-types. With the (relatively) recent rise in popularity of downloadable web fonts, the W3C recognised the need for an “intuitive top-level font type”. What they came up with is … font.

Accordingly, the IANA have since updated their official list of Media types with the font media type and all its sub-types that they currently recognise:

collection  font/collection
otf     font/otf
sfnt    font/sfnt
ttf     font/ttf
woff    font/woff
woff2   font/woff2

Here’s hoping this is the last answer this question needs.

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

From http://docs.python.org/library/csv.html#csv.writer:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with statement to close the file when you're done writing to it.
Tested example below:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

Attach (open) mdf file database with SQL Server Management Studio

You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.

The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.

DataTable, How to conditionally delete rows

Extension method based on Linq

public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
    foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
        row.Delete();
}

Then use:

DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");

How to detect DataGridView CheckBox event change?

It's all about editing the cell, the problem that is the cell didn't edited actually, so you need to save The changes of the cell or the row to get the event when you click the check box so you can use this function:

datagridview.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)

with this you can use it even with a different event.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Best C/C++ Network Library

Aggregated List of Libraries

How to decompile an APK or DEX file on Android platform?

You can also use the apktool: http://ibotpeaches.github.io/Apktool/ which will also give you the xml res files. Along with that you can also use the dex2jar system which will output the dex file in the apk to a jar file that can be opened with JD-GUI and exported to standard java files.

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

java: Class.isInstance vs Class.isAssignableFrom

I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance but just the Class object to use isAssignableFrom.

Creating a Shopping Cart using only HTML/JavaScript

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm

You can try following approach:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.

Documentation

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful.

How do I configure the proxy settings so that Eclipse can download new plugins?

Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.

After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.

Best of luck on finding a solution!

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

How to make HTML element resizable using pure Javascript?

I have created a function that recieve an id of an html element and adds a border to it's right side the function is general and just recieves an id so you can copy it as it is and it will work

_x000D_
_x000D_
var myoffset;_x000D_
function resizeE(elem){_x000D_
    var borderDiv = document.createElement("div");_x000D_
    borderDiv.className = "border";_x000D_
    borderDiv.addEventListener("mousedown",myresize = function myrsize(e) {_x000D_
     myoffset = e.clientX - (document.getElementById(elem).offsetLeft + parseInt(window.getComputedStyle(document.getElementById(elem)).getPropertyValue("width")));_x000D_
     window.addEventListener("mouseup",mouseUp);_x000D_
     document.addEventListener("mousemove",mouseMove = function mousMove(e) {_x000D_
      document.getElementById(elem).style.width = `${e.clientX -  myoffset - document.getElementById(elem).offsetLeft}px`;_x000D_
  });_x000D_
 });_x000D_
    document.getElementById(elem).appendChild(borderDiv);_x000D_
}_x000D_
_x000D_
function mouseUp() {_x000D_
    document.removeEventListener("mousemove", mouseMove);_x000D_
    window.removeEventListener("mouseup",mouseUp);_x000D_
}_x000D_
_x000D_
function load() _x000D_
{_x000D_
 resizeE("resizeableDiv");_x000D_
 resizeE("anotherresizeableDiv");_x000D_
  resizeE("anotherresizeableDiv1");_x000D_
}
_x000D_
.border {_x000D_
_x000D_
  position: absolute;_x000D_
  cursor: e-resize;_x000D_
  width: 9px;_x000D_
  right: -5px;_x000D_
  top: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#resizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #84f4c6;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #9394f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #43f4f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 .border{_x000D_
  background-color: black;_x000D_
}_x000D_
#anotherresizeableDiv .border{_x000D_
  width: 30px;_x000D_
  right: -200px;_x000D_
  background-color: green;_x000D_
}
_x000D_
<body onload="load()">_x000D_
_x000D_
  <div id="resizeableDiv">change my size with the east border</div>_x000D_
  <div id="anotherresizeableDiv1">with visible border</div>_x000D_
</body>_x000D_
  <div id="anotherresizeableDiv">with editted outside border</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

resizeE("resizeableDiv"); //this calls a function that does the magic to the id inserted

How to extract text from a PDF?

An efficient command line tool, open source, free of any fee, available on both linux & windows : simply named pdftotext. This tool is a part of the xpdf library.

http://en.wikipedia.org/wiki/Pdftotext

Sending and receiving data over a network using TcpClient

First of all, TCP does not guarantee that everything that you send will be received with the same read at the other end. It only guarantees that all bytes that you send will arrive and in the correct order.

Therefore, you will need to keep building up a buffer when reading from the stream. You will also have to know how large each message is.

The simplest ever is to use a non-typeable ASCII character to mark the end of the packet and look for it in the received data.

When to use 'raise NotImplementedError'?

Consider if instead it was:

class RectangularRoom(object):
    def __init__(self, width, height):
        pass

    def cleanTileAtPosition(self, pos):
        pass

    def isTileCleaned(self, m, n):
        pass

and you subclass and forget to tell it how to isTileCleaned() or, perhaps more likely, typo it as isTileCLeaned(). Then in your code, you'll get a None when you call it.

  • Will you get the overridden function you wanted? Definitely not.
  • Is None valid output? Who knows.
  • Is that intended behavior? Almost certainly not.
  • Will you get an error? It depends.

raise NotImplmentedError forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.

Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).

Displaying all table names in php from MySQL database

The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.

It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.

What is a smart pointer and when should I use one?

http://en.wikipedia.org/wiki/Smart_pointer

In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects that point to them for the purpose of memory management. The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers makes it very likely that some memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) is destroyed, for example because it goes out of scope, the pointed object is destroyed too.

How to align LinearLayout at the center of its parent?

I experienced this while working with nested RelativeLayouts. My solution ended up being simple, but it's a little gotcha that's worth being aware of.

My layout was defined with...

android:layout_height="fill_parent"
android:layout_below="@id/someLayout
android:gravity="center"

...however, I didn't think that the layout below this one was placed on top of it. Everything inside this layout was shifted towards the bottom instead of centered. Adding...

android:layout_above="@id/bottomLayout"

...fixed my issue.