Programs & Examples On #Spring.net

Spring.NET is an open source application framework for developing .NET enterprise applications.

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

How to convert string representation of list to a list?

The json module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data) function can be used to convert it to a list.

>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']

Similarly

>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]

Converting integer to string in Python

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

WebService Client Generation Error with JDK8

I have just tried that if you use SoapUI (5.4.x) and use Apache CXF tool to generate java code, put javax.xml.accessExternalSchema = all in YOUR_JDK/jre/lib/jaxp.properties file also works.

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

C# How do I click a button by hitting Enter whilst textbox has focus?

In Visual Studio 2017, using c#, just add the AcceptButton attribute to your button, in my example "btnLogIn":

this.btnLogIn = new System.Windows.Forms.Button();
//....other settings
this.AcceptButton = this.btnLogIn;

Converting HTML files to PDF

Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically?

This is how ActivePDF works, which is good means that you know what you'll get, and it actually has reasonable styling support.

It is also one of the few packages I found (when looking a few years back) that actually supports the various page-break CSS commands.


Unfortunately, the ActivePDF software is very frustrating - since it has to launch the IE browser in the background for conversions it can be quite slow, and it is not particularly stable either.

There is a new version currently in Beta which is supposed to be much better, but I've not actually had a chance to try it out, so don't know how much of an improvement it is.

How to sort an array of associative arrays by value of a given key in PHP?

While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:

array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);

Get the previous month's first and last day dates in c#

DateTime now = DateTime.Now;
int prevMonth = now.AddMonths(-1).Month;
int year = now.AddMonths(-1).Year;
int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
  lastDayPrevMonth.ToShortDateString());

Node.js Generate html

Although @yanick-rochon answer is correct, the simplest way to achieve your goal (if it's to serve a dynamically generated html) is:

var http = require('http');
http.createServer(function (req, res) {
  res.write('<html><head></head><body>');
  res.write('<p>Write your HTML content here</p>');
  res.end('</body></html>');
}).listen(1337);

This way when you browse at http://localhost:1337 you'll get your html page.

Get list of passed arguments in Windows batch script (.bat)

The way to retrieve all the args to a script is here:

@ECHO off
ECHO The %~nx0 script args are...
for %%I IN (%*) DO ECHO %%I
pause

How to make a progress bar

You could recreate the progress bar using CSS3 animations to give it a better look.

JSFiddle Demo

HTML

<div class="outer_div">
    <div class="inner_div">
        <div id="percent_count">

    </div>
</div>

CSS/CSS3

.outer_div {
    width: 250px;
    height: 25px;
    background-color: #CCC;
}

.inner_div {
    width: 5px;
    height: 21px;
    position: relative; top: 2px; left: 5px;
    background-color: #81DB92;
    box-shadow: inset 0px 0px 20px #6CC47D;
    -webkit-animation-name: progressBar;
    -webkit-animation-duration: 3s;
    -webkit-animation-fill-mode: forwards;
}

#percent_count {
    font: normal 1em calibri;
    position: relative;
    left: 10px;
}

@-webkit-keyframes progressBar {
    from {
        width: 5px;
    }
    to {
        width: 200px;
    }
}

How to resolve symbolic links in a shell script

Common shell scripts often have to find their "home" directory even if they are invoked as a symlink. The script thus have to find their "real" position from just $0.

cat `mvn`

on my system prints a script containing the following, which should be a good hint at what you need.

if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  M2_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`

Check if an element is present in a Bash array

You could do:

if [[ " ${arr[*]} " == *" d "* ]]; then
    echo "arr contains d"
fi

This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.

The safest way is to loop over the array until you find the element:

array_contains () {
    local seeking=$1; shift
    local in=1
    for element; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no    # no
array_contains "d e" "${arr[@]}" && echo yes || echo no    # yes

Here's a "cleaner" version where you just pass the array name, not all its elements

array_contains2 () { 
    local array="$1[@]"
    local seeking=$2
    local in=1
    for element in "${!array}"; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

array_contains2 arr "a b"  && echo yes || echo no    # no
array_contains2 arr "d e"  && echo yes || echo no    # yes

For associative arrays, there's a very tidy way to test if the array contains a given key: The -v operator

$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no

See 6.4 Bash Conditional Expressions in the manual.

How to use hex color values

UIColor:

extension UIColor {

    convenience init(hex: Int) {
        let components = (
            R: CGFloat((hex >> 16) & 0xff) / 255,
            G: CGFloat((hex >> 08) & 0xff) / 255,
            B: CGFloat((hex >> 00) & 0xff) / 255
        )
        self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
    }

}

CGColor:

extension CGColor {

    class func colorWithHex(hex: Int) -> CGColorRef {

        return UIColor(hex: hex).CGColor

    }

}

Usage

let purple = UIColor(hex: 0xAB47BC)

Convert to date format dd/mm/yyyy

$source    =    'your varible name';
$date    =     new DateTime($source);
$_REQUEST["date"]    =     $date->format('d-m-Y');

echo $_REQUEST["date"];

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Convert a string to integer with decimal in Python

>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24

You don't specify if you want rounding or not...

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/ld.so.conf, without include...

run ldconfig -p to see whether your library is well included in the cache.

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I tried all above solutions but no luck. Adding line <add assembly="*" /> to web.config fixed it for me. (You can also add to machine.config or root web.config file of the appropriate .NET framework version, I didn't try it) Thanks to MS Support for solution.

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

Changing the current directory of the script process is trivial. I think the question is actually how to change the current directory of the command window from which a python script is invoked, which is very difficult. A Bat script in Windows or a Bash script in a Bash shell can do this with an ordinary cd command because the shell itself is the interpreter. In both Windows and Linux Python is a program and no program can directly change its parent's environment. However the combination of a simple shell script with a Python script doing most of the hard stuff can achieve the desired result. For example, to make an extended cd command with traversal history for backward/forward/select revisit, I wrote a relatively complex Python script invoked by a simple bat script. The traversal list is stored in a file, with the target directory on the first line. When the python script returns, the bat script reads the first line of the file and makes it the argument to cd. The complete bat script (minus comments for brevity) is:

if _%1 == _. goto cdDone
if _%1 == _? goto help
if /i _%1 NEQ _-H goto doCd
:help
echo d.bat and dSup.py 2016.03.05. Extended chdir.
echo -C = clear traversal list.
echo -B or nothing = backward (to previous dir).
echo -F or - = forward (to next dir).
echo -R = remove current from list and return to previous.
echo -S = select from list.
echo -H, -h, ? = help.
echo . = make window title current directory.
echo Anything else = target directory.
goto done

:doCd
%~dp0dSup.py %1
for /F %%d in ( %~dp0dSupList ) do (
    cd %%d
    if errorlevel 1 ( %~dp0dSup.py -R )
    goto cdDone
)
:cdDone
title %CD%
:done

The python script, dSup.py is:

import sys, os, msvcrt

def indexNoCase ( slist, s ) :
    for idx in range( len( slist )) :
        if slist[idx].upper() == s.upper() :
            return idx
    raise ValueError

# .........main process ...................
if len( sys.argv ) < 2 :
    cmd = 1 # No argument defaults to -B, the most common operation
elif sys.argv[1][0] == '-':
    if len(sys.argv[1]) == 1 :
        cmd = 2 # '-' alone defaults to -F, second most common operation.
    else :
        cmd = 'CBFRS'.find( sys.argv[1][1:2].upper())
else :
    cmd = -1
    dir = os.path.abspath( sys.argv[1] ) + '\n'

# cmd is -1 = path, 0 = C, 1 = B, 2 = F, 3 = R, 4 = S

fo = open( os.path.dirname( sys.argv[0] ) + '\\dSupList', mode = 'a+t' )
fo.seek( 0 )
dlist = fo.readlines( -1 )
if len( dlist ) == 0 :
    dlist.append( os.getcwd() + '\n' ) # Prime new directory list with current.

if cmd == 1 : # B: move backward, i.e. to previous
    target = dlist.pop(0)
    dlist.append( target )
elif cmd == 2 : # F: move forward, i.e. to next
    target = dlist.pop( len( dlist ) - 1 )
    dlist.insert( 0, target )
elif cmd == 3 : # R: remove current from list. This forces cd to previous, a
                # desireable side-effect
    dlist.pop( 0 )
elif cmd == 4 : # S: select from list
# The current directory (dlist[0]) is included essentially as ESC.
    for idx in range( len( dlist )) :
        print( '(' + str( idx ) + ')', dlist[ idx ][:-1])
    while True :
        inp = msvcrt.getche()
        if inp.isdigit() :
            inp = int( inp )
            if inp < len( dlist ) :
                print( '' ) # Print the newline we didn't get from getche.
                break
        print( ' is out of range' )
# Select 0 means the current directory and the list is not changed. Otherwise
# the selected directory is moved to the top of the list. This can be done by
# either rotating the whole list until the selection is at the head or pop it
# and insert it to 0. It isn't obvious which would be better for the user but
# since pop-insert is simpler, it is used.
    if inp > 0 :
        dlist.insert( 0, dlist.pop( inp ))

elif cmd == -1 : # -1: dir is the requested new directory.
# If it is already in the list then remove it before inserting it at the head.
# This takes care of both the common case of it having been recently visited
# and the less common case of user mistakenly requesting current, in which
# case it is already at the head. Deleting and putting it back is a trivial
# inefficiency.
    try:
        dlist.pop( indexNoCase( dlist, dir ))
    except ValueError :
        pass
    dlist = dlist[:9] # Control list length by removing older dirs (should be
                      # no more than one).
    dlist.insert( 0, dir ) 

fo.truncate( 0 )
if cmd != 0 : # C: clear the list
    fo.writelines( dlist )

fo.close()
exit(0)

Update R using RStudio

I would recommend using the Windows package installr to accomplish this. Not only will the package update your R version, but it will also copy and update all of your packages. There is a blog on the subject here. Simply run the following commands in R Studio and follow the prompts:

# installing/loading the package:
if(!require(installr)) {
install.packages("installr"); require(installr)} #load / install+load installr

# using the package:
updateR() # this will start the updating process of your R installation.  It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.

Visual Studio 2017 - Git failed with a fatal error

enter image description here

When i do pull/fetch/push i got the above error in my output window, i followed the below soloution , it resovled my issue.

If you are using visual studio 2017 enterprise edition, replace the userId with your user id in the below command and execute this command in windows run window(windows key + R).

runas /netonly /user:UserId "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe"

enter image description here

This will prompt for password, enter your password. A new visual studio instance will open and will start working properly...

SQL: Two select statements in one query

Using union will help in this case.

You can also use join on a condition that always returns true and is not related to data in these tables.See below

select tmd .name,tbc.goals from tblMadrid tmd join tblBarcelona tbc on 1=1;

Unix - copy contents of one directory to another

Quite simple, with a * wildcard.

cp -r Folder1/* Folder2/

But according to your example recursion is not needed so the following will suffice:

cp Folder1/* Folder2/

EDIT:

Or skip the mkdir Folder2 part and just run:

cp -r Folder1 Folder2

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Rotation Test</title>
  <link type="text/css" href="css/style.css" rel="stylesheet"></style>
  <script src="js/jquery-1.5.min.js" type="text/javascript"></script>
  <script type="text/javascript">
        window.addEventListener("resize", function() {
            // Get screen size (inner/outerWidth, inner/outerHeight)
            var height = $(window).height();
            var width = $(window).width();

            if(width>height) {
              // Landscape
              $("#mode").text("LANDSCAPE");
            } else {
              // Portrait
              $("#mode").text("PORTRAIT");
            }
        }, false);

  </script>
 </head>
 <body onorientationchange="updateOrientation();">
   <div id="mode">LANDSCAPE</div>
 </body>
</html>

Get time difference between two dates in seconds

Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)

Remove Android App Title Bar

If you use AppCompat v7, v21

getSupportActionBar().setDisplayShowTitleEnabled(false);

How do I use raw_input in Python 3

Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:

# Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)

Now you can use real_raw_input. It's quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it's not important.

In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It's better stay on the safe side.

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

How to make the checkbox unchecked by default always

Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.

MongoDB: How to update multiple documents with a single command?

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )

PHP Get Site URL Protocol - http vs https

Some changes:

function siteURL() {
  $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || 
    $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  $domainName = $_SERVER['HTTP_HOST'];
  return $protocol.$domainName;
}

How to enable scrolling of content inside a modal?

I'm having this issue on Mobile Safari on my iPhone6

Bootstrap adds the class .modal-open to the body when a modal is opened.

I've tried to make minimal overrides to Bootstrap 3.2.0, and came up with the following:

.modal-open {
    position: fixed;
}

.modal {
    overflow-y: auto;
}

For comparison, I've included the associated Bootstrap styles below.

Selected extract from bootstrap/less/modals.less (don't include this in your fix):

// Kill the scroll on the body
.modal-open {
  overflow: hidden;
}

// Container that the modal scrolls within
.modal {
  display: none;
  overflow: hidden;
  position: fixed;
  -webkit-overflow-scrolling: touch;
}

.modal-open .modal {
  overflow-x: hidden;
  overflow-y: auto;
}

Mobile Safari version used: User-Agent Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B411 Safari/600.1.4

TERM environment variable not set

SOLVED: On Debian 10 by adding "EXPORT TERM=xterm" on the Script executed by CRONTAB (root) but executed as www-data.

$ crontab -e

*/15 * * * * /bin/su - www-data -s /bin/bash -c '/usr/local/bin/todos.sh'

FILE=/usr/local/bin/todos.sh

#!/bin/bash -p
export TERM=xterm && cd /var/www/dokuwiki/data/pages && clear && grep -r -h '|(TO-DO)' > /var/www/todos.txt && chmod 664 /var/www/todos.txt && chown www-data:www-data /var/www/todos.txt

WCF, Service attribute value in the ServiceHost directive could not be found

I had the same problem, found this thread, tried all but nogo.

Then I spend another 4 hours wasted time.

Then I found that the compilation settings had changed from 64bits to x86. When I changed it back to 64bits it worked. Don't know exactly why but could be that the IIS application pool was not set to allow 32 bit applications.

File to byte[] in Java

Can be done as simple as this (Kotlin version)

val byteArray = File(path).inputStream().readBytes()

EDIT:

I've read docs of readBytes method. It says:

Reads this stream completely into a byte array. Note: It is the caller's responsibility to close this stream.

So to be able to close the stream, while keeping everything clean, use the following code:

val byteArray = File(path).inputStream().use { it.readBytes() }

Thanks to @user2768856 for pointing this out.

What's an easy way to read random line from a file in Unix command line?

Another way using 'awk'

awk NR==$((${RANDOM} % `wc -l < file.name` + 1)) file.name

Subversion ignoring "--password" and "--username" options

The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.

IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?

If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password.

How to support UTF-8 encoding in Eclipse

Open Eclipse and do the following steps:

  1. Window -> Preferences -> Expand General and click Workspace, text file encoding (near bottom) has an encoding chooser.
  2. Select "Other" radio button -> Select UTF-8 from the drop down
  3. Click Apply and OK button OR click simply OK button

enter image description here

How do I implement JQuery.noConflict() ?

It allows for you to give the jQuery variable a different name, and still use it:

<script type="text/javascript">
  $jq = $.noConflict();
  // Code that uses other library's $ can follow here.
  //use $jq for all calls to jQuery:
  $jq.ajax(...)
  $jq('selector')
</script>

Changing the child element's CSS when the parent is hovered

No need to use the JavaScript or jquery, CSS is enough:

.child{ display:none; }
.parent:hover .child{ display:block; }

SEE DEMO

Response.Redirect with POST instead of Get?

Thought it might interesting to share that heroku does this with it's SSO to Add-on providers

An example of how it works can be seen in the source to the "kensa" tool:

https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb

And can be seen in practice if you turn of javascript. Example page source:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Heroku Add-ons SSO</title>
  </head>

  <body>
    <form method="POST" action="https://XXXXXXXX/sso/login">

        <input type="hidden" name="email" value="XXXXXXXX" />

        <input type="hidden" name="app" value="XXXXXXXXXX" />

        <input type="hidden" name="id" value="XXXXXXXX" />

        <input type="hidden" name="timestamp" value="1382728968" />

        <input type="hidden" name="token" value="XXXXXXX" />

        <input type="hidden" name="nav-data" value="XXXXXXXXX" />

    </form>

    <script type="text/javascript">
      document.forms[0].submit();
    </script>
  </body>
</html>

How can I convert String to Int?

You can do like below without TryParse or inbuilt functions:

static int convertToInt(string a)
{
    int x = 0;
    for (int i = 0; i < a.Length; i++)
    {
        int temp = a[i] - '0';
        if (temp != 0)
        {
            x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
        }
    }
    return x;
}

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

HTML/Javascript: how to access JSON data loaded in a script tag with src set

It would appear this is not possible, or at least not supported.

From the HTML5 specification:

When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.

How to throw std::exceptions with variable messages?

Here is my solution:

#include <stdexcept>
#include <sstream>

class Formatter
{
public:
    Formatter() {}
    ~Formatter() {}

    template <typename Type>
    Formatter & operator << (const Type & value)
    {
        stream_ << value;
        return *this;
    }

    std::string str() const         { return stream_.str(); }
    operator std::string () const   { return stream_.str(); }

    enum ConvertToString 
    {
        to_str
    };
    std::string operator >> (ConvertToString) { return stream_.str(); }

private:
    std::stringstream stream_;

    Formatter(const Formatter &);
    Formatter & operator = (Formatter &);
};

Example:

throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Triggering change detection manually in Angular

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.

Instant run in Android Studio 2.0 (how to turn off)

I tried all above but nothing helps, at last i just figured out that under setting >> apps, device still has an entry for uninstalled application as disabled, i just uninstalled from there and it starts working.

:) might be useful for someone

Eclipse C++ : "Program "g++" not found in PATH"

In my case, I didnt mark for instalation the mingw32-gcc-g++ package in the installation manager, that's why eclipse didn't know it.

Needed to go to the instalation manager, mark it (in basic setup tab) and update catalogue

Run a task every x-minutes with Windows Task Scheduler

Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"

In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.

I thought doing an "Export" and editing the XML from: PT30M to PT2M

and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that

My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)

How does Google calculate my location on a desktop?

It is possible get your approximate locate based on your IP address (wireless or fixed).

See for example hostip.info or maxmind which basically provide a mapping from IP address to geographical coordinates. The probably use many kinds of heuristics and datasources. This kind of system has probably enough accuracy to put you in right major city, in most cases.

Google probably uses somewhat similar approach in addition to WiFi tricks.

How to check if a socket is connected/disconnected in C#?

The accepted answer doesn't seem to work if you unplug the network cable. Or the server crashes. Or your router crashes. Or if you forget to pay your internet bill. Set the TCP keep-alive options for better reliability.

public static class SocketExtensions
{
    public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
    {
        //KeepAliveTime: default value is 2hr
        //KeepAliveInterval: default value is 1s and Detect 5 times

        //the native structure
        //struct tcp_keepalive {
        //ULONG onoff;
        //ULONG keepalivetime;
        //ULONG keepaliveinterval;
        //};

        int size = Marshal.SizeOf(new uint());
        byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12
        bool OnOff = true;

        BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size);
        BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2);

        instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
    }
}



// ...
Socket sock;
sock.SetSocketKeepAliveValues(2000, 1000);

The time value sets the timeout since data was last sent. Then it attempts to send and receive a keep-alive packet. If it fails it retries 10 times (number hardcoded since Vista AFAIK) in the interval specified before deciding the connection is dead.

So the above values would result in 2+10*1 = 12 second detection. After that any read / wrtie / poll operations should fail on the socket.

VB.NET Switch Statement GoTo Case

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here.
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select

Is there a reason for the goto? If it doesn't meet the if criterion, it will simply not perform the function and go to the next case.

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

The below process will solve the problem,

1: Open KeyChain access, and Delete "Apple world wide Developer relations certification authority" (Which expires on 14th Feb 2016) from both "Login" and "System" sections. If you can't find it, use “Show Expired Certificates” in the 'View' menu.

enter image description here

2: Now download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and double click the certificate to add it to Keychain access > certificates (which expires on 8th Feb 2023). Now the valid status of the certificates should turn green like below.

enter image description here

Once check the status.

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

What is Android keystore file, and what is it used for?

You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html

Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.

HashSet vs. List performance

The breakeven will depend on the cost of computing the hash. Hash computations can be trivial, or not... :-) There is always the System.Collections.Specialized.HybridDictionary class to help you not have to worry about the breakeven point.

Defining a HTML template to append using JQuery

In order to solve this problem, I recognize two solutions:

  • The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with .clone().

    $.get('url/to/template', function(data) {
        temp = data
        $('.search').keyup(function() {
            $('.list-items').html(null);
    
            $.each(items, function(index) {
                 $(this).append(temp.clone())
            });
    
        });
    });
    

    Take into account that the event should be added once the ajax has completed to be sure the data is available!

  • The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery:

    temp = $('.list_group_item').hide()
    

    You can after add a new instance of the template with

    $('.search').keyup(function() {
        $('.list-items').html(null);
    
        $.each(items, function(index) {
            $(this).append(temp.clone())
        });
    });
    
  • Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) .detach() instead of hide.

    temp = $('.list_group_item').detach()
    

    .detach() removes elements from the DOM while keeping the data and events alive (.remove() does not!).

Explaining Apache ZooKeeper

I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).

Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.

  • These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".

  • So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.

  • So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.

  • Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.

  • Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.

I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Undo scaffolding in Rails

So, Process you should follow to undo scaffolding in rails 4. Run Command as below:

  1. rails d scaffold FooBar
  2. rake db:rollback if you_had_run_rake db:migrate after creating above scaffold?

That's it!

Cheers!

How to compare values which may both be null in T-SQL

Use INTERSECT operator.

It's NULL-sensitive and efficient if you have a composite index on all your fields:

IF      EXISTS
        (
        SELECT  MY_FIELD1, MY_FIELD2, MY_FIELD3, MY_FIELD4, MY_FIELD5, MY_FIELD6
        FROM    MY_TABLE
        INTERSECT
        SELECT  @IN_MY_FIELD1, @IN_MY_FIELD2, @IN_MY_FIELD3, @IN_MY_FIELD4, @IN_MY_FIELD5, @IN_MY_FIELD6
        )
BEGIN
        goto on_duplicate
END

Note that if you create a UNIQUE index on your fields, your life will be much simpler.

jQuery add required to input fields

Using .attr method

.attr(attribute,value); // syntax

.attr("required", true);
// required="required"

.attr("required", false);
// 

Using .prop

.prop(property,value) // syntax

.prop("required", true);
// required=""

.prop("required", false);
//

Read more from here

https://stackoverflow.com/a/5876747/5413283

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

How to solve WAMP and Skype conflict on Windows 7?

Options>Advanced>connections

Uncheck the option :

Use port 80 and 443 as alternative....

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

pip install python-dateutil
>>> a = "2019-06-27T02:14:49.443814497Z"
>>> dateutil.parser.parse(a)
datetime.datetime(2019, 6, 27, 2, 14, 49, 443814, tzinfo=tzutc())

How do I reformat HTML code using Sublime Text 2?

Altough the question is for HTML, I would also additionally like to give info about how to auto-format your Javascript code for Sublime Text 2;

You can select all your code(ctrl + A) and use the in-app functionality, reindent(Edit -> Line -> Reindent) or you can use JsFormat formatting plugin for Sublime Text 2 if you would like to have more customizable settings on how to format your code to addition to the Sublime Text's default tab/indent settings.

https://github.com/jdc0589/JsFormat

You can easily install JsFormat with using Package Control (Preferences -> Package Control) Open package control then type install, hit enter. Then type js format and hit enter, you're done. (The package controller will show the status of the installation with success and errors on the bottom left bar of Sublime)

Add the following line to your key bindings (Preferences -> Key Bindings User)

{ "keys": ["ctrl+alt+2"], "command": "js_format"}

I'm using ctrl + alt + 2, you can change this shortcut key whatever you want to. So far, JsFormat is a good plugin, worth to try it!

Hope this will help someone.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to display raw html code in PRE or something like it but without escaping it

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

In other words, use htmlspecialchars() in PHP

How to hide column of DataGridView when using custom DataSource?

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

Execute a shell script in current shell with sudo permission

Basically sudo expects, an executable (command) to follow & you are providing with a .

Hence the error.

Try this way $ sudo setup.sh


How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

pg_config executable not found

I got fixed this by running the following command.

env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2

Reference : https://stackoverflow.com/a/39800677/4270698

Let JSON object accept bytes or let urlopen output strings

Python’s wonderful standard library to the rescue…

import codecs

reader = codecs.getreader("utf-8")
obj = json.load(reader(response))

Works with both py2 and py3.

Docs: Python 2, Python3

how to add new <li> to <ul> onclick with javascript

You have not appended your li as a child to your ul element

Try this

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
}

If you need to set the id , you can do so by

li.setAttribute("id", "element4");

Which turns the function into

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); // added line
  ul.appendChild(li);
  alert(li.id);
}

how to make password textbox value visible when hover an icon

a rapid response not tested on several brosers, works on gg chrome / win

-> On focus event -> show/hide password

<input type="password" name="password">

script jQuery

// show on focus
$('input[type="password"]').on('focusin', function(){

    $(this).attr('type', 'text');

});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){

    $(this).attr('type', 'password');

});

node.js shell command execution

I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !

https://github.com/aponxi/npm-execxi

ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !

Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!

I thought it was worth to mention it.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

Append an object to a list in R in amortized constant time, O(1)?

There is also list.append from the rlist (link to the documentation)

require(rlist)
LL <- list(a="Tom", b="Dick")
list.append(LL,d="Pam",f=c("Joe","Ann"))

It's very simple and efficient.

How to Remove Line Break in String

I hope this'll do . or else, may ask me directly

_x000D_
_x000D_
  
_x000D_
Sub RemoveBlankLines()
    Application.ScreenUpdating = False
    Dim rngCel As Range
    Dim strOldVal As String
    Dim strNewVal As String

    For Each rngCel In Selection
        If rngCel.HasFormula = False Then
            strOldVal = rngCel.Value
            strNewVal = strOldVal
            Debug.Print rngCel.Address

            Do
            If Left(strNewVal, 1) = vbLf Then strNewVal = Right(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            If Right(strNewVal, 1) = vbLf Then strNewVal = Left(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            strNewVal = Replace(strNewVal, vbLf & vbLf, "^")
            strNewVal = Replace(strNewVal, Replace(String(Len(strNewVal) - _
                        Len(Replace(strNewVal, "^", "")), "^"), "^", "^"), "^")
            strNewVal = Replace(strNewVal, "^", vbLf)

            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            If rngCel.Value <> strNewVal Then
                rngCel = strNewVal
            End If

        rngCel.Value = Application.Trim(rngCel.Value)
        End If
    Next rngCel
    Application.ScreenUpdating = True
End Sub
_x000D_
_x000D_
_x000D_

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

SQL Server 2000: How to exit a stored procedure?

This seems like a lot of code but the best way i've found to do it.

    ALTER PROCEDURE Procedure
    AS

    BEGIN TRY
        EXEC AnotherProcedure
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;

        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
        RETURN --this forces it out
    END CATCH

--Stuff here that you do not want to execute if the above failed.    

    END --end procedure

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

How to call code behind server method from a client side JavaScript function?

JS Code:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
}

string sanitizer for filename

preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)

Add/remove more valid characters depending on what is allowed for your system.

Alternatively you can try to create the file and then return an error if it's bad.

Remove unused imports in Android Studio

you can use Alt + Enter in Android Studio as Shortcut Key

How to insert double and float values to sqlite?

I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL

Read http://sqlite.org/datatype3.html to more info.

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

How to preserve request url with nginx proxy_pass

To perfectly forward without chopping the absoluteURI of the request and the Host in the header:

server {
    listen 35005;

    location / {
        rewrite            ^(.*)$   "://$http_host$uri$is_args$args";
        rewrite            ^(.*)$   "http$uri$is_args$args" break;
        proxy_set_header   Host     $host;

        proxy_pass         https://deploy.org.local:35005;
    }
}

Found here: https://opensysnotes.wordpress.com/2016/11/17/nginx-proxy_pass-with-absolute-url/

How to format font style and color in echo

Are you trying to echo out a style or an inline style? An inline style would be like

echo "<p style=\"font-color: #ff0000;\">text here</p>";

Deleting elements from std::set while iterating

If you run your program through valgrind, you'll see a bunch of read errors. In other words, yes, the iterators are being invalidated, but you're getting lucky in your example (or really unlucky, as you're not seeing the negative effects of undefined behavior). One solution to this is to create a temporary iterator, increment the temp, delete the target iterator, then set the target to the temp. For example, re-write your loop as follows:

std::set<int>::iterator it = numbers.begin();                               
std::set<int>::iterator tmp;                                                

// iterate through the set and erase all even numbers                       
for ( ; it != numbers.end(); )                                              
{                                                                           
    int n = *it;                                                            
    if (n % 2 == 0)                                                         
    {                                                                       
        tmp = it;                                                           
        ++tmp;                                                              
        numbers.erase(it);                                                  
        it = tmp;                                                           
    }                                                                       
    else                                                                    
    {                                                                       
        ++it;                                                               
    }                                                                       
} 

ImportError: No module named xlsxwriter

I installed it by using a wheel file that can be found at this location: https://pypi.org/project/XlsxWriter/#files

I then ran pip install "XlsxWriter-1.2.8-py2.py3-none-any.whl"

Processing ./XlsxWriter-1.2.8-py2.py3-none-any.whl
Installing collected packages: XlsxWriter
Successfully installed XlsxWriter-1.2.8

Where can I find decent visio templates/diagrams for software architecture?

For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.

I use the Visio Network and Database stencils to model most other requirements.

Convert Current date to integer

The issue is that an Integer is not large enough to store a current date, you need to use a Long.

The date is stored internally as the number of milliseconds since 1/1/1970.

The maximum Integer value is 2147483648, whereas the number of milliseconds since 1970 is currently in the order of 1345618537869

Putting the maximum integer value into a date yields Monday 26th January 1970.

Edit: Code to display division by 1000 as per comment below:

    int i = (int) (new Date().getTime()/1000);
    System.out.println("Integer : " + i);
    System.out.println("Long : "+ new Date().getTime());
    System.out.println("Long date : " + new Date(new Date().getTime()));
    System.out.println("Int Date : " + new Date(((long)i)*1000L));

Integer : 1345619256
Long : 1345619256308
Long date : Wed Aug 22 16:37:36 CST 2012
Int Date : Wed Aug 22 16:37:36 CST 2012

Best way to get value from Collection by index

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = World
elem = Hello
myCollection.toArray()[0] = World

whilst:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello

Why do you want to do this? Could you not just iterate over the collection?

What is the copy-and-swap idiom?

Assignment, at its heart, is two steps: tearing down the object's old state and building its new state as a copy of some other object's state.

Basically, that's what the destructor and the copy constructor do, so the first idea would be to delegate the work to them. However, since destruction mustn't fail, while construction might, we actually want to do it the other way around: first perform the constructive part and, if that succeeded, then do the destructive part. The copy-and-swap idiom is a way to do just that: It first calls a class' copy constructor to create a temporary object, then swaps its data with the temporary's, and then lets the temporary's destructor destroy the old state.
Since swap() is supposed to never fail, the only part which might fail is the copy-construction. That is performed first, and if it fails, nothing will be changed in the targeted object.

In its refined form, copy-and-swap is implemented by having the copy performed by initializing the (non-reference) parameter of the assignment operator:

T& operator=(T tmp)
{
    this->swap(tmp);
    return *this;
}

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

Bootstrap fullscreen layout with 100% height

Here's an answer using the latest Bootstrap 4.0.0. This layout is easier using the flexbox and sizing utility classes that are all provided in Bootstrap 4. This layout is possible with very little extra CSS.

#mmenu_screen > .row {
    min-height: 100vh;
}

.flex-fill {
    flex:1 1 auto;
}

<div id="mmenu_screen" class="container-fluid main_container d-flex">
    <div class="row flex-fill">
        <div class="col-sm-6 h-100">
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--book">
                    <!-- Button for booking -->
                    Booking
                </div>
            </div>
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--information">
                    <!-- Button for information -->
                    Info
                </div>
            </div>
        </div>
        <div class="col-sm-6 mmenu_screen--direktaction flex-fill">
            <!-- Button for direktaction -->
            Action
        </div>
    </div>
</div>

Demo

The flex-fill and vh-100 classes are included in Bootstrap 4.1 (and later)

Entity framework linq query Include() multiple children entities

EF 4.1 to EF 6

There is a strongly typed .Include which allows the required depth of eager loading to be specified by providing Select expressions to the appropriate depth:

using System.Data.Entity; // NB!

var company = context.Companies
                     .Include(co => co.Employees.Select(emp => emp.Employee_Car))
                     .Include(co => co.Employees.Select(emp => emp.Employee_Country))
                     .FirstOrDefault(co => co.companyID == companyID);

The Sql generated is by no means intuitive, but seems performant enough. I've put a small example on GitHub here

EF Core

EF Core has a new extension method, .ThenInclude(), although the syntax is slightly different:

var company = context.Companies
                     .Include(co => co.Employees)
                           .ThenInclude(emp => emp.Employee_Car)
                     .Include(co => co.Employees)
                           .ThenInclude(emp => emp.Employee_Country)

With some notes

  • As per above (Employees.Employee_Car and Employees.Employee_Country), if you need to include 2 or more child properties of an intermediate child collection, you'll need to repeat the .Include navigation for the collection for each child of the collection.
  • As per the docs, I would keep the extra 'indent' in the .ThenInclude to preserve your sanity.

MySQL Like multiple values

Why not you try REGEXP. Try it like this:

SELECT * FROM table WHERE interests REGEXP 'sports|pub'

How to manually reload Google Map with JavaScript

map.setZoom(map.getZoom());

For some reasons, resize trigger did not work for me, and this one worked.

Return a "NULL" object if search result not found

There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:

  • Return by reference, and signal can-not-find by exception.

    Attr& getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            throw no_such_attribute_error;
    }

It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.

  • Return by pointer

    Attr* getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;
    }

It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.

  • Use Boost.Optional

    boost::optional<Attr&> getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            return boost::optional<Attr&>();
    }

A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.


Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.

RegEx: Grabbing values between quotation marks

Peculiarly, none of these answers produce a regex where the returned match is the text inside the quotes, which is what is asked for. MA-Madden tries but only gets the inside match as a captured group rather than the whole match. One way to actually do it would be :

(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)

Examples for this can be seen in this demo https://regex101.com/r/Hbj8aP/1

The key here is the the positive lookbehind at the start (the ?<= ) and the positive lookahead at the end (the ?=). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the ["']) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead (?=\1) to make sure it only stops when it finds the corresponding quote.

The only other complication is that because the lookahead doesn't actually consume the end quote, it will be found again by the starting lookbehind which causes text between ending and starting quotes on the same line to be matched. Putting a word boundary on the opening quote (["']\b) helps with this, though ideally I'd like to move past the lookahead but I don't think that is possible. The bit allowing escaped characters in the middle I've taken directly from Adam's answer.

Django Rest Framework -- no module named rest_framework

(I would assume that folks using containers know what they're doing, but here's my two cents)

Let's say you setup your project using cookiecutter-django and enabled the docker container support, be sure to update the pip requirements file with djangorestframework==<x.yy.z> (or whichever python dependency you're trying to install) and re-build the docker images (local and production).

How can you float: right in React Native?

using flex

 <View style={{ flexDirection: 'row',}}>
                  <Text style={{fontSize: 12, lineHeight: 30, color:'#9394B3' }}>left</Text>
                  <Text style={{ flex:1, fontSize: 16, lineHeight: 30, color:'#1D2359', textAlign:'right' }}>right</Text>
               </View>

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

Spring,Request method 'POST' not supported

For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"

I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.

C++ program converts fahrenheit to celsius

In C++, 5/9 computes the result as an integer as both the operands are integers. You need to give an hint to the compiler that you want the result as a float/double. You can do it by explictly casting one of the operands like ((double)5)/9;

EDIT Since it is tagged C++, you can do the casting bit more elegantly using the static_cast. For example: static_cast<double>(5)/9. Although in this particular case you can directly use 5.0/9 to get the desired result, the casting will be helpful when you have variables instead of constant values such as 5.

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

How to Use UTF-8 Collation in SQL Server database?

Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp, BULK_INSERT, and OPENROWSET.

Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.

Dynamically load JS inside JS

Necromancing.

I use this to load dependant scripts;
it works with IE8+ without adding any dependency on another library like jQuery !

var cScriptLoader = (function ()
{
    function cScriptLoader(files)
    {
        var _this = this;
        this.log = function (t)
        {
            console.log("ScriptLoader: " + t);
        };
        this.withNoCache = function (filename)
        {
            if (filename.indexOf("?") === -1)
                filename += "?no_cache=" + new Date().getTime();
            else
                filename += "&no_cache=" + new Date().getTime();
            return filename;
        };
        this.loadStyle = function (filename)
        {
            // HTMLLinkElement
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = _this.withNoCache(filename);
            _this.log('Loading style ' + filename);
            link.onload = function ()
            {
                _this.log('Loaded style "' + filename + '".');
            };
            link.onerror = function ()
            {
                _this.log('Error loading style "' + filename + '".');
            };
            _this.m_head.appendChild(link);
        };
        this.loadScript = function (i)
        {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = _this.withNoCache(_this.m_js_files[i]);
            var loadNextScript = function ()
            {
                if (i + 1 < _this.m_js_files.length)
                {
                    _this.loadScript(i + 1);
                }
            };
            script.onload = function ()
            {
                _this.log('Loaded script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            script.onerror = function ()
            {
                _this.log('Error loading script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            _this.log('Loading script "' + _this.m_js_files[i] + '".');
            _this.m_head.appendChild(script);
        };
        this.loadFiles = function ()
        {
            // this.log(this.m_css_files);
            // this.log(this.m_js_files);
            for (var i = 0; i < _this.m_css_files.length; ++i)
                _this.loadStyle(_this.m_css_files[i]);
            _this.loadScript(0);
        };
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        function endsWith(str, suffix)
        {
            if (str === null || suffix === null)
                return false;
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        for (var i = 0; i < files.length; ++i)
        {
            if (endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if (endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] + '".');
        }
    }
    return cScriptLoader;
})();
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If you are interested in the typescript-version used to create this:

class cScriptLoader {
    private m_js_files: string[];
    private m_css_files: string[];
    private m_head:HTMLHeadElement;
    
    private log = (t:any) =>
    {
        console.log("ScriptLoader: " + t);
    }
    
    
    constructor(files: string[]) {
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        
        
        function endsWith(str:string, suffix:string):boolean 
        {
            if(str === null || suffix === null)
                return false;
                
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        
        
        for(let i:number = 0; i < files.length; ++i) 
        {
            if(endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if(endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] +'".');
        }
        
    }
    
    
    public withNoCache = (filename:string):string =>
    {
        if(filename.indexOf("?") === -1)
            filename += "?no_cache=" + new Date().getTime();
        else
            filename += "&no_cache=" + new Date().getTime();
            
        return filename;    
    }
    

    public loadStyle = (filename:string) =>
    {
        // HTMLLinkElement
        let link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = this.withNoCache(filename);
        
        this.log('Loading style ' + filename);
        link.onload = () =>
        {
            this.log('Loaded style "' + filename + '".');
            
        };
        
        link.onerror = () =>
        {
            this.log('Error loading style "' + filename + '".');
        };
        
        this.m_head.appendChild(link);
    }
    
    
    public loadScript = (i:number) => 
    {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.withNoCache(this.m_js_files[i]);
        
        var loadNextScript = () => 
        {
            if (i + 1 < this.m_js_files.length)
            {
                this.loadScript(i + 1);
            }
        }
        
        script.onload = () =>
        {
            this.log('Loaded script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        script.onerror = () =>
        {
            this.log('Error loading script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        this.log('Loading script "' + this.m_js_files[i] + '".');
        this.m_head.appendChild(script);
    }
    
    public loadFiles = () => 
    {
        // this.log(this.m_css_files);
        // this.log(this.m_js_files);
        
        for(let i:number = 0; i < this.m_css_files.length; ++i)
            this.loadStyle(this.m_css_files[i])
        
        this.loadScript(0);
    }
    
}


var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If it's to load a dynamic list of scripts, write the scripts into an attribute, such as data-main, e.g. <script src="scriptloader.js" data-main="file1.js,file2.js,file3.js,etc." ></script>
and do a element.getAttribute("data-main").split(',')

such as

var target = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  // Note: this is for IE as IE doesn't support currentScript
  // this does not work if you have deferred loading with async
  // e.g. <script src="..." async="async" ></script>
  // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
  return scripts[scripts.length - 1];
})();

target.getAttribute("data-main").split(',')

to obtain the list.

Printing newlines with print() in R

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

Anaconda Installed but Cannot Launch Navigator

I figured out the reason as to why:

1-There seems to be no navigator icon

2-When conducting the above steps of running the "anaconda-navigator" command in prompt (whether cmd or Anaconda) it yields "anaconda navigator is not recognized as an internal or external command"

This was very frustrating to me as I'd installed the proper version multiple times with no avail.

To solve this problem :

  • in the installation process, there will be an advanced options step with 2 selections one of which is unchecked (the top one). Make sure you check it which will add the navigator to the path of your machine variables.

Cheers, Hossam

How to keep footer at bottom of screen

What you’re looking for is the CSS Sticky Footer.

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
  overflow: auto;_x000D_
  padding-bottom: 180px;_x000D_
  /* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
  position: relative;_x000D_
  margin-top: -180px;_x000D_
  /* negative value of footer height */_x000D_
  height: 180px;_x000D_
  clear: both;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
  content: "";_x000D_
  height: 100%;_x000D_
  float: left;_x000D_
  width: 0;_x000D_
  margin-top: -32767px;_x000D_
  /* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
  <div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
_x000D_
_x000D_

Having links relative to root?

Use this code "./" as root on the server as it works for me

<a href="./fruits/index.html">Back to Fruits List</a>

but when you are on a local machine use the following code "../" as the root relative path

<a href="../fruits/index.html">Back to Fruits List</a>

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

What killed my process and why?

If the user or sysadmin did not kill the program the kernel may have. The kernel would only kill a process under exceptional circumstances such as extreme resource starvation (think mem+swap exhaustion).

Using true and false in C

Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

Android how to use Environment.getExternalStorageDirectory()

To get the directory, you can use the code below:

File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

Regular Expression: Any character that is NOT a letter or number

  • Match letters only /[A-Z]/ig
  • Match anything not letters /[^A-Z]/ig
  • Match number only /[0-9]/g or /\d+/g
  • Match anything not number /[^0-9]/g or /\D+/g
  • Match anything not number or letter /[^A-Z0-9]/ig

There are other possible patterns

Serializing with Jackson (JSON) - getting "No serializer found"?

For Oracle Java applications, add this after the ObjectMapper instantiation:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

django admin - add custom form fields that are not part of the model

If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:

I never done something like this so I'm not completely sure how it will work out.

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

ReactJS: Maximum update depth exceeded error

onClick you should call function, thats called your function toggle.

onClick={() => this.toggle()}

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

TLDR; range is an arithmetic series so it can very easily calculate whether the object is there.It could even get the index of it if it were list like really quickly.

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Why is there no tuple comprehension in Python?

You can use a generator expression:

tuple(i for i in (1, 2, 3))

but parentheses were already taken for … generator expressions.

How to transfer data from JSP to servlet when submitting HTML form

first up on create your jsp file : and write the text field which you want
for ex:

after that create your servlet class:

public class test{

protected void doGet(paramter , paramter){

String name  = request.getparameter("name");
 }

}

'Class' does not contain a definition for 'Method'

I had the same problem. I changed the Version of Assembly in AssemblyInfo.cs in the Properties Folder. But, I don't have any idea why this problem happened. Maybe the compiler doesn't understand that this dll is newer, just changing the version of Assembly.

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

vertical-align with Bootstrap 3

I elaborated a bit on zessx's answer, in order to make it easier to use when mixing different column sizes on different screen sizes.

If you use Sass, you can add this to your scss-file:

@mixin v-col($prefix, $min-width) {
    @media (min-width: $min-width) {
        .col-#{$prefix}-v {
            display: inline-block;
            vertical-align: middle;
            float: none;
        }
    }
}

@include v-col(lg, $screen-lg);
@include v-col(md, $screen-md);
@include v-col(sm, $screen-sm);
@include v-col(xs, $screen-xs);

Which generates the following CSS (that you can use directly in your stylesheets, if you are not using Sass):

@media (min-width: 1200px) {
    .col-lg-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 992px) {
    .col-md-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 768px) {
    .col-sm-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 480px) {
    .col-xs-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

Now you can use it on your responsive columns like this:

<div class="container">
    <div class="row">
        <div class="col-sm-7 col-sm-v col-xs-12">
            <p>
                This content is vertically aligned on tablets and larger. On mobile it will expand to screen width.
            </p>
        </div><div class="col-sm-5 col-sm-v col-xs-12">
            <p>
                This content is vertically aligned on tablets and larger. On mobile it will expand to screen width.
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-7 col-md-v col-sm-12">
            <p>
                This content is vertically aligned on desktops and larger. On tablets and smaller it will expand to screen width.
            </p>
        </div><div class="col-md-5 col-md-v col-sm-12">
            <p>
                This content is vertically aligned on desktops and larger. On tablets and smaller it will expand to screen width.
            </p>
        </div>
    </div>
</div>

PHP: date function to get month of the current date

$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime); 
echo date('y', $unixtime );

Strange out of memory issue while loading an image to a Bitmap object

use this concept this will help you, After that set the imagebitmap on image view

public static Bitmap convertBitmap(String path)   {

        Bitmap bitmap=null;
        BitmapFactory.Options bfOptions=new BitmapFactory.Options();
        bfOptions.inDither=false;                     //Disable Dithering mode
        bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        bfOptions.inTempStorage=new byte[32 * 1024]; 


        File file=new File(path);
        FileInputStream fs=null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            if(fs!=null)
            {
                bitmap=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
            }
            } catch (IOException e) {

            e.printStackTrace();
        } finally{ 
            if(fs!=null) {
                try {
                    fs.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }

        return bitmap;
    }

If you want to make a small image from large image with height and width like 60 and 60 and scroll the listview fast then use this concept

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
            int reqHeight) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        return bmp;
        }

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
             }
         }
         return inSampleSize;
        }

I hope it will help you much.

You can take help from developer site Here

Hashmap holding different data types as values for instance Integer, String and Object

Create an object holding following properties with an appropriate name.

  1. message
  2. timestamp
  3. count
  4. version

and use this as a value in your map.

Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).

How to configure heroku application DNS to Godaddy Domain?

I pointed the non-www to 54.243.64.13 and the www.domain.com to the alias.herokuapp.com and all worked nicely.

Found the IP only after pointing www.domain.com and then running the dig command on the www.domain.com and it showed:

;; ANSWER SECTION:
www.domain.com. 14400  IN      CNAME   aliasat.herokuapp.com.
aliasat.herokuapp.com. 300 IN CNAME us-east-1-a.route.herokuapp.com.
us-east-1-a.route.herokuapp.com. 60 IN  A       54.235.186.37

;; AUTHORITY SECTION:
herokuapp.com.          900     IN      NS      ns-1378.awsdns-44.org.
herokuapp.com.          900     IN      NS      ns-1624.awsdns-11.co.uk.
herokuapp.com.          900     IN      NS      ns-505.awsdns-63.com.
herokuapp.com.          900     IN      NS      ns-662.awsdns-18.net.

May not be ideal but worked.

Change User Agent in UIWebView

Taking everything this is how it was solved for me:

- (void)viewDidLoad {
    NSURL *url = [NSURL URLWithString: @"http://www.amazon.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"Foobar/1.0" forHTTPHeaderField:@"User-Agent"];
    [webView loadRequest:request];
}

Thanks Everyone.

Add Twitter Bootstrap icon to Input box

Updated Bootstrap 3.x

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Working Demo in jsFiddle for 3.x


Bootstrap 2.x

You can use the .input-append class like this:

<div class="input-append">
    <input class="span2" type="text">
    <button type="submit" class="btn">
        <i class="icon-search"></i>
    </button>
</div>

Working Demo in jsFiddle for 2.x


Both will look like this:

screenshot outside

If you'd like the icon inside the input box, like this:

screenshot inside

Then see my answer to Add a Bootstrap Glyphicon to Input Box

How to disable Hyper-V in command line?

This command works

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

Run it then agree to restart the computer when prompted.

I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.

Does 'position: absolute' conflict with Flexbox?

you have forgotten width of parent

_x000D_
_x000D_
.parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to hide navigation bar permanently in android activity?

According to Android Developer site

I think you cant(as far as i know) hide navigation bar permanently..

However you can do one trick. Its a trick mind you.

Just when the navigation bar shows up when user touches the screen. Immediately hide it again. Its fun.

Check this.

void setNavVisibility(boolean visible) {
int newVis = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | SYSTEM_UI_FLAG_LAYOUT_STABLE;
if (!visible) {
    newVis |= SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_FULLSCREEN
            | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}

// If we are now visible, schedule a timer for us to go invisible.
if (visible) {
    Handler h = getHandler();
    if (h != null) {
        h.removeCallbacks(mNavHider);
        if (!mMenusOpen && !mPaused) {
            // If the menus are open or play is paused, we will not auto-hide.
            h.postDelayed(mNavHider, 1500);
        }
    }
}

// Set the new desired visibility.
setSystemUiVisibility(newVis);
mTitleView.setVisibility(visible ? VISIBLE : INVISIBLE);
mPlayButton.setVisibility(visible ? VISIBLE : INVISIBLE);
mSeekView.setVisibility(visible ? VISIBLE : INVISIBLE);
}

See this for more information on this ..

Hide System Bar in Tablets

is there a function in lodash to replace matched item

[ES6] This code works for me.

let result = array.map(item => item.id === updatedItem.id ? updatedItem : item)

Add attribute 'checked' on click jquery

A simple answer is to add checked attributes within a checkbox:

$('input[id='+$(this).attr("id")+']').attr("checked", "checked");

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

Assign an initial value to radio button as checked

The other way to set default checked on radio buttons, especially if you're using angularjs is setting the 'ng-checked' flag to "true" eg: <input id="d_man" value="M" ng-disabled="some Value" type="radio" ng-checked="true">Man

the checked="checked" did not work for me..

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

How is length implemented in Java Arrays?

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] arrays have a third header field, for the array size.

CORS: credentials mode is 'include'

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

How can I add comments in MySQL?

/* comment here */ 

here is an example: SELECT 1 /* this is an in-line comment */ + 1;

http://dev.mysql.com/doc/refman/5.0/en/comments.html

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

Read and write a text file in typescript

believe there should be a way in accessing file system.

Include node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed:

import fs from 'fs';
fs.readFileSync('foo.txt','utf8');

You can use other functions in fs as well : https://nodejs.org/api/fs.html

More

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

Difference between "git add -A" and "git add ."

A more distilled quick answer:

Does both below (same as git add --all)

git add -A

Stages new + modified files

git add .

Stages modified + deleted files

git add -u

NTFS performance and large volumes of files and directories

Here's some advice from someone with an environment where we have folders containing tens of millions of files.

  1. A folder stores the index information (links to child files & child folder) in an index file. This file will get very large when you have a lot of children. Note that it doesn't distinguish between a child that's a folder and a child that's a file. The only difference really is the content of that child is either the child's folder index or the child's file data. Note: I am simplifying this somewhat but this gets the point across.
  2. The index file will get fragmented. When it gets too fragmented, you will be unable to add files to that folder. This is because there is a limit on the # of fragments that's allowed. It's by design. I've confirmed it with Microsoft in a support incident call. So although the theoretical limit to the number of files that you can have in a folder is several billions, good luck when you start hitting tens of million of files as you will hit the fragmentation limitation first.
  3. It's not all bad however. You can use the tool: contig.exe to defragment this index. It will not reduce the size of the index (which can reach up to several Gigs for tens of million of files) but you can reduce the # of fragments. Note: The Disk Defragment tool will NOT defrag the folder's index. It will defrag file data. Only the contig.exe tool will defrag the index. FYI: You can also use that to defrag an individual file's data.
  4. If you DO defrag, don't wait until you hit the max # of fragment limit. I have a folder where I cannot defrag because I've waited until it's too late. My next test is to try to move some files out of that folder into another folder to see if I could defrag it then. If this fails, then what I would have to do is 1) create a new folder. 2) move a batch of files to the new folder. 3) defrag the new folder. repeat #2 & #3 until this is done and then 4) remove the old folder and rename the new folder to match the old.

To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:

a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or

b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.

Read below only if you're bored.

The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.

So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.

CodeIgniter - accessing $config variable in view

Example, if you have:

$config['base_url'] = 'www.example.com'

set in your config.php then

echo base_url();

This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).

How to create a drop shadow only on one side of an element?

Just use the spread parameter to make the shadow smaller:

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 6px 4px -4px black;_x000D_
  -moz-box-shadow: 0 6px 4px -4px black;_x000D_
  box-shadow: 0 6px 4px -4px black;_x000D_
}
_x000D_
<div class="shadow">Some content</div>
_x000D_
_x000D_
_x000D_

Live demo: http://dabblet.com/gist/a8f8ba527f5cff607327

To not see any shadow on the sides, the (absolute value of the) spread radius (4th parameter) needs to be the same as the blur radius (3rd parameter).

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

back arrow

If you don't want to bother with image files, the arrow shape can be drawn in a UIView subclass with the following code:

- (void)drawRect:(CGRect)rect {
    float width = rect.size.width;
    float height = rect.size.height;
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextBeginPath(context);
    CGContextMoveToPoint(context, width * 5.0/6.0, height * 0.0/10.0);
    CGContextAddLineToPoint(context, width * 0.0/6.0, height * 5.0/10.0);
    CGContextAddLineToPoint(context, width * 5.0/6.0, height * 10.0/10.0);
    CGContextAddLineToPoint(context, width * 6.0/6.0, height * 9.0/10.0);
    CGContextAddLineToPoint(context, width * 2.0/6.0, height * 5.0/10.0);
    CGContextAddLineToPoint(context, width * 6.0/6.0, height * 1.0/10.0);
    CGContextClosePath(context);

    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextFillPath(context);
}

where the arrow view is proportional to a width of 6.0 and a height of 10.0

How to hide command output in Bash

You should not use bash in this case to get rid of the output. Yum does have an option -q which suppresses the output.

You'll most certainly also want to use -y

echo "Installing nano..."
yum -y -q install nano

To see all the options for yum, use man yum.

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

.rar, .zip files MIME Type

In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:

import Foundation
import MobileCoreServices

extension URL {
    var mimeType: String? {
        guard self.pathExtension.count != 0 else {
            return nil
        }

        let pathExtension = self.pathExtension as CFString
        if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
            guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
                return nil
            }
            return mimeType.takeRetainedValue() as String
        }

        return nil
    }
}

How do I exit from a function?

I'd suggest trying to avoid using return/exit if you don't have to. Some people will devoutly tell you to NEVER do it, but sometimes it just makes sense. However if you can structure you checks so that you don't have to enter into them, I think it makes it easier for people to follow your code later.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I got this issue after migration to Gradle 3.3, on Windows (with gradle-2.14.1 everything was fine).

The problem was in the path to the Gradle build-cache, which contains Cyrillic characters, like

C:\Users\????\.android\build-cache

So I renamed the user's folder to "Ivan", and the problem was gone.

Only read selected columns

The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

Column selection (col_select)

The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().

Select columns by name
data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr  [ 4]: carrier, tailnum, origin, dest
#> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
#>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
#>  1 N142…  2013     1     1      517            515         2      830
#>  2 N242…  2013     1     1      533            529         4      850
#>  3 N619…  2013     1     1      542            540         2      923
#>  4 N804…  2013     1     1      544            545        -1     1004
#>  5 N668…  2013     1     1      554            600        -6      812
#>  6 N394…  2013     1     1      554            558        -4      740
#>  7 N516…  2013     1     1      555            600        -5      913
#>  8 N829…  2013     1     1      557            600        -3      709
#>  9 N593…  2013     1     1      557            600        -3      838
#> 10 N3AL…  2013     1     1      558            600        -2      753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> #   time_hour <dttm>

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I have similar issue, check header if it's not match then run below command

CentOS: sudo yum update && sudo yum -y install kernel-headers kernel-devel

Is there an "if -then - else " statement in XPath?

Yes, there is a way to do it in XPath 1.0:

concat(
  substring($s1, 1, number($condition)      * string-length($s1)),
  substring($s2, 1, number(not($condition)) * string-length($s2))
)

This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false (0 * string-length(...)), the second one being empty if the condition is true. This is called "Becker's method", attributed to Oliver Becker.

In your case:

concat(
  substring(
    substring-before(//div[@id='head']/text(), ': '),
    1, 
    number(
      ends-with(//div[@id='head']/text(), ': ')
    )
    * string-length(substring-before(//div [@id='head']/text(), ': '))
  ),
  substring(
    //div[@id='head']/text(), 
    1, 
    number(not(
      ends-with(//div[@id='head']/text(), ': ')
    ))
    * string-length(//div[@id='head']/text())
  )
)

Though I would try to get rid of all the "//" before.

Also, there is the possibility that //div[@id='head'] returns more than one node.
Just be aware of that — using //div[@id='head'][1] is more defensive.

Android - Handle "Enter" in an EditText

This should work

input.addTextChangedListener(new TextWatcher() {

           @Override
           public void afterTextChanged(Editable s) {}

           @Override    
           public void beforeTextChanged(CharSequence s, int start,
             int count, int after) {
           }

           @Override    
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });

Stacking DIVs on top of each other?

If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index CSS attribute. This should work (untested)

<div>
    <div style='z-index: 1'>1</div>
    <div style='z-index: 2'>2</div>
    <div style='z-index: 3'>3</div>
    <div style='z-index: 4'>4</div>
</div>

This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)

How to set background image in Java?

Firstly create a new class that extends the WorldView class. I called my new class Background. So in this new class import all the Java packages you will need in order to override the paintBackground method. This should be:

import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;

Next after the class name make sure that it says extends WorldView. Something like this:

public class Background extends WorldView

Then declare the variables game of type Game and an image variable of type Image something like this:

private Game game;
private Image image;

Then in the constructor of this class make sure the game of type Game is in the signature of the constructor and that in the call to super you will have to initialise the WorldView, initialise the game and initialise the image variables, something like this:

super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();

Then you just override the paintBackground method in exactly the same way as you did when overriding the paint method in the Player class. Just like this:

public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}

Now finally you have to declare a class level reference to the new class you just made in the Game class and initialise this in the Game constructor, something like this:

private Background image;

And in the Game constructor:
image = new Background(this);

Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame has been declared:

frame.add(image);

Make sure you add this code just before frame.pack();. Also make sure you use a background image that isn't too big!

Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.

Sending emails with Javascript

You can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

Add st, nd, rd and th (ordinal) suffix to a number

I wanted to provide a functional answer to this question to complement the existing answer:

const ordinalSuffix = ['st', 'nd', 'rd']
const addSuffix = n => n + (ordinalSuffix[(n - 1) % 10] || 'th')
const numberToOrdinal = n => `${n}`.match(/1\d$/) ? n + 'th' : addSuffix(n)

we've created an array of the special values, the important thing to remember is arrays have a zero based index so ordinalSuffix[0] is equal to 'st'.

Our function numberToOrdinal checks if the number ends in a teen number in which case append the number with 'th' as all then numbers ordinals are 'th'. In the event that the number is not a teen we pass the number to addSuffix which adds the number to the ordinal which is determined by if the number minus 1 (because we're using a zero based index) mod 10 has a remainder of 2 or less it's taken from the array, otherwise it's 'th'.

sample output:

numberToOrdinal(1) // 1st
numberToOrdinal(2) // 2nd
numberToOrdinal(3) // 3rd
numberToOrdinal(4) // 4th
numberToOrdinal(5) // 5th
numberToOrdinal(6) // 6th
numberToOrdinal(7) // 7th
numberToOrdinal(8) // 8th
numberToOrdinal(9) // 9th
numberToOrdinal(10) // 10th
numberToOrdinal(11) // 11th
numberToOrdinal(12) // 12th
numberToOrdinal(13) // 13th
numberToOrdinal(14) // 14th
numberToOrdinal(101) // 101st

ImageView rounded corners

Now we no need to use any third party lib or custom imageView

Now We can use ShapeableImageView

SAMPLE CODE

First add below dependencies in your build.gradle file

implementation 'com.google.android.material:material:1.2.0-alpha05'

Make ImageView Circular from coding

Add ShapeableImageView in your layout

<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/nilesh" />

Kotlin code to make ImageView Circle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.shape.CornerFamily
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


//        <dimen name="image_corner_radius">50dp</dimen>

        val radius = resources.getDimension(R.dimen.image_corner_radius)
        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setTopRightCorner(CornerFamily.ROUNDED, radius)
            .setTopLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomRightCorner(CornerFamily.ROUNDED, radius)
            .build()

            // or  You can use setAllCorners() method

        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED, radius)
            .build()


    }
}

OUTPUT

enter image description here

Make ImageView Circle from using a style

First, create a below style in your style.xml

<style name="circleImageViewStyle" >
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

Now use that style in your layout like this

<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:shapeAppearanceOverlay="@style/circleImageViewStyle"
    app:srcCompat="@drawable/nilesh" />

OUTPUT

enter image description here

Please find the complete exmaple here how to use ShapeableImageView

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

I think that replacing:

List<String> list = Arrays.asList(split);

with

List<String> list = new ArrayList<String>(Arrays.asList(split));

resolves the problem.

How do you create vectors with specific intervals in R?

Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)

a <- 1:10
b <- 4

FunctionIntervalM <- function(a,b) {
  seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}

FunctionIntervalM(a,b)
# 1.00  3.25  5.50  7.75 10.00

Therefore you have 4 intervals:

1.00 - 3.25 
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00

You can also use a cut function

  cut(a, 4)

# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5]   (3.25,5.5]   (5.5,7.75]  
# (5.5,7.75]   (7.75,10]    (7.75,10]    (7.75,10]   
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]

Using global variables in a function

Writing to explicit elements of a global array does not apparently need the global declaration, though writing to it "wholesale" does have that requirement:

import numpy as np

hostValue = 3.14159
hostArray = np.array([2., 3.])
hostMatrix = np.array([[1.0, 0.0],[ 0.0, 1.0]])

def func1():
    global hostValue    # mandatory, else local.
    hostValue = 2.0

def func2():
    global hostValue    # mandatory, else UnboundLocalError.
    hostValue += 1.0

def func3():
    global hostArray    # mandatory, else local.
    hostArray = np.array([14., 15.])

def func4():            # no need for globals
    hostArray[0] = 123.4

def func5():            # no need for globals
    hostArray[1] += 1.0

def func6():            # no need for globals
    hostMatrix[1][1] = 12.

def func7():            # no need for globals
    hostMatrix[0][0] += 0.33

func1()
print "After func1(), hostValue = ", hostValue
func2()
print "After func2(), hostValue = ", hostValue
func3()
print "After func3(), hostArray = ", hostArray
func4()
print "After func4(), hostArray = ", hostArray
func5()
print "After func5(), hostArray = ", hostArray
func6()
print "After func6(), hostMatrix = \n", hostMatrix
func7()
print "After func7(), hostMatrix = \n", hostMatrix

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

How to Test Facebook Connect Locally

Edit your app at www.facebook.com/developers/ and set the "Site URL" to "http://localhost/myapppath".

When done - change it back.

Connection string using Windows Authentication

Replace the username and password with Integrated Security=SSPI;

So the connection string should be

<connectionStrings> 
<add name="NorthwindContex" 
   connectionString="data source=localhost;
   initial catalog=northwind;persist security info=True; 
   Integrated Security=SSPI;" 
   providerName="System.Data.SqlClient" /> 
</connectionStrings> 

How to connect to a secure website using SSL in Java with a pkcs12 file?

This is an example to use ONLY p12 file it's not optimazed but it work. The pkcs12 file where generated by OpenSSL by me. Example how to load p12 file and build Trust zone from it... It outputs certificates from p12 file and add good certs to TrustStore

KeyStore ks=KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream("client_t_c1.p12"),"c1".toCharArray());

KeyStore jks=KeyStore.getInstance("JKS");
jks.load(null);

for (Enumeration<String>t=ks.aliases();t.hasMoreElements();)
{
    String alias = t.nextElement();
    System.out.println("@:" + alias);
    if (ks.isKeyEntry(alias)){
        Certificate[] a = ks.getCertificateChain(alias);
        for (int i=0;i<a.length;i++)
        {
            X509Certificate x509 = (X509Certificate)a[i];
            System.out.println(x509.getSubjectDN().toString());
            if (i>0)
                jks.setCertificateEntry(x509.getSubjectDN().toString(), x509);
            System.out.println(ks.getCertificateAlias(x509));
            System.out.println("ok");
        }
    }
}

System.out.println("init Stores...");

KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "c1".toCharArray());

TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");
tmf.init(jks);

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

Cannot use string offset as an array in php

Since the release PHP 7.1+, is not more possible to assign a value for an array as follow:

$foo = ""; 
$foo['key'] = $foo2; 

because as of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.

Implement division with bit-wise operator

The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.

Code

-(int)binaryDivide:(int)numerator with:(int)denominator
{
    if (numerator == 0 || denominator == 1) {
        return numerator;
    }

    if (denominator == 0) {

        #ifdef DEBUG
            NSAssert(denominator == 0, @"denominator should be greater then 0");
        #endif
        return INFINITY;
    }

    // if (numerator <0) {
    //     numerator = abs(numerator);
    // }

    int maxBitDenom = [self getMaxBit:denominator];
    int maxBitNumerator = [self getMaxBit:numerator];
    int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];

    int qoutient = 0;

    int subResult = 0;

    int remainingBits = maxBitNumerator-maxBitDenom;

    if (msbNumber >= denominator) {
        qoutient |=1;
        subResult = msbNumber - denominator;
    }
    else {
        subResult = msbNumber;
    }

    while (remainingBits>0) {
        int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
        subResult = (subResult << 1) |msbBit;
        if (subResult >= denominator) {
            subResult = subResult-denominator;
            qoutient = (qoutient << 1) | 1;
        }
        else {
            qoutient = qoutient << 1;
        }
        remainingBits--;
    }
    return qoutient;
}


-(int)getMaxBit:(int)inputNumber
{
    int maxBit =0;
    BOOL isMaxBitSet = NO;
    for (int i=0; i<sizeof(inputNumber)*8; i++) {
        if (inputNumber & (1 << i) ) {
            maxBit = i;
            isMaxBitSet=YES;
        }
    }
    if (isMaxBitSet) {
        maxBit += 1;
    }
    return maxBit;
}


-(int)getMSB:(int)bits ofNumber:(int)number
{
    int numbeMaxBit = [self getMaxBit:number];
    return number >> (numbeMaxBit -bits);
}

What is the difference between tree depth and height?

height and depth of a tree is equal...

but height and depth of a node is not equal because...

the height is calculated by traversing from the given node to the deepest possible leaf.

depth is calculated from traversal from root to the given node.....

Arrays in unix shell?

To read the values from keybord and insert element into array

# enter 0 when exit the insert element
echo "Enter the numbers"
read n
while [ $n -ne 0 ]
do
    x[$i]=`expr $n`
    read n
    let i++
done

#display the all array elements
echo "Array values ${x[@]}"
echo "Array values ${x[*]}"

# To find the array length
length=${#x[*]}
echo $length

How to remove folders with a certain name

find path/to/the/folders -maxdepth 1 -name "my_*" -type d -delete

What do the crossed style properties in Google Chrome devtools mean?

In addition to the above answer I also want to highlight a case of striked out property which really surprised me.

If you are adding a background image to a div :

<div class = "myBackground">

</div>

You want to scale the image to fit in the dimensions of the div so this would be your normal class definition.

.myBackground {

 height:100px;
 width:100px;
 background: url("/img/bck/myImage.jpg") no-repeat; 
 background-size: contain;

}

but if you interchange the order as :-

.myBackground {
 height:100px;
 width:100px;
 background-size: contain;  //before the background
 background: url("/img/bck/myImage.jpg") no-repeat; 
}

then in chrome you ll see background-size as striked out. I am not sure why this is , but yeah you dont want to mess with it.