Programs & Examples On #Phptal

PHPTAL is a templating engine for PHP5 that implements the brilliant Zope Page Templates syntax.

How can I make a program wait for a variable change in javascript?

Alternatively, you can make a function that executes tasks based on the value of its "Static" variables, example below:

enter image description here

<!DOCTYPE html>

<div id="Time_Box"> Time </div>

<button type="button" onclick='Update_Time("on")'>Update Time On</button>
<button type="button" onclick='Update_Time("off")'>Update Time Off</button>

<script>

var Update_Time = (function () {     //_____________________________________________________________

var Static = [];             //"var" declares "Static" variable as static object in this function

    return function (Option) {

    var Local = [];           //"var" declares "Local" variable as local object in this function

        if (typeof Option === 'string'){Static.Update = Option};

        if (Static.Update === "on"){
        document.getElementById("Time_Box").innerText = Date();

        setTimeout(function(){Update_Time()}, 1000);    //update every 1 seconds
        };

    };

})();  

Update_Time('on');    //turns on time update

</script>

dropping a global temporary table

  1. Down the apache server by running below in putty cd $ADMIN_SCRIPTS_HOME ./adstpall.sh
  2. Drop the Global temporary tables drop table t;

This will workout..

What is the difference between #include <filename> and #include "filename"?

"" will search ./ first. then search the default include path. you can use command like this to print the default include path:

 gcc -v -o a a.c

here are some examples to make thing more clear: the code a.c works

// a.c
#include "stdio.h"
int main() {
        int a = 3;
        printf("a = %d\n", a);
        return 0;

}

the code of b.c works too

\\ b.c
#include <stdio.h>
int main() {
        int a = 3;
        printf("a = %d\n", a);
        return 0;

}

but when I create a new file named stdio.h in current directory

// stdio.h
inline int foo()
{
        return 10;
}

a.c will generate compile error, but b.c still works

and "", <> can be used together with the same file name. since the search path priority is different. so d.c also works

// d.c
#include <stdio.h>
#include "stdio.h"
int main()
{
        int a = 0;

        a = foo();

        printf("a=%d\n", a);

        return 0;
}

~

How to do SQL Like % in Linq?

System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")

How to create composite primary key in SQL Server 2008

create table my_table (
     column_a integer not null,
     column_b integer not null,
     column_c varchar(50),
     primary key (column_a, column_b)
);

Get Category name from Post ID

echo '<p>'. get_the_category( $id )[0]->name .'</p>';

is what you maybe looking for.

Android: Unable to add window. Permission denied for this window type

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);

} else {
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);


    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);
}

Shell Script — Get all files modified after <date>

This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)

PATH_SRC="/home/celvas/Documents/Imp_Task/"
PATH_DST="/home/celvas/Downloads/zeeshan/"

cd $PATH_SRC
TODAY=$(date  -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)


for f in `ls`;
do
#       echo "File -> $f"
        MOD_DATE=$(stat -c %y "$f")
        MOD_DATE=${MOD_DATE% *}
#       echo MOD_DATE: $MOD_DATE
        MOD_DATE1=$(date -d "$MOD_DATE" +%s)
#       echo MOD_DATE: $MOD_DATE

DIFF_IN_DATE=$[ $MOD_DATE1 - $TODAY ]
DIFF_IN_DATE1=$[ $MOD_DATE1 - $TODAY_TIME ]
#echo DIFF: $DIFF_IN_DATE
#echo DIFF1: $DIFF_IN_DATE1
if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
then
echo File lies in Next Hour = $f
echo MOD_DATE: $MOD_DATE

#mv $PATH_SRC/$f  $PATH_DST/$f
fi
done

For example you want files having modification date before the given date only, you may change 120 to 0 in $DIFF_IN_DATE parameter discarding the conditions of $DIFF_IN_DATE1 parameter.

Similarly if you want files having modification date 1 hour before and after given date, just replace 120 by 3600 in if CONDITION.

Default parameters with C++ constructors

Mostly personal choice. However, overload can do anything default parameter can do, but not vice versa.

Example:

You can use overload to write A(int x, foo& a) and A(int x), but you cannot use default parameter to write A(int x, foo& = null).

The general rule is to use whatever makes sense and makes the code more readable.

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

Python, Pandas : write content of DataFrame into text File

The current best way to do this is to use df.to_string() :

with open(writePath, 'a') as f:
    f.write(
        df.to_string(header = False, index = False)
    )

Will output the following

18 55 1 70   
18 55 2 67 
18 57 2 75     
18 58 1 35  
19 54 2 70 

This method also lets you easily choose which columns to print with the columns attribute, lets you keep the column, index labels if you wish, and has other attributes for spacing ect.

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

How to clear https proxy setting of NPM?

In my case, (windows OS), after put all those commands listed, npm kept taking the proxy in the setting of windows registry

\ HKEY_CURRENT_USER \ Environment

just remove the proxy settings there, after that, I restarted the pc and then "npm install" worked for me

Example

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

How to split a delimited string in Ruby and convert it to an array?

"12345".each_char.map(&:to_i)

each_char does basically the same as split(''): It splits a string into an array of its characters.

hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

ReSharper "Cannot resolve symbol" even when project builds

I my case, I tried all the suggestions above. But, at some point I realized that the problem persists even if Resharper is suspended. So, I looked for similar problem in VS itself and found the solution in the comments for the accepted answer in this SO post.

I'm listing my steps for brevity.

  1. VS -> Tools -> Options -> ReSharper Suspend button
  2. Build solution. Notice all references still unresolved
  3. Clean the solution
  4. Restart VS
  5. Build the solution without Resharper. Notice all references resolved
  6. VS -> Tools -> Options -> ReSharper Resume button

Take nth column in a text file

One more simple variant -

$ while read line
  do
      set $line          # assigns words in line to positional parameters
      echo "$3 $5"
  done < file

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

IIS - 401.3 - Unauthorized

Here is what worked for me.

  1. Set the app pool identity to an account that can be assigned permissions to a folder.
  2. Ensure the source directory and all related files have been granted read rights to the files to the account assigned to the app pool identity property
  3. In IIS, at the server root node, set anonymous user to inherit from app pool identity. (This was the part I struggled with)

To set the server anonymous to inherit from the app pool identity do the following..

  • Open IIS Manager (inetmgr)
  • In the left-hand pane select the root node (server host name)
  • In the middle pane open the 'Authentication' applet
  • Highlight 'Anonymous Authentication'
  • In the right-hand pane select 'Edit...' (a dialog box should open)
  • select 'Application pool identity'

How to get Django and ReactJS to work together?

I feel your pain as I, too, am starting out to get Django and React.js working together. Did a couple of Django projects, and I think, React.js is a great match for Django. However, it can be intimidating to get started. We are standing on the shoulders of giants here ;)

Here's how I think, it all works together (big picture, please someone correct me if I'm wrong).

  • Django and its database (I prefer Postgres) on one side (backend)
  • Django Rest-framework providing the interface to the outside world (i.e. Mobile Apps and React and such)
  • Reactjs, Nodejs, Webpack, Redux (or maybe MobX?) on the other side (frontend)

Communication between Django and 'the frontend' is done via the Rest framework. Make sure you get your authorization and permissions for the Rest framework in place.

I found a good boiler template for exactly this scenario and it works out of the box. Just follow the readme https://github.com/scottwoodall/django-react-template and once you are done, you have a pretty nice Django Reactjs project running. By no means this is meant for production, but rather as a way for you to dig in and see how things are connected and working!

One tiny change I'd like to suggest is this: Follow the setup instructions BUT before you get to the 2nd step to setup the backend (Django here https://github.com/scottwoodall/django-react-template/blob/master/backend/README.md), change the requirements file for the setup.

You'll find the file in your project at /backend/requirements/common.pip Replace its content with this

appdirs==1.4.0
Django==1.10.5
django-autofixture==0.12.0
django-extensions==1.6.1
django-filter==1.0.1
djangorestframework==3.5.3
psycopg2==2.6.1

this gets you the latest stable version for Django and its Rest framework.

I hope that helps.

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I found the solution to the problem of serializing entities was as follows:

#config/config.yml

services:
    serializer.method:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    serializer.encoder.json:
        class: Symfony\Component\Serializer\Encoder\JsonEncoder
    serializer:
        class: Symfony\Component\Serializer\Serializer
        arguments:
            - [@serializer.method]
            - {json: @serializer.encoder.json }

in my controller:

$serializer = $this->get('serializer');

$entity = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findOneBy($params);


$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$toEncode = array(
    'response' => array(
        'entity' => $serializer->normalize($entity),
        'entities' => $serializer->normalize($collection)
    ),
);

return new Response(json_encode($toEncode));

other example:

$serializer = $this->get('serializer');

$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$json = $serializer->serialize($collection, 'json');

return new Response($json);

you can even configure it to deserialize arrays in http://api.symfony.com/2.0

"Unable to find remote helper for 'https'" during git clone

This worked for me in Centos 6.6 to install git 2.3.1:

  1. I didn't have curl-devel installed (checking for curl_global_init in -lcurl... no). The key was to generate configure script

  2. add rpmforge for docboox2x

  3. install packages

    yum install openssl-devel zlib-devel perl-ExtUtils-MakeMaker svn tcl perl-Locale-Msgfmt gettext asciidoc xmlto docbook2x
    
  4. make symlink

    ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
    
  5. build git

    # download latest relase from https://github.com/git/git/releases
    curl -O -J -L https://github.com/git/git/archive/v2.13.0.tar.gz
    tar xf git-2.13.0.tar.gz
    cd git-2.13.0
    make configure
    ./configure --prefix=/usr
    make all doc
    make install install-doc install-html
    

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

This happens sometimes when I'm trying to open my old projects, what helps me is to change projects target framework. Go to Project -> projectname Properties... and change the Target framework to the one that you have installed. Project properties

Is object empty?

How bad is this?

function(obj){
    for(var key in obj){
        return false; // not empty
    }

    return true; // empty
}

How to drop a database with Mongoose?

The best way to drop your database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that 4.6.4 or newer, then this method added in that release is likely going to work fine for you:

mongoose.connection.dropDatabase();

In older releases this method did not exist. Instead, you were to use a direct MongoDB call:

mongoose.connection.db.dropDatabase();

However, if this was run just after the database connection was created, it could possibly fail silently. This is related to the connection actually be asynchronous and not being set up yet when the command happens. This is not normally a problem for other Mongoose calls like .find(), which queue until the connection is open and then run.

If you look at the source code for the dropDatabase() shortcut that was added, you can see it was designed to solve this exact problem. It checks to see if the connection is open and ready. If so, it fires the command immediately. If not, it registers the command to run when the database connection has opened.

Some of the suggestions above recommend always putting your dropDatabase command in the open handler. But that only works in the case when the connection is not open yet.

Connection.prototype.dropDatabase = function(callback) {
  var Promise = PromiseProvider.get();
  var _this = this;
  var promise = new Promise.ES6(function(resolve, reject) {
    if (_this.readyState !== STATES.connected) {
      _this.on('open', function() {
        _this.db.dropDatabase(function(error) {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
    } else {
      _this.db.dropDatabase(function(error) {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    }
  });
  if (callback) {
    promise.then(function() { callback(); }, callback);
  }
  return promise;
};

Here's a simple version of the above logic that can be used with earlier Mongoose versions:

// This shim is backported from Mongoose 4.6.4 to reliably drop a database
// http://stackoverflow.com/a/42860208/254318
// The first arg should be "mongoose.connection"
function dropDatabase (connection, callback) {
    // readyState 1 === 'connected'
    if (connection.readyState !== 1) {
      connection.on('open', function() {
        connection.db.dropDatabase(callback);
      });
    } else {
      connection.db.dropDatabase(callback);
    }
}  

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

Finding the max/min value in an array of primitives using Java

Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

How do you query for "is not null" in Mongo?

the Query Will be

db.mycollection.find({"IMAGE URL":{"$exists":"true"}})

it will return all documents having "IMAGE URL" as a key ...........

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

Windows equivalent of OS X Keychain?

Credential dumping on Windows, even with "Credential Manager" is still an issue, and I don't think there is any way to prevent it outside of special hardware. MacOS keychain doesn't have this problem and so I don't think there is an exact equivalent.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

WARNING: sanitizing unsafe style value url

You have to wrap the entire url statement in the bypassSecurityTrustStyle:

<div class="header" *ngIf="image" [style.background-image]="image"></div>

And have

this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);

Otherwise it is not seen as a valid style property

How do you run a Python script as a service in Windows?

https://www.chrisumbel.com/article/windows_services_in_python

  1. Follow up the PySvc.py

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

How can I make a clickable link in an NSAttributedString?

Use UITextView it supports clickable Links. Create attributed string using the following code

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

Then set UITextView text as follows

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],

                                 NSUnderlineColorAttributeName: [UIColor blueColor],

                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

Make sure that you enable "Selectable" behavior of the UITextView in XIB.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

TypeError: 'dict_keys' object does not support indexing

Clearly you're passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it can't be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

What's "this" in JavaScript onclick?

In JavaScript this refers to the element containing the action. For example, if you have a function called hide():

function hide(element){
   element.style.display = 'none';
}

Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.

For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.

<ul>
  <li class="bullet" onclick="hide(this);">1</li>
  <li class="bullet" onclick="hide(this);">2</li>
  <li class="bullet" onclick="hide(this);">3</li>
  <li class="bullet" onclick="hide(this);">4</li>
</ul>

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

What is the difference between ndarray and array in numpy?

numpy.array is just a convenience function to create an ndarray; it is not a class itself.

You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray:

Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:

https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py

How can I convert ArrayList<Object> to ArrayList<String>?

Using Java 8 you can do:

List<Object> list = ...;
List<String> strList = list.stream()
                           .map( Object::toString )
                           .collect( Collectors.toList() );

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

chrome undo the action of "prevent this page from creating additional dialogs"

No. But you should really use console.log() instead of alert() for debugging.

In Chrome it even has the advantage of being able to print out entire objects (not just toString()).

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

How can I get the IP address from NIC in Python?

If you only need to work on Unix, you can use a system call (ref. Stack Overflow question Parse ifconfig to get only my IP address using Bash):

import os
f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
your_ip=f.read()

Sqlite primary key on multiple columns

Since version 3.8.2 of SQLite, an alternative to explicit NOT NULL specifications is the "WITHOUT ROWID" specification: [1]

NOT NULL is enforced on every column of the PRIMARY KEY
in a WITHOUT ROWID table.

"WITHOUT ROWID" tables have potential efficiency advantages, so a less verbose alternative to consider is:

CREATE TABLE t (
  c1, 
  c2, 
  c3, 
  PRIMARY KEY (c1, c2)
 ) WITHOUT ROWID;

For example, at the sqlite3 prompt: sqlite> insert into t values(1,null,3); Error: NOT NULL constraint failed: t.c2

Check whether variable is number or string in JavaScript

Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.

function is_number(x) { return x === x+0;  }
function is_string(x) { return x === x+""; }

For some unfathomable reason, x===x+0 seems to perform better than x===+x.

Are there any cases where this fails?

In the same vein:

function is_boolean(x) { return x === !!x; }

This appears to be mildly faster than either x===true || x===false or typeof x==="boolean" (and much faster than x===Boolean(x)).

Then there's also

function is_regexp(x)  { return x === RegExp(x); }

All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question. I cannot think of such an operation for dates.

For NaN, there is

function is_nan(x) { return x !== x;}

This is basically underscore's version, and as it stands is about four times faster than isNaN(), but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber. Why? What other objects would not equal themselves? Also, underscore uses x !== +x--but what difference could the + here make?

Then for the paranoid:

function is_undefined(x) { return x===[][0]; }

or this

function is_undefined(x) { return x===void(0); }

How to extend / inherit components?

if you read through the CDK libraries and the material libraries, they're using inheritance but not so much for components themselves, content projection is king IMO. see this link https://blog.angular-university.io/angular-ng-content/ where it says "the key problem with this design"

I know this doesn't answer your question but I really think inheriting / extending components should be avoided. Here's my reasoning:

If the abstract class extended by two or more components contains shared logic: use a service or even create a new typescript class that can be shared between the two components.

If the abstract class... contains shared variables or onClicketc functions, Then there will be duplication between the html of the two extending components views. This is bad practice & that shared html needs to be broken into Component(s). These Component(s) (parts) can be shared between the two components.

Am I missing other reasons for having an abstract class for components?

An example I saw recently was components extending AutoUnsubscribe:

import { Subscription } from 'rxjs';
import { OnDestroy } from '@angular/core';
export abstract class AutoUnsubscribeComponent implements OnDestroy {
  protected infiniteSubscriptions: Array<Subscription>;

  constructor() {
    this.infiniteSubscriptions = [];
  }

  ngOnDestroy() {
    this.infiniteSubscriptions.forEach((subscription) => {
      subscription.unsubscribe();
    });
  }
}

this was bas because throughout a large codebase, infiniteSubscriptions.push() was only used 10 times. Also importing & extending AutoUnsubscribe actually takes more code than just adding mySubscription.unsubscribe() in the ngOnDestroy() method of the component itself, which required additional logic anyway.

Does JavaScript have the interface type (such as Java's 'interface')?

There's no notion of "this class must have these functions" (that is, no interfaces per se), because:

  1. JavaScript inheritance is based on objects, not classes. That's not a big deal until you realize:
  2. JavaScript is an extremely dynamically typed language -- you can create an object with the proper methods, which would make it conform to the interface, and then undefine all the stuff that made it conform. It'd be so easy to subvert the type system -- even accidentally! -- that it wouldn't be worth it to try and make a type system in the first place.

Instead, JavaScript uses what's called duck typing. (If it walks like a duck, and quacks like a duck, as far as JS cares, it's a duck.) If your object has quack(), walk(), and fly() methods, code can use it wherever it expects an object that can walk, quack, and fly, without requiring the implementation of some "Duckable" interface. The interface is exactly the set of functions that the code uses (and the return values from those functions), and with duck typing, you get that for free.

Now, that's not to say your code won't fail halfway through, if you try to call some_dog.quack(); you'll get a TypeError. Frankly, if you're telling dogs to quack, you have slightly bigger problems; duck typing works best when you keep all your ducks in a row, so to speak, and aren't letting dogs and ducks mingle together unless you're treating them as generic animals. In other words, even though the interface is fluid, it's still there; it's often an error to pass a dog to code that expects it to quack and fly in the first place.

But if you're sure you're doing the right thing, you can work around the quacking-dog problem by testing for the existence of a particular method before trying to use it. Something like

if (typeof(someObject.quack) == "function")
{
    // This thing can quack
}

So you can check for all the methods you can use before you use them. The syntax is kind of ugly, though. There's a slightly prettier way:

Object.prototype.can = function(methodName)
{
     return ((typeof this[methodName]) == "function");
};

if (someObject.can("quack"))
{
    someObject.quack();
}

This is standard JavaScript, so it should work in any JS interpreter worth using. It has the added benefit of reading like English.

For modern browsers (that is, pretty much any browser other than IE 6-8), there's even a way to keep the property from showing up in for...in:

Object.defineProperty(Object.prototype, 'can', {
    enumerable: false,
    value: function(method) {
        return (typeof this[method] === 'function');
    }
}

The problem is that IE7 objects don't have .defineProperty at all, and in IE8, it allegedly only works on host objects (that is, DOM elements and such). If compatibility is an issue, you can't use .defineProperty. (I won't even mention IE6, because it's rather irrelevant anymore outside of China.)

Another issue is that some coding styles like to assume that everyone writes bad code, and prohibit modifying Object.prototype in case someone wants to blindly use for...in. If you care about that, or are using (IMO broken) code that does, try a slightly different version:

function can(obj, methodName)
{
     return ((typeof obj[methodName]) == "function");
}

if (can(someObject, "quack"))
{
    someObject.quack();
}

Apache shows PHP code instead of executing it

Wow, lots of solutions here! Here's what I did on Ubuntu 16.04:

sudo apt-get install php libapache2-mod-php
sudo a2enmod mpm_prefork && sudo a2enmod php7.0
sudo service apache2 restart

How to add a WiX custom action that happens only on uninstall (via MSI)?

Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.

<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
 <SetProperty Id="_INSTALL"   After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
 <SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
 <SetProperty Id="_CHANGE"    After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
 <SetProperty Id="_REPAIR"    After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
 <SetProperty Id="_UPGRADE"   After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>

Here's some sample usage:

  <Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
  <Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
  <Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
  <Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
  <Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>

Issues:

Proper way to set response status and JSON content in a REST API made with nodejs and express

FOR IIS

If you are using iisnode to run nodejs through IIS, keep in mind that IIS by default replaces any error message you send.

This means that if you send res.status(401).json({message: "Incorrect authorization token"}) You would get back You do not have permission to view this directory or page.

This behavior can be turned off by using adding the following code to your web.config file under <system.webServer> (source):

<httpErrors existingResponse="PassThrough" />

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

How does Python return multiple values from a function?

mentioned also here, you can use this:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

What is the best way to compare 2 folder trees on windows?

You can use git for exactly this purpose. Basically, you create a git repository in folder A (the repo is in A/.git), then copy A/.git to B/.git, then change to B folder and compare simply by running git diff. And the --exclude functionality can be achieved with .gitignore.

So, sticking to your example (but using bash shell on Linux):

# Create a Git repo in current_vss
pushd current_vss
printf ".svn\n*.vspscc\n*.scc" >> .gitignore
git init && git add . && git commit -m 'initial'
popd

# Copy the repo to current_svn and compare
cp -r current_vss/.git* current_svn/
pushd current_svn
git diff

Difference between HttpModule and HttpClientModule

This is a good reference, it helped me switch my http requests to httpClient.

It compares the two in terms of differences and gives code examples.

This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :

Importing

import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';

Requesting and parsing response:

@angular/http

 this.http.get(url)
      // Extract the data in HTTP Response (parsing)
      .map((response: Response) => response.json() as GithubUser)
      .subscribe((data: GithubUser) => {
        // Display the result
        console.log('TJ user data', data);
      });

@angular/common/http

 this.http.get(url)
      .subscribe((data: GithubUser) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.

But, if you need to parse any other type of response like text or blob, then make sure you add the responseType in the request. Like so:

Making the GET HTTP request with responseType option:

 this.http.get(url, {responseType: 'blob'})
      .subscribe((data) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Adding Interceptor

I also used interceptors for adding the token for my authorization to every request, reference.

like so:

@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {

    constructor(private currentUserService: CurrentUserService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // get the token from a service
        const token: string = this.currentUserService.token;

        // add it if we have one
        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        // if this is a login-request the header is 
        // already set to x/www/formurl/encoded. 
        // so if we already have a content-type, do not 
        // set it, but if we don't have one, set it to 
        // default --> json
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        // setting the accept header
        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        return next.handle(req);
    }
}

Its a pretty nice upgrade!

Is quitting an application frowned upon?

You have probably spent many years writing "proper" programs for "proper" computers. You say you are learning to program in Android. This is just one of the things you have to learn. You can't spent years doing watercolour painting and assume that oil painting works exactly the same way. This was the very least of the things that were new concepts to me when I wrote my first app eight years ago.

UTF-8 encoding in JSP page

This thread can help you: Passing request parameters as UTF-8 encoded strings

Basically:

request.setCharacterEncoding("UTF-8");
String login = request.getParameter("login");
String password = request.getParameter("password");

Or you use javascript on jsp file:

var userInput = $("#myInput").val();            
var encodedUserInput = encodeURIComponent(userInput);
$("#hiddenImput").val(encodedUserInput);

and after recover on class:

String parameter = URLDecoder.decode(request.getParameter("hiddenImput"), "UTF-8");

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.

However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.

You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.

A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.

Create Test Intention

Create Test Dialog

You can find more details in the Testing help section of the on-line documentation.

How do you load custom UITableViewCells from Xib files?

Loading UITableViewCells from XIBs saves a lot of code, but usually results in horrible scrolling speed (actually, it's not the XIB but the excessive use of UIViews that cause this).

I suggest you take a look at this: Link reference

ReflectionException: Class ClassName does not exist - Laravel

You may try to write app in use uppercase, so App. Worked for me.

How to get a context in a recycler view adapter

You can use pub_image context (holder.pub_image.getContext()) :

@Override
public void onBindViewHolder(ViewHolder ViewHolder, int position) {

    holder.txtHeader.setText(mDataset.get(position).getPost_text());

    Picasso.with(holder.pub_image.getContext()).load("http://i.imgur.com/DvpvklR.png").into(holder.pub_image);


}

Access parent URL from iframe

In chrome it is possible to use location.ancestorOrigins It will return all parent urls

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

How to import a module given its name as string?

The recommended way for Python 2.7 and 3.1 and later is to use importlib module:

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

e.g.

my_module = importlib.import_module('os.path')

SQL Server after update trigger

You should be able to access the INSERTED table and retrieve ID or table's primary key. Something similar to this example ...

CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
AFTER UPDATE AS 
BEGIN
    DECLARE @id AS INT
    SELECT @id = [IdColumnName]
    FROM INSERTED

    UPDATE MYTABLE 
    SET mytable.CHANGED_ON = GETDATE(),
    CHANGED_BY=USER_NAME(USER_ID())
    WHERE [IdColumnName] = @id

Here's a link on MSDN on the INSERTED and DELETED tables available when using triggers: http://msdn.microsoft.com/en-au/library/ms191300.aspx

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

Column name or number of supplied values does not match table definition

This is an older post but I want to also mention that if you have something like

insert into blah
       select * from blah2

and blah and blah2 are identical keep in mind that a computed column will throw this same error...

I just realized that when the above failed and I tried

insert into blah (cola, colb, colc)
       select cola, colb, colc from blah2

In my example it was fullname field (computed from first and last, etc)

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

How can I install Apache Ant on Mac OS X?

The only way i could get my ant version updated on the mac from 1.8.2 to 1.9.1 was by following instructions here

http://wiki.eclipse.org/Ant/User_Guide

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

How to wait till the response comes from the $http request, in angularjs?

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

How do I rotate the Android emulator display?

If you're on a Mac, fn+F11 will rotate the emulator.

But if you're using 4.4, that won't rotate the application orientation. There's a bug

How do I create a copy of an object in PHP?

According to previous comment, if you have another object as a member variable, do following:

class MyClass {
  private $someObject;

  public function __construct() {
    $this->someObject = new SomeClass();
  }

  public function __clone() {
    $this->someObject = clone $this->someObject;
  }

}

Now you can do cloning:

$bar = new MyClass();
$foo = clone $bar;

Android: combining text & image on a Button or ImageButton

There's a much better solution for this problem.

Just take a normal Button and use the drawableLeft and the gravity attributes.

<Button
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:drawableLeft="@drawable/my_btn_icon"
  android:gravity="left|center_vertical" />

This way you get a button which displays a icon in the left side of the button and the text at the right site of the icon vertical centered.

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

Get started with Latex on Linux

yum -y install texlive

was not enough for my centos distro to get the latex command.

This site https://gist.github.com/melvincabatuan/350f86611bc012a5c1c6 contains additional packages. In particular:

yum -y install texlive texlive-latex texlive-xetex

was enough but the author also points out these as well:

yum -y install texlive-collection-latex
yum -y install texlive-collection-latexrecommended
yum -y install texlive-xetex-def
yum -y install texlive-collection-xetex

Only if needed:

yum -y install texlive-collection-latexextra

Check if a row exists, otherwise insert

I assume a single row for each flight? If so:

IF EXISTS (SELECT * FROM Bookings WHERE FLightID = @Id)
BEGIN
    --UPDATE HERE
END
ELSE
BEGIN
   -- INSERT HERE
END

I assume what I said, as your way of doing things can overbook a flight, as it will insert a new row when there are 10 tickets max and you are booking 20.

Inline JavaScript onclick function

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

How to install an APK file on an Android phone?

Directly connect your Android device and select the USB debugging option in the device. Eclipse will itself find your device, and then just run the code.

Or alternatively, paste your APK file in the Android SDK platform-tools folder and from the command prompt install it like this:

D:......../platform-tools> adb install yourfile.apk.

What does HTTP/1.1 302 mean exactly?

302 is a response indicating change of resource location - "Found".

The url where the resource should be now located should be in the response 'Location' header.

The "jump" should be done by the requesting client (make a new request to the resource url in the response Location header field).

Node.js request CERT_HAS_EXPIRED

I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.

After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(

Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.

enter image description here

Android Service needs to run always (Never pause or stop)

Add this in manifest.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

Add a service class.

public class YourServiceName extends Service {


    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}

word-wrap break-word does not work in this example

  • inline-block is of no use in this scenario

SOLUTION

  • word-break: normal|break-all|keep-all|break-word|initial|inherit;
    Simple Answer to your doubt is Use above and make sure white-space: nowrap nowhere used.

NOTE FOR BETTER UNDERSTANDING:

  • word-wrap/overflow-wrap is used to break words that overflow their container

  • word-break property breaks all words at the end of a line, even those that would normally wrap onto another line and wouldn’t overflow their container.

  • word-wrap is the historic and nonstandard property. It has been renamed to overflow-wrap but remains an alias, browsers must support in future. Many browsers (especially the old ones) don’t support overflow-wrap and require word-wrap as a fallback (which is supported by all).

  • If you want to please the W3C you should consider associate both in your CSS. If you don’t, using word-wrap alone is just fine.

How can I submit a form using JavaScript?

You can use the below code to submit the form using JavaScript:

document.getElementById('FormID').submit();

Get a list of all threads currently running in Java

You can get a lot of information about threads from the ThreadMXBean.

Call the static ManagementFactory.getThreadMXBean() method to get a reference to the MBean.

How to check programmatically if an application is installed or not in Android?

Try this

This code is used to check weather your application with package name is installed or not if not then it will open playstore link of your app otherwise your installed app

String your_apppackagename="com.app.testing";
    PackageManager packageManager = getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (applicationInfo == null) {
        // not installed it will open your app directly on playstore
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
    } else {
        // Installed
        Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
        startActivity( LaunchIntent );
    }

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

How to open a new window on form submit

i believe this jquery work for you well please check a code below.

this will make your submit action works and open a link in new tab whether you want to open action url again or a new link

jQuery('form').on('submit',function(e){
setTimeout(function () { window.open('https://www.google.com','_blank');}, 1000);});})

This code works for me perfect..

Calculating average of an array list?

You can use standard looping constructs or iterator/listiterator for the same :

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
double sum = 0;
Iterator<Integer> iter1 = list.iterator();
while (iter1.hasNext()) {
    sum += iter1.next();
}
double average = sum / list.size();
System.out.println("Average = " + average);

If using Java 8, you could use Stream or IntSream operations for the same :

OptionalDouble avg = list.stream().mapToInt(Integer::intValue).average();
System.out.println("Average = " + avg.getAsDouble());

Reference : Calculating average of arraylist

How to run Conda?

If you have just installed MiniConda or Anaconda make sure you re-run your terminal.

From this, I mean close and open your terminal and then try conda list to verify your installation

For me, this worked!!

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

Bash script processing limited number of commands in parallel

In fact, xargs can run commands in parallel for you. There is a special -P max_procs command-line option for that. See man xargs.

How to load data to hive from HDFS without removing the source file?

from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

create external table table_name (
  id int,
  myfields string
)
location '/my/location/in/hdfs';

Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

row format delimited fields terminated by ','

Remove '\' char from string c#

Trim only removes characters at the beginning and the end of the string, that's why your code doesn't quite work. You should use Replace instead:

line.Replace(@"\", string.Empty);

How do I add BundleConfig.cs to my project?

If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html

If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/

How do I apply a diff patch on Windows?

When applying patches using TortoiseSVN, I typically save the path in the root of the checked out repository. You should then be able to right click on the patch, go to the TortoiseSVN menu, and click ApplyPatch. ApplyPatch should automatically figure out which level in the directory hierarchy the patch was created.

I have, however, had issues in the past with applying patches that contain new files, or which involve renames to files. Whatever algorithm Tortoise uses for this doesn't seem to handle those scenarios very well. Unicode can give you similar issues.

How to encode the filename parameter of Content-Disposition header in HTTP?

I know this is an old post but it is still very relevant. I have found that modern browsers support rfc5987, which allows utf-8 encoding, percentage encoded (url-encoded). Then Naïve file.txt becomes:

Content-Disposition: attachment; filename*=UTF-8''Na%C3%AFve%20file.txt

Safari (5) does not support this. Instead you should use the Safari standard of writing the file name directly in your utf-8 encoded header:

Content-Disposition: attachment; filename=Naïve file.txt

IE8 and older don't support it either and you need to use the IE standard of utf-8 encoding, percentage encoded:

Content-Disposition: attachment; filename=Na%C3%AFve%20file.txt

In ASP.Net I use the following code:

string contentDisposition;
if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0"))
    contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);
else if (Request.Browser.Browser == "Safari")
    contentDisposition = "attachment; filename=" + fileName;
else
    contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(fileName);
Response.AddHeader("Content-Disposition", contentDisposition);

I tested the above using IE7, IE8, IE9, Chrome 13, Opera 11, FF5, Safari 5.

Update November 2013:

Here is the code I currently use. I still have to support IE8, so I cannot get rid of the first part. It turns out that browsers on Android use the built in Android download manager and it cannot reliably parse file names in the standard way.

string contentDisposition;
if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0"))
    contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);
else if (Request.UserAgent != null && Request.UserAgent.ToLowerInvariant().Contains("android")) // android built-in download manager (all browsers on android)
    contentDisposition = "attachment; filename=\"" + MakeAndroidSafeFileName(fileName) + "\"";
else
    contentDisposition = "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + Uri.EscapeDataString(fileName);
Response.AddHeader("Content-Disposition", contentDisposition);

The above now tested in IE7-11, Chrome 32, Opera 12, FF25, Safari 6, using this filename for download: ??abcABCæøåÆØÅäöüïëêîâéíáóúýñ½§!#¤%&()=`@£$€{[]}+´¨^~'-_,;.txt

On IE7 it works for some characters but not all. But who cares about IE7 nowadays?

This is the function I use to generate safe file names for Android. Note that I don't know which characters are supported on Android but that I have tested that these work for sure:

private static readonly Dictionary<char, char> AndroidAllowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._-+,@£$€!½§~'=()[]{}0123456789".ToDictionary(c => c);
private string MakeAndroidSafeFileName(string fileName)
{
    char[] newFileName = fileName.ToCharArray();
    for (int i = 0; i < newFileName.Length; i++)
    {
        if (!AndroidAllowedChars.ContainsKey(newFileName[i]))
            newFileName[i] = '_';
    }
    return new string(newFileName);
}

@TomZ: I tested in IE7 and IE8 and it turned out that I did not need to escape apostrophe ('). Do you have an example where it fails?

@Dave Van den Eynde: Combining the two file names on one line as according to RFC6266 works except for Android and IE7+8 and I have updated the code to reflect this. Thank you for the suggestion.

@Thilo: No idea about GoodReader or any other non-browser. You might have some luck using the Android approach.

@Alex Zhukovskiy: I don't know why but as discussed on Connect it doesn't seem to work terribly well.

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

Setting public class variables

Add getter and setter method to your class.

public function setValue($new_value)
{
    $this->testvar = $new_value;
}

public function getValue()
{
    return $this->testvar;        
}

How to give Jenkins more heap space when it´s started as a service under Windows?

From the Jenkins wiki:

The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.

The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.

https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service

How to check if variable is array?... or something array-like

<?php
$var = new ArrayIterator();

var_dump(is_array($var), ($var instanceof ArrayIterator));

returns bool(false) or bool(true)

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

Xcopy exit code 4 means "Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line."

It looks like Visual Studio is supplying invalid arguments to xcopy. Check your post-build event command via Project > Right Click > Properties > Build Events > Post Build Event.

Note that if the $(ProjectDir) or similar macro terms have spaces in the resulting paths when expanded, then they will need to be wrapped in double quotes. For example:

xcopy "$(ProjectDir)Library\dsoframer.ocx" "$(TargetDir)" /Y /E /D1

How to escape a single quote inside awk

awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'

How do I get a div to float to the bottom of its container?

Put the div in another div and set the parent div's style to position:relative; Then on the child div set the following CSS properties: position:absolute; bottom:0;

Is there a replacement for unistd.h for Windows (Visual C)?

Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as neeeded.
 * https://stackoverflow.com/a/826027/1202830
 */

#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */

#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t; 
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */

how to get selected row value in the KendoUI

There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...

change: function (e) {
   var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

NLS_NUMERIC_CHARACTERS setting for decimal

You can see your current session settings by querying nls_session_parameters:

select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';

VALUE                                  
----------------------------------------
.,                                       

That may differ from the database defaults, which you can see in nls_database_parameters.

In this session your query errors:

select to_number('100,12') from dual;

Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"

I could alter my session, either directly with alter session or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):

alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;

TO_NUMBER('100,12')
-------------------
             100,12 

In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.

But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number(); though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:

alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;

TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
                                                        100.12 

By default the result is still displayed with my session settings, so the decimal separator is still a period.

creating a table in ionic

css

.table:nth-child(2n+1) {
    background-color: whatever color !important;
  }

html

    <ion-row class="nameClass" justify-content-center align-items-center style='height: 100%'>

   <ion-col>
            <div>
                <strong>name</strong>
            </div>
        </ion-col>
        <ion-col>
            <div>
                <strong>name</strong>
            </div>
        </ion-col>
        <ion-col>
            <div>
                <strong>name</strong>
            </div>
        </ion-col>
        <ion-col>
            <div>
                <strong>name</strong>
            </div>
        </ion-col>
        <ion-col>
            <div text-center>
                <strong>name</strong>
            </div>
        </ion-col>
    </ion-row>

row 2

        <ion-col >
            <div>
            name
            </div>

        </ion-col>
        <ion-col >
            <div>
            name
            </div>

        </ion-col>
        <ion-col >
            <div>
               name
            </div>

        </ion-col>
        <ion-col>
            <div>
               name
            </div>

        </ion-col>
        <ion-col>
            <div>
                <button>name</button>
            </div>

        </ion-col>

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

Cocoa Touch: How To Change UIView's Border Color And Thickness?

I wouldn't suggest overriding the drawRect due to causing a performance hit.

Instead, I would modify the properties of the class like below (in your custom uiview):

  - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
      self.layer.borderWidth = 2.f;
      self.layer.borderColor = [UIColor redColor].CGColor;
    }
  return self;

I didn't see any glitches when taking above approach - not sure why putting in the initWithFrame stops these ;-)

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

As written in How to pop fragment off backstack and by LarsH here, we can pop several fragments from top down to specifical tag (together with the tagged fragment) using this method:

fragmentManager?.popBackStack ("frag", FragmentManager.POP_BACK_STACK_INCLUSIVE);

Substitute "frag" with your fragment's tag. Remember that first we should add the fragment to backstack with:

fragmentTransaction.addToBackStack("frag")

If we add fragments with addToBackStack(null), we won't pop fragments that way.

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

Google Maps V3 - How to calculate the zoom level for a given bounds

Work example to find average default center with react-google-maps on ES6:

const bounds = new google.maps.LatLngBounds();
paths.map((latLng) => bounds.extend(new google.maps.LatLng(latLng)));
const defaultCenter = bounds.getCenter();
<GoogleMap
 defaultZoom={paths.length ? 12 : 4}
 defaultCenter={defaultCenter}
>
 <Marker position={{ lat, lng }} />
</GoogleMap>

How to add hours to current date in SQL Server?

Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp

Select DateAdd(Hour, 10 , JoiningDate )
from emp


Select dateadd (hour , 10 , getdate()), getdate()

Select dateadd (hour , 10 , joiningDate)
from Emp


Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate 
From EMP

Retrieving the last record in each group - MySQL

If you want the last row for each Name, then you can give a row number to each row group by the Name and order by Id in descending order.

QUERY

SELECT t1.Id, 
       t1.Name, 
       t1.Other_Columns
FROM 
(
     SELECT Id, 
            Name, 
            Other_Columns,
    (
        CASE Name WHEN @curA 
        THEN @curRow := @curRow + 1 
        ELSE @curRow := 1 AND @curA := Name END 
    ) + 1 AS rn 
    FROM messages t, 
    (SELECT @curRow := 0, @curA := '') r 
    ORDER BY Name,Id DESC 
)t1
WHERE t1.rn = 1
ORDER BY t1.Id;

SQL Fiddle

Reverse engineering from an APK file to a project

Yes, you can get your project back. Just rename the yourproject.apk file to yourproject.zip, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex file and decompile it by following way.

First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.

Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.

How to initialize all members of an array to the same value?

If the array happens to be int or anything with the size of int or your mem-pattern's size fits exact times into an int (i.e. all zeroes or 0xA5A5A5A5), the best way is to use memset().

Otherwise call memcpy() in a loop moving the index.

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How to set locale in DatePipe in Angular 2?

With angular5 the above answer no longer works!

The following code:

app.module.ts

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

Leads to following error:

Error: Missing locale data for the locale "de-at".

With angular5 you have to load and register the used locale file on your own.

app.module.ts

import { NgModule, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDeAt from '@angular/common/locales/de-at';

registerLocaleData(localeDeAt);

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

Documentation

How to simulate a mouse click using JavaScript?

From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.

List all tables in postgresql information_schema

\dt information_schema.

from within psql, should be fine.

How to get memory available or used in C#

System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.

If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

For those of you who are popping up a new window to print from, and then automatically closing it after the user clicks "Print" or "Cancel" on the Chrome print preview, I used the following (thanks to the help from PaulVB's answer):

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    var showPopup = false;
    window.onbeforeunload = function () {
        if (showPopup) {
            return 'You must use the Cancel button to close the Print Preview window.\n';
        } else {
            showPopup = true;
        }
    }
    window.print();
    window.close();
} else {
    window.print();
    window.close();
}

I am debating if it would be a good idea to also filter by the version of Chrome...

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

For Rect-Native developers. I encounter this error while renderingItem in FlatList. I had two Text components. I was using them like below

renderItem = { ({item}) => 
     <Text style = {styles.item}>{item.key}</Text>
     <Text style = {styles.item}>{item.user}</Text>
}

But after I put these tow Inside View Components it worked for me.

renderItem = { ({item}) => 
   <View style={styles.flatview}>
      <Text style = {styles.item}>{item.key}</Text>
      <Text style = {styles.item}>{item.user}</Text>
   </View>
 }

You might be using other components but putting them into View may be worked for you.

How to connect a Windows Mobile PDA to Windows 10

Here is the answer: Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182

Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!

The best way to remove duplicate values from NSMutableArray in Objective-C?

Using Orderedset will do the trick. This will keep the remove duplicates from the array and maintain order which sets normally doesn't do

Error TF30063: You are not authorized to access ... \DefaultCollection

What isn't officially an answer here, but worked for me (the other answers didn't help): Click Team Explorer tab -> Connect hyperlink - connect\choose repository. And it works.

Why does cURL return error "(23) Failed writing body"?

Another possibility, if using the -o (output file) option - the destination directory does not exist.

eg. if you have -o /tmp/download/abc.txt and /tmp/download does not exist.

Hence, ensure any required directories are created/exist beforehand, use the --create-dirs option as well as -o if necessary

Any easy way to use icons from resources?

After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension

For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:

NotifyIcon1.Icon = My.Resources.Logo_square

Can I automatically increment the file build version when using Visual Studio?

Go to Project | Properties and then Assembly Information and then Assembly Version and put an * in the last or the second-to-last box (you can't auto-increment the Major or Minor components).

Adding an onclick function to go to url in JavaScript?

Simply use this

onclick="location.href='pageurl.html';"

jQuery if div contains this text, replace that part of the text

Very simple just use this code, it will preserve the HTML, while removing unwrapped text only:

jQuery(function($){

    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

How to make a WPF window be on top of all other windows of my app (not system wide)?

You can add this to your windows tags

WindowStartupLocation="CenterScreen"

Then you can also display it if you want your users to acknowledge it in order to proceed

YourWindow.ShowDialog();

First try it without TopMost parameters and see the results.

How to change the URI (URL) for a remote Git repository?

Change Host for a Git Origin Server

from: http://pseudofish.com/blog/2010/06/28/change-host-for-a-git-origin-server/

Hopefully this isn’t something you need to do. The server that I’ve been using to collaborate on a few git projects with had the domain name expire. This meant finding a way of migrating the local repositories to get back in sync.

Update: Thanks to @mawolf for pointing out there is an easy way with recent git versions (post Feb, 2010):

git remote set-url origin ssh://newhost.com/usr/local/gitroot/myproject.git

See the man page for details.

If you’re on an older version, then try this:

As a caveat, this works only as it is the same server, just with different names.

Assuming that the new hostname is newhost.com, and the old one was oldhost.com, the change is quite simple.

Edit the .git/config file in your working directory. You should see something like:

[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ssh://oldhost.com/usr/local/gitroot/myproject.git

Change oldhost.com to newhost.com, save the file and you’re done.

From my limited testing (git pull origin; git push origin; gitx) everything seems in order. And yes, I know it is bad form to mess with git internals.

How to get unique values in an array

Or for those looking for a one-liner (simple and functional), compatible with current browsers:

_x000D_
_x000D_
let a = ["1", "1", "2", "3", "3", "1"];_x000D_
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);_x000D_
console.log(unique);
_x000D_
_x000D_
_x000D_

Update 18-04-2017

It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)

Update 29-07-2015:

There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.

Usage:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser support, source from mozilla):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n = 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

Remove tracking branches no longer on remote

I use this method so I can have more control.

git branch -D $(git branch | grep -v "master" | grep -v "develop")

This is remove any branches not named: master or develop.

Cannot find Microsoft.Office.Interop Visual Studio

I forgot to select Microsoft Office Developer Tools for installation initially. In my case Visual Studio Professional 2013 and also 2015.

enter image description here

How to use LINQ to select object with minimum or maximum property value

A way via extension function on IEnumerable that returns both the object and the minimum found. It takes a Func that can do any operation on the object in the collection:

public static (double min, T obj) tMin<T>(this IEnumerable<T> ienum, 
            Func<T, double> aFunc)
        {
            var okNull = default(T);
            if (okNull != null)
                throw new ApplicationException("object passed to Min not nullable");

            (double aMin, T okObj) best = (double.MaxValue, okNull);
            foreach (T obj in ienum)
            {
                double q = aFunc(obj);
                if (q < best.aMin)
                    best = (q, obj);
            }
            return (best);
        }

Example where object is an Airport and we want to find closest Airport to a given (latitude, longitude). Airport has a dist(lat, lon) function.

(double okDist, Airport best) greatestPort = airPorts.tMin(x => x.dist(okLat, okLon));

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

Create zip file and ignore directory structure

Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip my.zip will give a folder containing all your files:

parent-directory
+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

file1
file2
dir1
+-- file3
+-- file4

Import SQL file by command line in Windows 7

I use mysql -u root -ppassword databasename < filename.sql in batch process. For an individual file, I like to use source more because it shows the progress and any errors like

Query OK, 6717 rows affected (0.18 sec)
Records: 6717  Duplicates: 0  Warnings: 0
  1. Log in to MySQL using mysql -u root -ppassword
  2. In MySQL, change the database you want to import in: mysql>use databasename;

    • This is very important otherwise it will import to the default database
  3. Import the SQL file using source command: mysql>source path\to\the\file\filename.sql;

Can Console.Clear be used to only clear a line instead of whole console?

I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}

Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

Compiling C++11 with g++

You can check your g++ by command:

which g++
g++ --version

this will tell you which complier is currently it is pointing.

To switch to g++ 4.7 (assuming that you have installed it in your machine),run:

sudo update-alternatives --config gcc

There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path              Priority   Status
------------------------------------------------------------
  0            /usr/bin/gcc-4.6   60        auto mode
  1            /usr/bin/gcc-4.6   60        manual mode
* 2            /usr/bin/gcc-4.7   40        manual mode

Then select 2 as selection(My machine already pointing to g++ 4.7,so the *)

Once you switch the complier then again run g++ --version to check the switching has happened correctly.

Now compile your program with

g++ -std=c++11 your_file.cpp -o main

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

Difference between a Seq and a List in Scala

In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :

sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...

[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

System.exit(0) by convention, a zero status code indicates successful termination.

System.exit(1) -It means termination unsuccessful due to some error

How to remove all null elements from a ArrayList or String Array?

List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);

cmake - find_library - custom library location

You have one extra level of nesting. CMAKE will search under $CMAKE_PREFIX_PATH/include for headers and $CMAKE_PREFIX_PATH/libs for libraries.

From CMAKE documentation:

For each path in the CMAKE_PREFIX_PATH list, CMake will check "PATH/include" and "PATH" when FIND_PATH() is called, "PATH/bin" and "PATH" when FIND_PROGRAM() is called, and "PATH/lib and "PATH" when FIND_LIBRARY() is called.

How do I redirect to another webpage?

Should just be able to set using window.location.

Example:

window.location = "https://stackoverflow.com/";

Here is a past post on the subject: How do I redirect to another webpage?

How to access the php.ini from my CPanel?

In cPanel search for php, You will find "Select PHP version" under Software.

Software -> Select PHP Version -> Switch to Php Options -> Change Value -> save.

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

You can activate the proper header in PHP with this:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

HTML5 Form Input Pattern Currency Format

If you want to allow a comma delimiter which will pass the following test cases:

0,00  => true
0.00  => true
01,00 => true
01.00 => true
0.000 => false
0-01  => false

then use this:

^\d+(\.|\,)\d{2}$

Jquery UI datepicker. Disable array of Dates

$('input').datepicker({
   beforeShowDay: function(date){
       var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
       return [ array.indexOf(string) == -1 ]
   }
});

Node Version Manager (NVM) on Windows

As an node manager alternative you can use Volta from LinkedIn.

Editing hosts file to redirect url?

You could use the RedirectMatch directive in Apache to do something similar you want.

It's pretty simple.

RedirectMatch / http://222.222.222.222/

Anyway, I can't see any reason to do that thing. Aren't you trying to intercept traffic? There are better ways. For Linux boxes as a router: iptables -j REDIRECT + Squid or Apache. For Cisco routers, you can use WCCP to a Cache or Web Server...

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

<input onkeyup="this.setAttribute('value', this.value);" />

and

input[value=""]

will work :-)

edit: http://jsfiddle.net/XwZR2/

'invalid value encountered in double_scalars' warning, possibly numpy

Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.

Closing database connections in Java

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.

Actually, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them. Something like this:

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* Ignored */}
    }
}

The finally block can be slightly improved into (to avoid the null check):

} finally {
    try { rs.close(); } catch (Exception e) { /* Ignored */ }
    try { ps.close(); } catch (Exception e) { /* Ignored */ }
    try { conn.close(); } catch (Exception e) { /* Ignored */ }
}

But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like this:

} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(ps);
    DbUtils.closeQuietly(conn);
}

And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that, so there isn't any need to write your own.

fetch gives an empty response body

fetch("http://localhost:8988/api", {
        //mode: "no-cors",
        method: "GET",
        headers: {
            "Accept": "application/json"
        }
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        return data;
    })
    .catch(error => {
        return error;
    });

This works for me.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Pythonic way to check if a list is sorted or not

Just to add another way (even if it requires an additional module): iteration_utilities.all_monotone:

>>> from iteration_utilities import all_monotone
>>> listtimestamps = [1, 2, 3, 5, 6, 7]
>>> all_monotone(listtimestamps)
True

>>> all_monotone([1,2,1])
False

To check for DESC order:

>>> all_monotone(listtimestamps, decreasing=True)
False

>>> all_monotone([3,2,1], decreasing=True)
True

There is also a strict parameter if you need to check for strictly (if successive elements should not be equal) monotonic sequences.

It's not a problem in your case but if your sequences contains nan values then some methods will fail, for example with sorted:

def is_sorted_using_sorted(iterable):
    return sorted(iterable) == iterable

>>> is_sorted_using_sorted([3, float('nan'), 1])  # definetly False, right?
True

>>> all_monotone([3, float('nan'), 1])
False

Note that iteration_utilities.all_monotone performs faster compared to the other solutions mentioned here especially for unsorted inputs (see benchmark).

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Set the value of a variable with the result of a command in a Windows batch file

Here are two approaches:

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%

::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%


::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

How to get featured image of a product in woocommerce

I got the solution . I tried this .

<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' );?>

    <img src="<?php  echo $image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">

MongoDB what are the default user and password?

In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth switch). In order to do that, you need to have localhost access to the server and then run:

mongo
use admin
db.createUser(
 {
     user: "user_name",
     pwd: "user_pass",
     roles: [
           { role: "userAdminAnyDatabase", db: "admin" },
           { role: "readWriteAnyDatabase", db: "admin" },
           { role: "dbAdminAnyDatabase", db: "admin" }
        ]
 })

As stated in MongoDB documentation:

The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.

Here is the link to that section of the docs.

Always pass weak reference of self into block in ARC?

As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog in your operation's dealloc method and confirm that's getting called.

You said:

I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit

The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self, or even just references an instance variable of self, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation subclass is released.

For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.

If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation is getting deallocated). A common example is the use of a repeating NSTimer. Or some custom delegate or other object that is erroneously maintaining a strong reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:

record reference counts in Xcode 6

Or in Xcode 5:

record reference counts in Xcode 5

Adding the "Clear" Button to an iPhone UITextField

Swift 4 (adapted from Kristopher Johnson's answer)

textfield.clearButtonMode = .always

textfield.clearButtonMode = .whileEditing

textfield.clearButtonMode = .unlessEditing

textfield.clearButtonMode = .never

How to add constraints programmatically using Swift

If you want to fill your super view then I suggest the swifty way:

    view.translatesAutoresizingMaskIntoConstraints = false
    let attributes: [NSLayoutAttribute] = [.top, .bottom, .right, .left]
    NSLayoutConstraint.activate(attributes.map {
        NSLayoutConstraint(item: view, attribute: $0, relatedBy: .equal, toItem: view.superview, attribute: $0, multiplier: 1, constant: 0)
    })

Other wise if you need non equal constraints check out NSLayoutAnchor as of iOS 9. Its often much easier to read that using NSLayoutConstraint directly:

    view.translatesAutoresizingMaskIntoConstraints = false
    view.topAnchor.constraint(equalTo: view.superview!.topAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: view.superview!.bottomAnchor).isActive = true
    view.leadingAnchor.constraint(equalTo: view.superview!.leadingAnchor, constant: 10).isActive = true
    view.trailingAnchor.constraint(equalTo: view.superview!.trailingAnchor, constant: 10).isActive = true

Identify duplicates in a List

How about this code -

public static void main(String[] args) {

    //Lets say we have a elements in array
    int[] a = {13,65,13,67,88,65,88,23,65,88,92};

    List<Integer> ls1 = new ArrayList<>();
    List<Integer> ls2 = new ArrayList<>();
    Set<Integer> ls3 = new TreeSet<>();

    //Adding each element of the array in the list      
    for(int i=0;i<a.length;i++) {
     {
    ls1.add(a[i]);
    }
    }

    //Iterating each element in the arrary
    for (Integer eachInt : ls1) {

    //If the list2 contains the iterating element, then add that into set<> (as this would be a duplicate element)
        if(ls2.contains(eachInt)) {
            ls3.add(eachInt);
        }
        else {ls2.add(eachInt);}

    }

    System.out.println("Elements in array or ls1"+ls1); 
    System.out.println("Duplicate Elements in Set ls3"+ls3);


}

How to get UTC+0 date in Java 8?

In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone

manage.py runserver

You can run it for machines in your network by

./manage.py runserver 0.0.0.0:8000

And than you will be able to reach you server from any machine in your network. Just type on other machine in browser http://192.168.0.1:8000 where 192.168.0.1 is IP of you server... and it ready to go....

or in you case:

  1. On machine A in command line ./manage.py runserver 0.0.0.0:8000
  2. Than try in machine B in browser type http://A:8000
  3. Make a sip of beer.

Source from django docs

Align the form to the center in Bootstrap 4

<div class="d-flex justify-content-center align-items-center container ">

    <div class="row ">


        <form action="">
            <div class="form-group">
                <label for="inputUserName" class="control-label">Enter UserName</label>
                <input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
                <small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
            </div>
            <div class="form-group">
                <label for="inputPassword" class="control-label">Enter Password</label>
                <input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">

            </div>
        </form>

    </div>

</div>

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Adding a virtual device with the lowest possible Android version that was acceptable in my case worked for me. (Before that I'd tried several recent Android versions and had been getting the Missing emulator engine program for 'x86_64' CPUS error.)

100% width Twitter Bootstrap 3 template

Using Bootstrap 3.3.5 and .container-fluid, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid was re-introduced in 3.1.

Full width on mobile/tablet, 1/4 screen on desktop

<div class="container-fluid"> <!-- Adds 15px left/right padding --> 
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
      <!-- Full-width for mobile -->
      <!-- 1/4 screen width for desktop -->
    </div>
  </div>
</div>

Full width on all resolutions (mobile, table, desktop)

<div class="container-fluid"> <!-- Adds 15px left/right padding -->
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div>
      <!-- Full-width content -->
    </div>
  </div>
</div>

Java 8, Streams to find the duplicate elements

You can use Collections.frequency:

numbers.stream().filter(i -> Collections.frequency(numbers, i) >1)
                .collect(Collectors.toSet()).forEach(System.out::println);

Refresh an asp.net page on button click

_x000D_
_x000D_
  XmlDocument doc = new XmlDocument();_x000D_
            doc.Load(@"F:\dji\A18rad\A18rad\XMLFile1.xml");_x000D_
            List<vreme> vreme = new List<vreme>();_x000D_
            string grad = Request.Form["grad"];_x000D_
_x000D_
            foreach (XmlNode cvor in doc.SelectNodes("/vreme/Prognoza"))_x000D_
            {_x000D_
                if (grad == cvor["NazivMesta"].InnerText)_x000D_
                    vreme.Add(new vreme_x000D_
                    {_x000D_
                        mesto = cvor["NazivMesta"].InnerText,_x000D_
                        maxtemp = cvor["MaxTemperatura"].InnerText,_x000D_
                        mintemp = cvor["MinTemperatura"].InnerText,_x000D_
                        vremee = cvor["Vreme"].InnerText_x000D_
                    });_x000D_
            }_x000D_
            return View(vreme);_x000D_
        }_x000D_
        public ActionResult maxtemperature()_x000D_
        {_x000D_
            XmlDocument doc = new XmlDocument();_x000D_
            doc.Load(@"F:\dji\A18rad\A18rad\XMLFile1.xml");_x000D_
            List<vreme> vreme = new List<vreme>();_x000D_
_x000D_
            foreach (XmlNode cvor in doc.SelectNodes("/vreme/Prognoza"))_x000D_
            {_x000D_
                vreme.Add(new vreme_x000D_
                {_x000D_
                    mesto = cvor["NazivMesta"].InnerText,_x000D_
                    maxtemp = cvor["MaxTemperatura"].InnerText_x000D_
                });_x000D_
            }_x000D_
            return View(vreme);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
@*@{_x000D_
    ViewBag.Title = "maxtemperature";_x000D_
}_x000D_
@Html.ActionLink("Vreme Po izboru","index","home")_x000D_
<h2>maxtemperature</h2>_x000D_
<table border="10">_x000D_
    <tr><th>Mesto</th>_x000D_
        <th>MaxTemp</th>_x000D_
    </tr>_x000D_
@foreach (A18rad.Models.vreme vr in Model)_x000D_
{_x000D_
    <tr>_x000D_
        <td>@vr.mesto</td>_x000D_
        <td>@vr.maxtemp</td>_x000D_
    </tr>_x000D_
}_x000D_
    </table>*@_x000D_
@*@{_x000D_
    ViewBag.Title = "Index";_x000D_
}_x000D_
@Html.ActionLink("MaxTemperature","maxtemperature","home")_x000D_
@using(Html.BeginForm("Index","Home")){_x000D_
<h2>Index</h2>_x000D_
_x000D_
_x000D_
    <span>Grad:</span><select name="grad">_x000D_
        <option  value="Nis">Nis</option>_x000D_
        <option value="Beograd">Beograd</option>_x000D_
        <option value="Kopaonik">Kopaonik</option>_x000D_
    </select>_x000D_
    <input type="submit" value="Moze" /><br />_x000D_
    foreach (A18rad.Models.vreme vr in Model)_x000D_
    {_x000D_
     <span>Min temperatura:</span>  @vr.mintemp<br />_x000D_
       <span>Max temperatura:</span> @vr.maxtemp<br />_x000D_
        if(vr.vremee =="Kisa"){_x000D_
      <span>Vreme:</span>  <img src ="kisa.jpg" />_x000D_
        }_x000D_
        else if(vr.vremee =="Sneg"){_x000D_
           <img src="sneg.jpg" />_x000D_
       } else if (vr.vremee == "Vedro") { _x000D_
       _x000D_
        <img src ="vedro.png" /><br />_x000D_
       }_x000D_
}_x000D_
    _x000D_
   _x000D_
        _x000D_
        _x000D_
}*@
_x000D_
_x000D_
_x000D_

How to perform a sum of an int[] array

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:

int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
    sum += numbers[i];
}
System.out.println("The sum is: " + sum);

babel-loader jsx SyntaxError: Unexpected token

This works perfect for me

{
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015','react']
    }
},

How to force Sequential Javascript Execution?

I had the same problem, this is my solution:

_x000D_
_x000D_
var functionsToCall = new Array();_x000D_
_x000D_
function f1() {_x000D_
    $.ajax({_x000D_
        type:"POST",_x000D_
        url: "/some/url",_x000D_
        success: function(data) {_x000D_
            doSomethingWith(data);_x000D_
            //When done, call the next function.._x000D_
            callAFunction("parameter");_x000D_
        }_x000D_
    });_x000D_
}_x000D_
_x000D_
function f2() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter2");_x000D_
}_x000D_
function f3() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter3");_x000D_
}_x000D_
function f4() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter4");_x000D_
}_x000D_
function f5() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter5");_x000D_
}_x000D_
function f6() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter6");_x000D_
}_x000D_
function f7() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter7");_x000D_
}_x000D_
function f8() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter8");_x000D_
}_x000D_
function f9() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter9");_x000D_
}_x000D_
    _x000D_
function callAllFunctionsSy(params) {_x000D_
 functionsToCall.push(f1);_x000D_
 functionsToCall.push(f2);_x000D_
 functionsToCall.push(f3);_x000D_
 functionsToCall.push(f4);_x000D_
 functionsToCall.push(f5);_x000D_
 functionsToCall.push(f6);_x000D_
 functionsToCall.push(f7);_x000D_
 functionsToCall.push(f8);_x000D_
 functionsToCall.push(f9);_x000D_
 functionsToCall.reverse();_x000D_
 callAFunction(params);_x000D_
}_x000D_
_x000D_
function callAFunction(params) {_x000D_
 if (functionsToCall.length > 0) {_x000D_
  var f=functionsToCall.pop();_x000D_
  f(params);_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.