Programs & Examples On #Saxon

Saxon is an implementation of XSLT, XQuery, XPath, and XSD. In supports the latest W3C standards including XSLT 3.0, XQuery 3.1, XPath 3.1, and XSD 1.1. There are versions for Java, .NET, and C, in both open source and commercial editions. The latest addition to the product set is Saxon-JS, an XSLT runtime which will run in most browsers.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I was facing the same problem called "Content is not allowed in prolog" in my xml file.

Solution

Initially my root folder was '#Filename'.

When i removed the first character '#' ,the error got resolved.

No need of removing the #filename... Try in this way..

Instead of passing a File or URL object to the unmarshaller method, use a FileInputStream.

File myFile = new File("........");
Object obj = unmarshaller.unmarshal(new FileInputStream(myFile));

How to force a line break in a long word in a DIV?

just try this in our style

white-space: normal;

ALTER TABLE DROP COLUMN failed because one or more objects access this column

When you alter column datatype you need to change constraint key for every database

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

how to draw smooth curve through N points using javascript HTML5 canvas?

To add to K3N's cardinal splines method and perhaps address T. J. Crowder's concerns about curves 'dipping' in misleading places, I inserted the following code in the getCurvePoints() function, just before res.push(x);

if ((y < _pts[i+1] && y < _pts[i+3]) || (y > _pts[i+1] && y > _pts[i+3])) {
    y = (_pts[i+1] + _pts[i+3]) / 2;
}
if ((x < _pts[i] && x < _pts[i+2]) || (x > _pts[i] && x > _pts[i+2])) {
    x = (_pts[i] + _pts[i+2]) / 2;
}

This effectively creates a (invisible) bounding box between each pair of successive points and ensures the curve stays within this bounding box - ie. if a point on the curve is above/below/left/right of both points, it alters its position to be within the box. Here the midpoint is used, but this could be improved upon, perhaps using linear interpolation.

How can I merge properties of two JavaScript objects dynamically?

This merges obj into a "default" def. obj has precedence for anything that exists in both, since obj is copied into def. Note also that this is recursive.

function mergeObjs(def, obj) {
    if (typeof obj == 'undefined') {
        return def;
    } else if (typeof def == 'undefined') {
        return obj;
    }
    for (var i in obj) {
        if (obj[i] != null && obj[i].constructor == Object) {
            def[i] = mergeObjs(def[i], obj[i]);
        } else {
            def[i] = obj[i];
        }
    }
    return def;
}

a = {x : {y : [123]}}
b = {x : {z : 123}}
console.log(mergeObjs(a, b));
// {x: {y : [123], z : 123}}

"E: Unable to locate package python-pip" on Ubuntu 18.04

ls /bin/python*

Identify the highest version of python listed. If the highest version is something like python2.7 then install python2-pip If its something like python3.8 then install python3-pip

Example for python3.8:

sudo apt-get install python3-pip

How to insert close button in popover for Bootstrap

I found other answers were either not generic enough, or too complicated. Here is a simple one that should always work (for bootstrap 3):

$('[data-toggle="popover"]').each(function () {
    var button = $(this);
    button.popover().on('shown.bs.popover', function() {
        button.data('bs.popover').tip().find('[data-dismiss="popover"]').on('click', function () {
            button.popover('toggle');
        });
    });
});

Then just add attribute data-dismiss="popover" in your close button. Also make sure not to use popover('hide') elsewhere in your code as it hides the popup but doesn't properly sets its internal state in bootstrap code, which will cause issues next time you use popover('toggle').

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I had the same problem, turned out after I have updated my schema, I have forgotten I was calling the model using the old id, which was created by me; I have updated my schema from something like:

patientid: {
           type: String,
            required: true,
            unique: true
          }, 

to

patientid: { type: mongoose.SchemaTypes.ObjectId, ref: "Patient" },

It turned out, since my code is big, I was calling the findOne with the old id, therefore, the problem.

I am posting here just to help somebody else: please, check your code for unknown wrong calls! it may be the problem, and it can save your huge headacles!

After MySQL install via Brew, I get the error - The server quit without updating PID file

I’ve got a similar problem with MySQL on a Mac (Mac Os X Could not startup MySQL Server. Reason: 255 and also “ERROR! The server quit without updating PID file”). After a long trial and error process, finally in order to restore the file permissions, I’ve just do that:

launch the Disk Utilities.app
choose my drive on the left panel
click on the “Repair disk permissions” button

This did the trick for me. Hoping this can help someone else.

Getting rid of all the rounded corners in Twitter Bootstrap

if you are using bootstrap you can just use the bootstrap class="rounded-0" to make the border with the sharp edges with no rounded corners <button class="btn btn-info rounded-0"">Generate</button></span>

Plot multiple columns on the same graph in R

Using tidyverse

df %>% tidyr::gather("id", "value", 1:4) %>% 
  ggplot(., aes(Xax, value))+
  geom_point()+
  geom_smooth(method = "lm", se=FALSE, color="black")+
  facet_wrap(~id)

DATA

df<- read.table(text =c("
A       B       C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23"), header = T)

Convert RGB values to Integer

To get individual colour values you can use Color like following for pixel(x,y).

import java.awt.Color;
import java.awt.image.BufferedImage;

Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();

The above will give you the integer values of Red, Green and Blue in range of 0 to 255.

To set the values from RGB you can do so by:

Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();

//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);

Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How to copy Java Collections list

b has a capacity of 3, but a size of 0. The fact that ArrayList has some sort of buffer capacity is an implementation detail - it's not part of the List interface, so Collections.copy(List, List) doesn't use it. It would be ugly for it to special-case ArrayList.

As MrWiggles has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.

For more complicated scenarios (which may well include your real code), you may find the collections within Guava useful.

How can I output UTF-8 from Perl?

You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL but also PERL5OPT=-Mutf8.

How can I append a query parameter to an existing URL?

I suggest an improvement of the Adam's answer accepting HashMap as parameter

/**
 * Append parameters to given url
 * @param url
 * @param parameters
 * @return new String url with given parameters
 * @throws URISyntaxException
 */
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
    URI uri = new URI(url);
    String query = uri.getQuery();

    StringBuilder builder = new StringBuilder();

    if (query != null)
        builder.append(query);

    for (Map.Entry<String, String> entry: parameters.entrySet())
    {
        String keyValueParam = entry.getKey() + "=" + entry.getValue();
        if (!builder.toString().isEmpty())
            builder.append("&");

        builder.append(keyValueParam);
    }

    URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
    return newUri.toString();
}

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

How to redirect output to a file and stdout

You can do that for your entire script by using something like that at the beginning of your script :

#!/usr/bin/env bash

test x$1 = x$'\x00' && shift || { set -o pipefail ; ( exec 2>&1 ; $0 $'\x00' "$@" ) | tee mylogfile ; exit $? ; }

# do whaetever you want

This redirect both stderr and stdout outputs to the file called mylogfile and let everything goes to stdout at the same time.

It is used some stupid tricks :

  • use exec without command to setup redirections,
  • use tee to duplicates outputs,
  • restart the script with the wanted redirections,
  • use a special first parameter (a simple NUL character specified by the $'string' special bash notation) to specify that the script is restarted (no equivalent parameter may be used by your original work),
  • try to preserve the original exit status when restarting the script using the pipefail option.

Ugly but useful for me in certain situations.

Execute bash script from URL

source <(curl -s http://mywebsite.com/myscript.txt)

ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash takes a filename to execute just fine without redirection, and <(command) syntax provides a path.

bash <(curl -s http://mywebsite.com/myscript.txt)

It may be clearer if you look at the output of echo <(cat /dev/null)

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

        const arr = ['1', '2', '3'];

         // Old way
        const cloneArr = arr.slice();

        // ES6 way
        const cloneArrES6 = [...arr];

// But problem with 3rd approach is that if you are using muti-dimensional 
 // array, then only first level is copied

        const nums = [
              [1, 2], 
              [10],
         ];

        const cloneNums = [...nums];

// Let's change the first item in the first nested item in our cloned array.

        cloneNums[0][0] = '8';

        console.log(cloneNums);
           // [ [ '8', 2 ], [ 10 ], [ 300 ] ]

        // NOOooo, the original is also affected
        console.log(nums);
          // [ [ '8', 2 ], [ 10 ], [ 300 ] ]

So, in order to avoid these scenarios to happen, use

        const arr = ['1', '2', '3'];

        const cloneArr = Array.from(arr);

Any difference between await Promise.all() and multiple await?

Note:

This answer just covers the timing differences between await in series and Promise.all. Be sure to read @mikep's comprehensive answer that also covers the more important differences in error handling.


For the purposes of this answer I will be using some example methods:

  • res(ms) is a function that takes an integer of milliseconds and returns a promise that resolves after that many milliseconds.
  • rej(ms) is a function that takes an integer of milliseconds and returns a promise that rejects after that many milliseconds.

Calling res starts the timer. Using Promise.all to wait for a handful of delays will resolve after all the delays have finished, but remember they execute at the same time:

Example #1
const data = await Promise.all([res(3000), res(2000), res(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========O                     delay 3
//
// =============================O Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }

  const data = await Promise.all([res(3000), res(2000), res(1000)])
  console.log(`Promise.all finished`, Date.now() - start)
}

example()
_x000D_
_x000D_
_x000D_

This means that Promise.all will resolve with the data from the inner promises after 3 seconds.

But, Promise.all has a "fail fast" behavior:

Example #2
const data = await Promise.all([res(3000), res(2000), rej(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =========X                     Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const data = await Promise.all([res(3000), res(2000), rej(1000)])
  } catch (error) {
    console.log(`Promise.all finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

If you use async-await instead, you will have to wait for each promise to resolve sequentially, which may not be as efficient:

Example #3
const delay1 = res(3000)
const delay2 = res(2000)
const delay3 = rej(1000)

const data1 = await delay1
const data2 = await delay2
const data3 = await delay3

// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =============================X await

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const delay1 = res(3000)
    const delay2 = res(2000)
    const delay3 = rej(1000)

    const data1 = await delay1
    const data2 = await delay2
    const data3 = await delay3
  } catch (error) {
    console.log(`await finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

Why does .json() return a promise?

This difference is due to the behavior of Promises more than fetch() specifically.

When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

The 2nd snippet could also have been written as:

iterator.then(response =>
    response.json().then(post => document.write(post.title))
);

In both this form and yours, the value of post is provided by the Promise returned from response.json().


When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

iterator.then(response =>
    Promise.resolve({
      data: response.json(),
      status: response.status
    })
    .then(post => document.write(post.data))
);

post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

Enumerations on PHP

I know this is an old thread, however none of the workarounds I've seen really looked like enums, since almost all workarounds requires you to manually assign values to the enum items, or it requires you to pass an array of enum keys to a function. So I created my own solution for this.

To create an enum class using my solution one can simply extend this Enum class below, create a bunch of static variables (no need to initialize them), and make a call to yourEnumClass::init() just below the definition of your enum class.

edit: This only works in php >= 5.3, but it can probably be modified to work in older versions as well

/**
 * A base class for enums. 
 * 
 * This class can be used as a base class for enums. 
 * It can be used to create regular enums (incremental indices), but it can also be used to create binary flag values.
 * To create an enum class you can simply extend this class, and make a call to <yourEnumClass>::init() before you use the enum.
 * Preferably this call is made directly after the class declaration. 
 * Example usages:
 * DaysOfTheWeek.class.php
 * abstract class DaysOfTheWeek extends Enum{
 *      static $MONDAY = 1;
 *      static $TUESDAY;
 *      static $WEDNESDAY;
 *      static $THURSDAY;
 *      static $FRIDAY;
 *      static $SATURDAY;
 *      static $SUNDAY;
 * }
 * DaysOfTheWeek::init();
 * 
 * example.php
 * require_once("DaysOfTheWeek.class.php");
 * $today = date('N');
 * if ($today == DaysOfTheWeek::$SUNDAY || $today == DaysOfTheWeek::$SATURDAY)
 *      echo "It's weekend!";
 * 
 * Flags.class.php
 * abstract class Flags extends Enum{
 *      static $FLAG_1;
 *      static $FLAG_2;
 *      static $FLAG_3;
 * }
 * Flags::init(Enum::$BINARY_FLAG);
 * 
 * example2.php
 * require_once("Flags.class.php");
 * $flags = Flags::$FLAG_1 | Flags::$FLAG_2;
 * if ($flags & Flags::$FLAG_1)
 *      echo "Flag_1 is set";
 * 
 * @author Tiddo Langerak
 */
abstract class Enum{

    static $BINARY_FLAG = 1;
    /**
     * This function must be called to initialize the enumeration!
     * 
     * @param bool $flags If the USE_BINARY flag is provided, the enum values will be binary flag values. Default: no flags set.
     */ 
    public static function init($flags = 0){
        //First, we want to get a list of all static properties of the enum class. We'll use the ReflectionClass for this.
        $enum = get_called_class();
        $ref = new ReflectionClass($enum);
        $items = $ref->getStaticProperties();
        //Now we can start assigning values to the items. 
        if ($flags & self::$BINARY_FLAG){
            //If we want binary flag values, our first value should be 1.
            $value = 1;
            //Now we can set the values for all items.
            foreach ($items as $key=>$item){
                if (!isset($item)){                 
                    //If no value is set manually, we should set it.
                    $enum::$$key = $value;
                    //And we need to calculate the new value
                    $value *= 2;
                } else {
                    //If there was already a value set, we will continue starting from that value, but only if that was a valid binary flag value.
                    //Otherwise, we will just skip this item.
                    if ($key != 0 && ($key & ($key - 1) == 0))
                        $value = 2 * $item;
                }
            }
        } else {
            //If we want to use regular indices, we'll start with index 0.
            $value = 0;
            //Now we can set the values for all items.
            foreach ($items as $key=>$item){
                if (!isset($item)){
                    //If no value is set manually, we should set it, and increment the value for the next item.
                    $enum::$$key = $value;
                    $value++;
                } else {
                    //If a value was already set, we'll continue from that value.
                    $value = $item+1;
                }
            }
        }
    }
}

How do you install GLUT and OpenGL in Visual Studio 2012?

OpenGL should be present already - it will probably be Freeglut / GLUT that is missing.

GLUT is very dated now and not actively supported - so you should certainly be using Freeglut instead. You won't have to change your code at all, and a few additional features become available.

You'll find pre-packaged sets of files from here: http://freeglut.sourceforge.net/index.php#download If you don't see the "lib" folder, it's because you didn't download the pre-packaged set. "Martin Payne's Windows binaries" is posted at above link and works on Windows 8.1 with Visual Studio 2013 at the time of this writing.

When you download these you'll find that the Freeglut folder has three subfolders: - bin folder: this contains the dll files for runtime - include: the header files for compilation - lib: contains library files for compilation/linking

Installation instructions usually suggest moving these files into the visual studio folder and the Windows system folder: It is best to avoid doing this as it makes your project less portable, and makes it much more difficult if you ever need to change which version of the library you are using (old projects might suddenly stop working, etc.)

Instead (apologies for any inconsistencies, I'm basing these instructions on VS2010)... - put the freeglut folder somewhere else, e.g. C:\dev - Open your project in Visual Studio - Open project properties - There should be a tab for VC++ Directories, here you should add the appropriate include and lib folders, e.g.: C:\dev\freeglut\include and C:\dev\freeglut\lib - (Almost) Final step is to ensure that the opengl lib file is actually linked during compilation. Still in project properties, expand the linker menu, and open the input tab. For Additional Dependencies add opengl32.lib (you would assume that this would be linked automatically just by adding the include GL/gl.h to your project, but for some reason this doesn't seem to be the case)

At this stage your project should compile OK. To actually run it, you also need to copy the freeglut.dll files into your project folder

Deep-Learning Nan loss reasons

In my case I got NAN when setting distant integer LABELs. ie:

  • Labels [0..100] the training was ok,
  • Labels [0..100] plus one additional label 8000, then I got NANs.

So, not use a very distant Label.

EDIT You can see the effect in the following simple code:

from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np

X=np.random.random(size=(20,5))
y=np.random.randint(0,high=5, size=(20,1))

model = Sequential([
            Dense(10, input_dim=X.shape[1]),
            Activation('relu'),
            Dense(5),
            Activation('softmax')
            ])
model.compile(optimizer = "Adam", loss = "sparse_categorical_crossentropy", metrics = ["accuracy"] )

print('fit model with labels in range 0..5')
history = model.fit(X, y, epochs= 5 )

X = np.vstack( (X, np.random.random(size=(1,5))))
y = np.vstack( ( y, [[8000]]))
print('fit model with labels in range 0..5 plus 8000')
history = model.fit(X, y, epochs= 5 )

The result shows the NANs after adding the label 8000:

fit model with labels in range 0..5
Epoch 1/5
20/20 [==============================] - 0s 25ms/step - loss: 1.8345 - acc: 0.1500
Epoch 2/5
20/20 [==============================] - 0s 150us/step - loss: 1.8312 - acc: 0.1500
Epoch 3/5
20/20 [==============================] - 0s 151us/step - loss: 1.8273 - acc: 0.1500
Epoch 4/5
20/20 [==============================] - 0s 198us/step - loss: 1.8233 - acc: 0.1500
Epoch 5/5
20/20 [==============================] - 0s 151us/step - loss: 1.8192 - acc: 0.1500
fit model with labels in range 0..5 plus 8000
Epoch 1/5
21/21 [==============================] - 0s 142us/step - loss: nan - acc: 0.1429
Epoch 2/5
21/21 [==============================] - 0s 238us/step - loss: nan - acc: 0.2381
Epoch 3/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 4/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 5/5
21/21 [==============================] - 0s 188us/step - loss: nan - acc: 0.2381

HTML entity for the middle dot

The semantically correct character is the Interpunct, also known as middle dot, as HTML entity

&middot;

Example

Home · Photos · About


You could also use the bullet point character, as HTML entity

&bull;

Example

Home • Photos • About

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

By default , the WAMP server will take 80 as its working port.

You can change that port number as you like ... here are the steps to do that:

  • click on WAMP server tray icon
  • click on apache
  • select http.conf

Here notepad will open ...

  • scroll down and you will see the port number that WAMP server takes ...
  • change that port number to:

    #Listen x.x.x.x:8080
    Listen 8080
    
  • save that file and restart the services... it will work fine...

  • now check by typing http://localhost:8080/.

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

What is the path that Django uses for locating and loading templates?

Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name):

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMP_DIR],
...

in views.py just add such template path:

app_name/html_name

Prevent jQuery UI dialog from setting focus to first textbox

I had similar problem. On my page first input is text box with jQuery UI calendar. Second element is button. As date already have value, I set focus on button, but first add trigger for blur on text box. This solve problem in all browsers and probably in all version of jQuery. Tested in version 1.8.2.

<div style="padding-bottom: 30px; height: 40px; width: 100%;">
@using (Html.BeginForm("Statistics", "Admin", FormMethod.Post, new { id = "FormStatistics" }))
{
    <label style="float: left;">@Translation.StatisticsChooseDate</label>
    @Html.TextBoxFor(m => m.SelectDate, new { @class = "js-date-time",  @tabindex=1 })
    <input class="button gray-button button-large button-left-margin text-bold" style="position:relative; top:-5px;" type="submit" id="ButtonStatisticsSearchTrips" value="@Translation.StatisticsSearchTrips"  tabindex="2"/>
}

<script type="text/javascript">
$(document).ready(function () {        
    $("#SelectDate").blur(function () {
        $("#SelectDate").datepicker("hide");
    });
    $("#ButtonStatisticsSearchTrips").focus();

});   

Hide text using css

The answer is to create a span with the property

{display:none;}

You can find an example at this site

How to uncommit my last commit in Git

If you commit to the wrong branch

While on the wrong branch:

  1. git log -2 gives you hashes of 2 last commits, let's say $prev and $last
  2. git checkout $prev checkout correct commit
  3. git checkout -b new-feature-branch creates a new branch for the feature
  4. git cherry-pick $last patches a branch with your changes

Then you can follow one of the methods suggested above to remove your commit from the first branch.

malloc an array of struct pointers

I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.

The code uses the ms visual studio leak detector so you can experiment with the potential leaks.

#include "stdafx.h"

#include <string.h>
#include "msc-lzw.h"

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h> 



// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
    return (key + try_num) % max;  // the hash fun returns a number bounded by the number of slots.
}


// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
    int key; // use this field as the key
    char *pValue;  // use this field to store a variable length string
};


struct hash_table {
    int max;
    int number_of_elements;
    struct key_value_pair **elements;  // This is an array of pointers to mystruct objects
};


int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {

    int try_num, hash;
    int max_number_of_retries = hash_table->max;


    if (hash_table->number_of_elements >= hash_table->max) {
        return 0; // FULL
    }

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(data->key, try_num, hash_table->max);

        if (NULL == hash_table->elements[hash]) { // an unallocated slot
            hash_table->elements[hash] = data;
            hash_table->number_of_elements++;
            return RC_OK;
        }
    }
    return RC_ERROR;
}


// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {

    unsigned int try_num, hash;
    unsigned int max_number_of_retries = hash_table->max;

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(key, try_num, hash_table->max);

        if (hash_table->elements[hash] == 0) {
            return NULL; // Nothing found
        }

        if (hash_table->elements[hash]->key == key) {
            return hash_table->elements[hash];
        }
    }
    return NULL;
}


// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter.  It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {

    int num_keys = 0;

    *ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );

    for (int i = 0; i < pHashTable->max; i++) {
        if (NULL != pHashTable->elements[i]) {
            (*ppKeys)[num_keys] = pHashTable->elements[i]->key;
            num_keys++;
        }
    }
    return num_keys;
}

// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {


    // Allocate the hash table slots
    pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair));  // allocate max number of key_value_pair entries
    for (int i = 0; i < pHashTable->max; i++) {
        pHashTable->elements[i] = NULL;
    }



    // alloc all the slots
    //struct key_value_pair *pa_slot;
    //for (int i = 0; i < pHashTable->max; i++) {
    //  // all that he could see was babylon
    //  pa_slot = (struct key_value_pair *)  malloc(sizeof(struct key_value_pair));
    //  if (NULL == pa_slot) {
    //      printf("alloc of slot failed\n");
    //      while (1);
    //  }
    //  pHashTable->elements[i] = pa_slot;
    //  pHashTable->elements[i]->key = 0;
    //}

    return RC_OK;
}


// This will make a dictionary entry where
//   o  key is an int
//   o  value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {

    // determine the len of the buffer assuming it is a string
    int len = strlen(buffer);

    // alloc the buffer to hold the string
    pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
    if (NULL == pMyStruct->pValue) {
        printf("Failed to allocate the buffer for the dictionary string value.");
        return RC_ERROR;
    }
    strcpy(pMyStruct->pValue, buffer);
    pMyStruct->key = a_key;

    return RC_OK;
}


// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {

    int rc;
    struct key_value_pair *pKeyValuePair;

    if (NULL == pHashTable) {
        printf("Hash table is null.\n");
        return RC_ERROR;
    }

    // Allocate the dictionary key value pair struct
    pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
    if (NULL == pKeyValuePair) {
        printf("Failed to allocate key value pair struct.\n");
        return RC_ERROR;
    }


    rc = make_dict_entry(key, pBuff, pKeyValuePair);  // a_hash_table[1221] = "abba"
    if (RC_ERROR == rc) {
        printf("Failed to add buff to key value pair struct.\n");
        return RC_ERROR;
    }


    rc = hash_insert(pKeyValuePair, pHashTable);
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }

    return RC_OK;
}


void dump_hash_table(struct hash_table *pHashTable) {

    // Iterate the dictionary by keys
    char * pValue;
    struct key_value_pair *pMyStruct;
    int *pKeyList;
    int num_keys;

    printf("i\tKey\tValue\n");
    printf("-----------------------------\n");
    num_keys = keys(pHashTable, &pKeyList);
    for (int i = 0; i < num_keys; i++) {
        pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
        pValue = pMyStruct->pValue;
        printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
    }

    // Free the key list
    free(pKeyList);

}

int main(int argc, char *argv[]) {

    int rc;
    int i;


    struct hash_table a_hash_table;
    a_hash_table.max = 20;   // The dictionary can hold at most 20 entries.
    a_hash_table.number_of_elements = 0;  // The intial dictionary has 0 entries.
    allocate_the_dictionary(&a_hash_table);

    rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }



    // Iterate the dictionary by keys
    dump_hash_table(&a_hash_table);

    // Free the individual slots
    for (i = 0; i < a_hash_table.max; i++) {
        // all that he could see was babylon
        if (NULL != a_hash_table.elements[i]) {
            free(a_hash_table.elements[i]->pValue);  // free the buffer in the struct
            free(a_hash_table.elements[i]);  // free the key_value_pair entry
            a_hash_table.elements[i] = NULL;
        }
    }


    // Free the overall dictionary
    free(a_hash_table.elements);


    _CrtDumpMemoryLeaks();
    return 0;
}

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

How can I reverse a list in Python?

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.

Say you have a button and you set it to the loading state:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. Apparently, button() performs some delayed task. So you'll also have to postpone your disabling:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot.

Android: Clear the back stack

Either add this to your Activity B and Activity C

android:noHistory="true"

or Override onBackPressed function to avoid back pressing with a return.

@Override
public void onBackPressed() {
   return;
}

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Another way of getting 500.19 errot for no apparent reason is - missing directories and/or broken permissions on them.

In case of this question, I believe the question asks about full IIS version. I assume this because of this line:

Config File         \\?\E:\wwwroot\web.config

IIS installer usually creates the wwwroot for you and that's the default root folder for all websites and mount point for virtual directories. It always exists, so no problem, you usually don't care much about that.

Since web.config files are hierarchical, you can put there a master web.config file and have some root settings there, and all sites will inherit it. IIS checks if that file exists and tries to load it.

However, first fun part:

This directory will exists if you have IIS properly installed. If it does not exist, you will get 500-class error. However, if you play with file/directory permissions, especially 'advanced' ones, you can actually accidentally deny IIS service account from scanning/reading the contents of this directory. If IIS is unable to check if that wwwroot\web.config exists, or if it exists and IIS is not able to open&read it - bam - 500-class error.

However, for full IIS it is very unlikely. Developers/Admins working with full IIS are usually reluctant regarding playing with wwwroot so it usually stays properly configured.

However, on IIS Express..

Usually, IIS Express "just works". Often, developers using IIS Express often are not aware how much internally it resembles the real IIS.

You can easily stumble upon the fact that IIS Express has its own applicationHost.config file and VS creates and manages it for you (correctly, to some extent) and that sort of an eye-opener telling you that it's not that simple and point-and-click as it seems at first.

Aside from that config file, VisualStudio also creates an empty directory structure under your Documents folder. If I remember correctly, IIS Express considers these folders to be the root directories of your website(s) upon which virtual directories with your code are mounted.

Later, just like IIS, when IIS Express starts up, it expects these folders to exist and checks for root web.config files there. The site web.config files. Almost always, these web.config files are missing - and that's OK because you don't want them - you have your **application web.config", they are placed with rest of the content in a virtual directories.

Now, the second fun part is: IIS Express expects that empty directories. They can be empty, but they need to exist. If they don't exist - you will get a 500-class error telling you that "web.config" file at that path cannot be accessed.

The first time I bumped into this problem was when I was clearing my hard drive. I found that 'documents\websites' folder, full of trash, I recognized several year-old projects I no longer work on, all empty, not a single file, so I deleted it all. A week later - bam - I cannot run/debug any of the sites I was working at the moment. Error was 500.19, cannot read config file.

So, if you use IIS Express and see 500-class error telling about reading configuration, carefully check the error message and read all paths mentioned. If you see anything like:

c:\users\user\documents\visual studio 2013\projects\WebProject1\WebProject1.web\web.config
c:\users\zeshan.munir\documents\visual studio 2015\projects\WebProject1\WebProject1.web\web.config
c:\users\zeshan.munir\documents\visual studio 2017\projects\WebProject1\WebProject1.web\web.config
etc..

Go there exactly where the error indicates, ensure that these folders exist, ensure that IIS worker account can traverse and read them, and if you notice that anything's wrong, maybe it will be that.

BTW. In VisualStudio, on ProjectProperties/Web there's a button "Create Virtual Directory". It essentially does this very thing, so you may try it first, but IIRC it can also somethimes clear/overwrite/swap configuration sections in applicationHost.config file, so be careful with that button if you have any custom setups there.

Rename all files in directory from $filename_h to $filename_half?

Use the rename utility written in perl. Might be that it is not available by default though...

$ touch 0{5..6}_h.png

$ ls
05_h.png  06_h.png

$ rename 's/h/half/' *.png

$ ls
05_half.png  06_half.png

How to get an object's methods?

In ES6:

let myObj   = {myFn : function() {}, tamato: true};
let allKeys = Object.keys(myObj);
let fnKeys  = allKeys.filter(key => typeof myObj[key] == 'function');
console.log(fnKeys);
// output: ["myFn"]

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

Remove part of string after "."

We can pretend they are filenames and remove extensions:

tools::file_path_sans_ext(a)
# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

excel delete row if column contains value from to-remove-list

Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.

  • -Put Original List in Column A -Put To Remove list in Column B -Select both columns, then "Conditional Formatting"
    -Select "Hightlight Cells Rules" --> "Duplicate Values"
    -The duplicates should be hightlighted in both columns
    -Then select Column A and then "Sort & Filter" ---> "Custom Sort"
    -In the dialog box that appears, select the middle option "Sort On" and pick "Cell Color"
    -Then select the next option "Sort Order" and choose "No Cell Color" "On bottom"
    -All the highlighted cells should be at the top of the list. -Select all the highlighted cells by scrolling down the list, then click delete.

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Selecting rows where remainder (modulo) is 1 after division by 2?

Note: Disregard this answer, as I must have misunderstood the question.

select *
  from Table
  where len(ColName) mod 2 = 1

The exact syntax depends on what flavor of SQL you're using.

how to compare two string dates in javascript?

You can simply compare 2 strings

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

isLater("2012-12-01", "2012-11-01")

returns true while

isLater("2012-12-01", "2013-11-01")

returns false

Is there a unique Android device ID?

Just a heads up for everyone reading looking for more up to date info. With Android O there are some changes to how the system manages these ids.

https://android-developers.googleblog.com/2017/04/changes-to-device-identifiers-in.html

tl;dr Serial will require PHONE permission and Android ID will change for different apps, based on their package name and signature.

And also Google has put together a nice document which provides suggestions about when to use the hardware and software ids.

https://developer.android.com/training/articles/user-data-ids.html

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

Outlets cannot be connected to repeating content iOS

With me I have a UIViewcontroller, and into it I have a tableview with a custom cell on it. I map my outlet of UILabel into UItableviewcell to the UIViewController then got the error.

How to split a file into equal parts, without breaking individual lines?

A simple solution for a simple question:

split -n l/5 your_file.txt

no need for scripting here.

From the man file, CHUNKS may be:

l/N     split into N files without splitting lines

Update

Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.

$location / switching between html5 and hashbang mode / link rewriting

The documentation is not very clear about AngularJS routing. It talks about Hashbang and HTML5 mode. In fact, AngularJS routing operates in three modes:

  • Hashbang Mode
  • HTML5 Mode
  • Hashbang in HTML5 Mode

For each mode there is a a respective LocationUrl class (LocationHashbangUrl, LocationUrl and LocationHashbangInHTML5Url).

In order to simulate URL rewriting you must actually set html5mode to true and decorate the $sniffer class as follows:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});

I will now explain this in more detail:

Hashbang Mode

Configuration:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
});
$locationProvider
  .html5Mode(false)
  .hashPrefix('!');

This is the case when you need to use URLs with hashes in your HTML files such as in

<a href="index.html#!/path">link</a>

In the Browser you must use the following Link: http://www.example.com/base/index.html#!/base/path

As you can see in pure Hashbang mode all links in the HTML files must begin with the base such as "index.html#!".

HTML5 Mode

Configuration:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

You should set the base in HTML-file

<html>
  <head>
    <base href="/">
  </head>
</html>

In this mode you can use links without the # in HTML files

<a href="/path">link</a>

Link in Browser:

http://www.example.com/base/path

Hashbang in HTML5 Mode

This mode is activated when we actually use HTML5 mode but in an incompatible browser. We can simulate this mode in a compatible browser by decorating the $sniffer service and setting history to false.

Configuration:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});
$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true)
  .hashPrefix('!');

Set the base in HTML-file:

<html>
  <head>
    <base href="/">
  </head>
</html>

In this case the links can also be written without the hash in the HTML file

<a href="/path">link</a>

Link in Browser:

http://www.example.com/index.html#!/base/path

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

iPhone is not available. Please reconnect the device

If your iPhone iOS version is later than Xcode device support, you should download the files device support from this site and then paste at the below location:

/Applications/Xcode11_4_1.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/13.5

creating a new list with subset of list using index in python

Suppose

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

and the list of indexes is stored in

b= [0, 1, 2, 4, 6, 7, 8]

then a simple one-line solution will be

c = [a[i] for i in b]

Find something in column A then show the value of B for that row in Excel 2010

Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...

e.g.

in Column A we have field called company....

Column A                             Column B            Column C

Company_Name                         Value        
Monster                              25000                              
Naukri                               30000  
WNS                                  80000  
American Express                     40000  
Bank of America                      50000  
Alcatel Lucent                       35000  
Google                               75000  
Microsoft                            60000  
Monster                              35000  
Bank of America                      15000 

Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem

Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)..........Result will be Monster_1 for first line item and for row no 10 & 11.....Monster_2, Bank of America_2 respectively....Here you go now you have the unique value so now you can pick any data easily now..

Cheers!!! Anil Dhawan

C++ IDE for Macs

Avoid Eclipse for C/C++ development for now on Mac OS X v10.6 (Snow Leopard). There are serious problems which make debugging problematic or nearly impossible on it currently due to GDB incompatibility problems and the like. See: Trouble debugging C++ using Eclipse Galileo on Mac.

How to delete a stash created with git stash create?

You should be using

git stash save

and not

git stash create

because this creates a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. Hence won't be accessible with stash apply.

Use git stash save "some comment" is used when you have unstaged changes you wanna replicate/move onto another branch

Use git stash apply stash@{0} (assuming your saved stash index is 0) when you want your saved(stashed) changes to reflect on your current branch

you can always use git stash list to check all you stash indexes

and use git stash drop stash@{0} (assuming your saved stash index is 0 and you wanna delete it) to delete a particular stash.

What is the simplest way to SSH using Python?

Have a look at spurplus, a wrapper around spur and paramiko that we developed to manage remote machines and perform file operations.

Spurplus provides a check_output() function out-of-the-box:

import spurplus
with spurplus.connect_with_retries(
        hostname='some-machine.example.com', username='devop') as shell:
     out = shell.check_output(['/path/to/the/command', '--some_argument']) 
     print(out)

Show special characters in Unix while using 'less' Command

less will look in its environment to see if there is a variable named LESS

You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less from the comand line, it will find the LESS.

Try adding this

export LESS="-CQaix4"

This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less, just tap the 'h' key and nose around, or run less --help.

Edit:

I looked at the help, and noticed there is also an -r option

-r  -R  ....  --raw-control-chars  --RAW-CONTROL-CHARS
                Output "raw" control characters.

I agree that cat may be the most exact match to your stated needs.

cat -vet file | less

Will add '$' at end of each line and convert tab char to visual '^I'.

cat --help
   (edited)
    -e                       equivalent to -vE
    -E, --show-ends          display $ at end of each line
    -t                       equivalent to -vT
    -T, --show-tabs          display TAB characters as ^I
    -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB

I hope this helps.

browser.msie error after update to jQuery 1.9.1

You can detect the IE browser by this way.

(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1)

you can get reference on this URL: jquery.browser.msie Alternative

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

How to echo in PHP, HTML tags

Here I have added code, the way you want line by line.

The .= helps you to echo multiple lines of code.

$html = '<div>';
$html .= '<h3><a href="#">First</a></h3>';
$html .= '<div>Lorem ipsum dolor sit amet.</div>';
$html .= '</div>';
$html .= '<div>';
echo $html;

Mockito: Inject real objects into private @Autowired fields

In Spring there is a dedicated utility called ReflectionTestUtils for this purpose. Take the specific instance and inject into the the field.


@Spy
..
@Mock
..

@InjectMock
Foo foo;

@BeforeEach
void _before(){
   ReflectionTestUtils.setField(foo,"bar", new BarImpl());// `bar` is private field
}

Wait some seconds without blocking UI execution

Look into System.Threading.Timer class. I think this is what you're looking for.

The code example on MSDN seems to show this class doing very similar to what you're trying to do (check status after certain time).

The mentioned code example from the MSDN link:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        var autoEvent = new AutoResetEvent(false);
        
        var statusChecker = new StatusChecker(10);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", 
                        DateTime.Now);
        var stateTimer = new Timer(statusChecker.CheckStatus, 
                                autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne();
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne();
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    private int invokeCount;
    private int  maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal the waiting thread.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.

Delayed rendering of React components

Using the useEffect hook, we can easily implement delay feature while typing in input field:

import React, { useState, useEffect } from 'react'

function Search() {
  const [searchTerm, setSearchTerm] = useState('')

  // Without delay
  // useEffect(() => {
  //   console.log(searchTerm)
  // }, [searchTerm])

  // With delay
  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      console.log(searchTerm)
      // Send Axios request here
    }, 3000)

    // Cleanup fn
    return () => clearTimeout(delayDebounceFn)
  }, [searchTerm])

  return (
    <input
      autoFocus
      type='text'
      autoComplete='off'
      className='live-search-field'
      placeholder='Search here...'
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  )
}

export default Search

How to split large text file in windows?

Of course there is! Win CMD can do a lot more than just split text files :)

Split a text file into separate files of 'max' lines each:

Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000

set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul

echo Number of lines in %input%:
find /c /v "" < %input%

: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (

if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)

REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)

If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):

eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.

  1. Generate regexp string/pattern files with set command to be fed to /g flag of findstr

list1.txt

\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]

list2.txt

\[[3-5][0-9][0-9][0-9]\]

list3.txt

\[[6-9][0-9][0-9][0-9]\]

  1. Split the file into smaller files:
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
  1. remove prefixed line numbers for each file split:
    eg. for the 1st file:
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>file_1.txt)

Notes:
Works with leading whitespace, blank lines & whitespace lines.

Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.

Android: Rotate image in imageview by an angle

Another possible solution is to create your own custom Image view(say RotateableImageView extends ImageView )...and override the onDraw() to rotate either the canvas/bitmaps before redering on to the canvas.Don't forget to restore the canvas back.

But if you are going to rotate only a single instance of image view,your solution should be good enough.

How to run function of parent window when child window closes?

The answers as they are require you to add code to the spawned window. That is unnecessary coupling.

// In parent window
var pop = open(url);
pop.onunload = function() {
  // Run your code, the popup window is unloading
  // Beware though, this will also fire if the user navigates to a different
  // page within thepopup. If you need to support that, you will have to play around
  // with pop.closed and setTimeouts
}

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

How to float 3 divs side by side using CSS?

I didn't see the bootstrap answer, so for what's it's worth:

<div class="col-xs-4">Left Div</div>
<div class="col-xs-4">Middle Div</div>
<div class="col-xs-4">Right Div</div>
<br style="clear: both;" />

let Bootstrap figure out the percentages. I like to clear both, just in case.

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

PHP function to get the subdomain of a URL

I know I'm really late to the game, but here goes.

What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']) and the number of letters in the domain (so for example.com it would be 11).

Then I used the substr function to get the subdomain. I did

$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);

I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered test.example.com, the value of $subdomain would be test.

This is better than using explode because if the subdomain has a . in it, this will not cut it off.

How to load URL in UIWebView in Swift?

In Swift 3 you can do it like this:

@IBOutlet weak var webview: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Web view load
    let url = URL (string: "http://www.example.com/")
    let request = URLRequest(url: url!)
    webview.loadRequest(request)
}

Remember to add permission at Info.plist, add the following values:

Info.plist

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

List all liquibase sql types

I've found the liquibase.database.typeconversion.core.AbstractTypeConverter class. It lists all types that can be used:

protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
    // Translate type to database-specific type, if possible
    DataType returnTypeName = null;
    if (dataTypeName.equalsIgnoreCase("BIGINT")) {
        returnTypeName = getBigIntType();
    } else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
        returnTypeName = getNumberType();
    } else if (dataTypeName.equalsIgnoreCase("BLOB")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
        returnTypeName = getBooleanType();
    } else if (dataTypeName.equalsIgnoreCase("CHAR")) {
        returnTypeName = getCharType();
    } else if (dataTypeName.equalsIgnoreCase("CLOB")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
        returnTypeName = getCurrencyType();
    } else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
        returnTypeName = getDateType();
    } else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
        returnTypeName = getDoubleType();
    } else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
        returnTypeName = getFloatType();
    } else if (dataTypeName.equalsIgnoreCase("INT")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
        returnTypeName = getLongBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
        returnTypeName = getSmallIntType();
    } else if (dataTypeName.equalsIgnoreCase("TEXT")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
        returnTypeName = getTimeType();
    } else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
        returnTypeName = getTinyIntType();
    } else if (dataTypeName.equalsIgnoreCase("UUID")) {
        returnTypeName = getUUIDType();
    } else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
        returnTypeName = getVarcharType();
    } else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
        returnTypeName = getNVarcharType();
    } else {
        return new CustomType(columnTypeString,0,2);
    }

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

How to start Apache and MySQL automatically when Windows 8 comes up

One of the latest XAMPP releases (XAMPP for Windows v5.6.11 (PHP 5.6.11) for sure, probably some earlier versions too) does not have the Control Panel with the "Svc" checkbox that allows to install Apache and MySQL as a service.

Go to your XAMPP/Apache directory instead (typically C:/xampp/apache) and run apache_installservice.bat as an administrator. There is also apache_uninstallservice.bat for uninstall.

To run MySQL as a service. Do it the same way - the location is xampp/mysql and batch files are: mysql_installservice.bat for service installation and mysql_uninstallservice.bat for removing the MySQL service.

You can check if they were installed or not by going to services manager window (press Windows + R and type: services.msc) and check if you have Apache service (I had Apache2.4) running and set to startup automatically. The MySQL service name is just: mysql.

How to generate a git patch for a specific commit?

If you want to be sure the (single commit) patch will be applied on top of a specific commit, you can use the new git 2.9 (June 2016) option git format-patch --base

git format-patch --base=COMMIT_VALUE~ -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git format-patch --base=auto -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git config format.useAutoBase true
git format-patch -M -C COMMIT_VALUE~..COMMIT_VALUE

See commit bb52995, commit 3de6651, commit fa2ab86, commit ded2c09 (26 Apr 2016) by Xiaolong Ye (``).
(Merged by Junio C Hamano -- gitster -- in commit 72ce3ff, 23 May 2016)

format-patch: add '--base' option to record base tree info

Maintainers or third party testers may want to know the exact base tree the patch series applies to. Teach git format-patch a '--base' option to record the base tree info and append it at the end of the first message (either the cover letter or the first patch in the series).

The base tree info consists of the "base commit", which is a well-known commit that is part of the stable part of the project history everybody else works off of, and zero or more "prerequisite patches", which are well-known patches in flight that is not yet part of the "base commit" that need to be applied on top of "base commit" in topological order before the patches can be applied.

The "base commit" is shown as "base-commit: " followed by the 40-hex of the commit object name.
A "prerequisite patch" is shown as "prerequisite-patch-id: " followed by the 40-hex "patch id", which can be obtained by passing the patch through the "git patch-id --stable" command.


Git 2.23 (Q3 2019) will improve that, because the "--base" option of "format-patch" computed the patch-ids for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable".

See commit a8f6855, commit 6f93d26 (26 Apr 2019) by Stephen Boyd (akshayka).
(Merged by Junio C Hamano -- gitster -- in commit 8202d12, 13 Jun 2019)

format-patch: make --base patch-id output stable

We weren't flushing the context each time we processed a hunk in the patch-id generation code in diff.c, but we were doing that when we generated "stable" patch-ids with the 'patch-id' tool.

Let's port that similar logic over from patch-id.c into diff.c so we can get the same hash when we're generating patch-ids for 'format-patch --base=' types of command invocations.


Before Git 2.24 (Q4 2019), "git format-patch -o <outdir>" did an equivalent of "mkdir <outdir>" not "mkdir -p <outdir>", which is being corrected.

See commit edefc31 (11 Oct 2019) by Bert Wesarg (bertwesarg).
(Merged by Junio C Hamano -- gitster -- in commit f1afbb0, 18 Oct 2019)

format-patch: create leading components of output directory

Signed-off-by: Bert Wesarg

'git format-patch -o ' did an equivalent of 'mkdir <outdir>' not 'mkdir -p <outdir>', which is being corrected.

Avoid the usage of 'adjust_shared_perm' on the leading directories which may have security implications. Achieved by temporarily disabling of 'config.sharedRepository' like 'git init' does.


With Git 2.25 (Q1 2020), "git rebase" did not work well when format.useAutoBase configuration variable is set, which has been corrected.

See commit cae0bc0, commit 945dc55, commit 700e006, commit a749d01, commit 0c47e06 (04 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 71a7de7, 16 Dec 2019)

rebase: fix format.useAutoBase breakage

Reported-by: Christian Biesinger
Signed-off-by: Denton Liu

With format.useAutoBase = true, running rebase resulted in an error:

fatal: failed to get upstream, if you want to record base commit automatically,
please use git branch --set-upstream-to to track a remote branch.
Or you could specify base commit by --base=<base-commit-id> manually
error:
git encountered an error while preparing the patches to replay
these revisions:

ede2467cdedc63784887b587a61c36b7850ebfac..d8f581194799ae29bf5fa72a98cbae98a1198b12

As a result, git cannot rebase them.

Fix this by always passing --no-base to format-patch from rebase so that the effect of format.useAutoBase is negated.


With Git 2.29 (Q4 2020), "git format-patch"(man) learns to take "whenAble" as a possible value for the format.useAutoBase configuration variable to become no-op when the automatically computed base does not make sense.

See commit 7efba5f (01 Oct 2020) by Jacob Keller (jacob-keller).
(Merged by Junio C Hamano -- gitster -- in commit 5f8c70a, 05 Oct 2020)

format-patch: teach format.useAutoBase "whenAble" option

Signed-off-by: Jacob Keller

The format.useAutoBase configuration option exists to allow users to enable '--base=auto' for format-patch by default.

This can sometimes lead to poor workflow, due to unexpected failures when attempting to format an ancient patch:

$ git format-patch -1 <an old commit>
fatal: base commit shouldn't be in revision list  

This can be very confusing, as it is not necessarily immediately obvious that the user requested a --base (since this was in the configuration, not on the command line).

We do want --base=auto to fail when it cannot provide a suitable base, as it would be equally confusing if a formatted patch did not include the base information when it was requested.

Teach format.useAutoBase a new mode, "whenAble".

This mode will cause format-patch to attempt to include a base commit when it can. However, if no valid base commit can be found, then format-patch will continue formatting the patch without a base commit.

In order to avoid making yet another branch name unusable with --base, do not teach --base=whenAble or --base=whenable.

Instead, refactor the base_commit option to use a callback, and rely on the global configuration variable auto_base.

This does mean that a user cannot request this optional base commit generation from the command line. However, this is likely not too valuable. If the user requests base information manually, they will be immediately informed of the failure to acquire a suitable base commit. This allows the user to make an informed choice about whether to continue the format.

Add tests to cover the new mode of operation for --base.

git config now includes in its man page:

format-patch by default.
Can also be set to "whenAble" to allow enabling --base=auto if a suitable base is available, but to skip adding base info otherwise without the format dying.


With Git 2.30 (Q1 2021), "git format-patch --output=there"(man) did not work as expected and instead crashed.

The option is now supported.

See commit dc1672d, commit 1e1693b, commit 4c6f781 (04 Nov 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 5edc8bd, 18 Nov 2020)

format-patch: support --output option

Reported-by: Johannes Postler
Signed-off-by: Jeff King

We've never intended to support diff's --output option in format-patch. And until baa4adc66a (parse-options: disable option abbreviation with PARSE_OPT_KEEP_UNKNOWN, 2019-01-27, Git v2.22.0-rc0), it was impossible to trigger. We first parse the format-patch options before handing the remainder off to setup_revisions().
Before that commit, we'd accept "--output=foo" as an abbreviation for "--output-directory=foo". But afterwards, we don't check abbreviations, and --output gets passed to the diff code.

This results in nonsense behavior and bugs. The diff code will have opened a filehandle at rev.diffopt.file, but we'll overwrite that with our own handles that we open for each individual patch file. So the --output file will always just be empty. But worse, the diff code also sets rev.diffopt.close_file, so log_tree_commit() will close the filehandle itself. And then the main loop in cmd_format_patch() will try to close it again, resulting in a double-free.

The simplest solution would be to just disallow --output with format-patch, as nobody ever intended it to work. However, we have accidentally documented it (because format-patch includes diff-options). And it does work with "git log"(man) , which writes the whole output to the specified file. It's easy enough to make that work for format-patch, too: it's really the same as --stdout, but pointed at a specific file.

We can detect the use of the --output option by the "close_file" flag (note that we can't use rev.diffopt.file, since the diff setup will otherwise set it to stdout). So we just need to unset that flag, but don't have to do anything else. Our situation is otherwise exactly like --stdout (note that we don't fclose() the file, but nor does the stdout case; exiting the program takes care of that for us).

How can I change the color of a Google Maps marker?

Since maps v2 is deprecated, you are probably interested in v3 maps: https://developers.google.com/maps/documentation/javascript/markers#simple_icons

For v2 maps:

http://code.google.com/apis/maps/documentation/overlays.html#Icons_overview

You would have one set of logic do all the 'regular' pins, and another that does the 'special' pin(s) using the new marker defined.

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

In my case I'd install VS.Net 2015 update 2 and left the Windows 8.1 SDK box UNchecked (since I'm now using Windows 10 and didn't think it necessary). However that seems to have resulted in some required registry settings being omitted.

Doing a modify of VS.Net 2015 from the control panel and checking the 8.1 SDK box fixed the problem.

How to customize the back button on ActionBar

I have checked the question. Here is the steps that I follow. The source code is hosted on GitHub: https://github.com/jiahaoliuliu/sherlockActionBarLab

Override the actual style for the pre-v11 devices.

Copy and paste the follow code in the file styles.xml of the default values folder.

<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note that the parent could be changed to any Sherlock theme.

Override the actual style for the v11+ devices.

On the same folder where the folder values is, create a new folder called values-v11. Android will automatically look for the content of this folder for devices with API or above.

Create a new file called styles.xml and paste the follow code into the file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="android:homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note tha the name of the style must be the same as the file in the default values folder and instead of the item homeAsUpIndicator, it is called android:homeAsUpIndicator.

The item issue is because for devices with API 11 or above, Sherlock Action Bar use the default Action Bar which comes with Android, which the key name is android:homeAsUpIndicator. But for the devices with API 10 or lower, Sherlock Action Bar uses its own ActionBar, which the home as up indicator is called simple "homeAsUpIndicator".

Use the new theme in the manifest

Replace the theme for the application/activity in the AndroidManifest file:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyCustomTheme" >

Ping all addresses in network, windows

Best Utility in terms of speed is Nmap.

write @ cmd prompt:

Nmap -sn -oG ip.txt 192.168.1.1-255

this will just ping all the ip addresses in the range given and store it in simple text file

It takes just 2 secs to scan 255 hosts using Nmap.

Advantages of SQL Server 2008 over SQL Server 2005?

The Denver SQL Server Users group has had some really good presentations over the last couple of months on the new features in SQL 2008 including one from Paul Nielsen just last week shortly after he got back from "Jump Start" up in Redmond (if I remember the name of the event correctly).

A couple of caveats on all of the "new features" for SQL 2008, the triage to determine which features will be in the various editions is still in progress. Many/most of the new/very cool features like data compression, partitioned indexes, policies, etc. are only going to be in the enterprise edition. Unless you're planning on running enterprise edition a lot of the features that are in the CTP's will probably not be in SQL 2008 standard, etc.

On other minor but often overlooked issue - SQL 2008 will only be 64-bit, if you're buying new hardware shouldn't be an issue but if you're planning on using existing hardware... also, if you've got dependencies on third party drivers (e.g. oracle) best be sure that a 64-bit version is available/works

Why Choose Struct Over Class?

Here are some other reasons to consider:

  1. structs get an automatic initializer that you don't have to maintain in code at all.

    struct MorphProperty {
       var type : MorphPropertyValueType
       var key : String
       var value : AnyObject
    
       enum MorphPropertyValueType {
           case String, Int, Double
       }
     }
    
     var m = MorphProperty(type: .Int, key: "what", value: "blah")
    

To get this in a class, you would have to add the initializer, and maintain the intializer...

  1. Basic collection types like Array are structs. The more you use them in your own code, the more you will get used to passing by value as opposed to reference. For instance:

    func removeLast(var array:[String]) {
       array.removeLast()
       println(array) // [one, two]
    }
    
    var someArray = ["one", "two", "three"]
    removeLast(someArray)
    println(someArray) // [one, two, three]
    
  2. Apparently immutability vs. mutability is a huge topic, but a lot of smart folks think immutability -- structs in this case -- is preferable. Mutable vs immutable objects

Convert a string to int using sql query

Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.

Conversion failed when converting the varchar value '56.72' to data type int.

To get around this just do two converts as follows:

STRING -> NUMERIC -> INT

or

SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)

When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):

INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA

How do I replace multiple spaces with a single space in C#?

myString = Regex.Replace(myString, " {2,}", " ");

Simplest Way to Test ODBC on WIndows

For ad hoc queries, the ODBC Test utility is pretty handy. Its design and interface is more oriented toward testing various parts of the ODBC API. But it works quite nicely for running queries and showing the output. It is part of the Microsoft Data Access Components.

To run a query, you can click the connect button (or use ctrl-F), choose a data source, type a query, then ctrl-E to execute it and ctrl-R to display the results (e.g., if it is a SELECT or something that returns a cursor).

How can I create numbered map markers in Google Maps V3?

My two cents showing how to use the Google Charts API to solve this problem.

How to solve a pair of nonlinear equations using Python?

You can use nsolve of sympy, meaning numerical solver.

Example snippet:

from sympy import *

L = 4.11 * 10 ** 5
nu = 1
rho = 0.8175
mu = 2.88 * 10 ** -6
dP = 20000
eps = 4.6 * 10 ** -5

Re, D, f = symbols('Re, D, f')

nsolve((Eq(Re, rho * nu * D / mu),
       Eq(dP, f * L / D * rho * nu ** 2 / 2),
       Eq(1 / sqrt(f), -1.8 * log ( (eps / D / 3.) ** 1.11 + 6.9 / Re))),
      (Re, D, f), (1123, -1231, -1000))

where (1123, -1231, -1000) is the initial vector to find the root. And it gives out:

enter image description here

The imaginary part are very small, both at 10^(-20), so we can consider them zero, which means the roots are all real. Re ~ 13602.938, D ~ 0.047922 and f~0.0057.

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt(string) will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters

'10px' => 10

Number(string) will return NaN if the string contains any non-numeric characters

'10px' => NaN

console.log timestamps in Chrome?

From Chrome 68:

"Show timestamps" moved to settings

The Show timestamps checkbox previously in Console Settings Console Settings has moved to Settings.

enter image description here

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.

Check if URL has certain string with PHP

if( strpos( $url, $word ) !== false ) {
    // Do something
}

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I found a solution wherein the Eclipse.ini the location was the old version of Java, and after updating the new version of java the location of -vm

C:\Program Files\Java\jre1.8.0_201\bin

was same so I had to change the directory to my new version of Java.

So solution is to just open the most updated Java version and copying its directory path and replacing it in the Eclipse.ini file.

Keytool is not recognized as an internal or external command

Make sure JAVA_HOME is set and the path in environment variables. The PATH should be able to find the keytools.exe

Open “Windows search” and search for "Environment Variables"

Under “System variables” click the “New…” button and enter JAVA_HOME as “Variable name” and the path to your Java JDK directory under “Variable value” it should be similar to this C:\Program Files\Java\jre1.8.0_231

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.

Calling one Activity from another in Android

check the following code to open new activit.

Intent f = new Intent(MainActivity.this, SecondActivity.class);

startActivity(f);

java IO Exception: Stream Closed

Don't call write.close() in writeToFile().

POST request with a simple string in body with Alamofire

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
            (convertible, params) in
            var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
            mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            return (mutableRequest, nil)
        }))

Note: parameters should not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])

Specifying trust store information in spring boot application.properties

When everything sounded so complicated, this command worked for me:

keytool -genkey -alias foo -keystore cacerts -dname cn=test -storepass changeit -keypass changeit

When a developer is in trouble, I believe a simple working solution snippet is more than enough for him. Later he could diagnose the root cause and basic understanding related to the issue.

All possible array initialization syntaxes

Non-empty arrays

  • var data0 = new int[3]

  • var data1 = new int[3] { 1, 2, 3 }

  • var data2 = new int[] { 1, 2, 3 }

  • var data3 = new[] { 1, 2, 3 }

  • var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.

Empty arrays

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } and int[] data9 = new [] { } are not compilable.

  • var data10 = { } is not compilable. Use int[] data11 = { } instead.

As an argument of a method

Only expressions that can be assigned with the var keyword can be passed as arguments.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) is not compilable
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) is not compilable

ng serve not detecting file changes automatically

Only need to run sudo ng serve to resolve the issue.

Can I set up HTML/Email Templates with ASP.NET?

Here is one more alternative that uses XSL transformations for more complex email templates: Sending HTML-based email from .NET applications.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

Find and copy files

If your intent is to copy the found files into /home/shantanu/tosend, you have the order of the arguments to cp reversed:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp "{}" /home/shantanu/tosend  \;

Please, note: the find command use {} as placeholder for matched file.

pip not working in Python Installation in Windows 10

I had the same problem on Visual Studio Code. For various reasons several python versions are installed on my computer. I was thus able to easily solve the problem by switching python interpreter.

If like me you have several versions of python on you machine, in Visual Studio Code, you can easily change the interpreter by clicking on the bottom left corner where it says Python...

enter image description here

How do I break out of nested loops in Java?

Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position. Example 1:

loop1:
 for(int i= 0; i<6; i++){
    for(int j=0; j<5; j++){
          if(i==3)
            break loop1;
        }
    }

suppose there are 3 loops and you want to terminate the loop3: Example 2:

loop3: 
for(int i= 0; i<6; i++){
loop2:
  for(int k= 0; k<6; k++){
loop1:
    for(int j=0; j<5; j++){
          if(i==3)
            break loop3;
        }
    }
}

Retrofit 2 - Dynamic URL

step -*1 

movie_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"

    android:orientation="horizontal"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/row_padding_vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/row_padding_vertical">

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginRight="10dp"
        android:src="@mipmap/ic_launcher" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:text="Hello"
            android:textColor="@color/title"
            android:textSize="16dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/genre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/title"
            android:text="realName" />
    </LinearLayout>

    <TextView
        android:id="@+id/year"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Team"
        android:textColor="@color/year" />

</LinearLayout>                                                                                                            

Api.java                                                                                  
import org.json.JSONObject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;

public interface  Api {

    String BASE_URL = "https://simplifiedcoding.net/demos/";

    @GET("marvel")
    Call<List<Hero>> getHeroes();

    @FormUrlEncoded
    @POST("/login")
    public void login(@Field("username") String username, @Field("password") String password, Callback<List<Hero>> callback);

}


MoviesAdapter.java                                                                                       import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.List;

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private List<Hero> moviesList;

    Context context;


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;
        public ImageView ivImage;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            genre = (TextView) view.findViewById(R.id.genre);
            year = (TextView) view.findViewById(R.id.year);
            ivImage =  view.findViewById(R.id.ivImage);
            ivImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(context, "-" + moviesList.get(getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    public MoviesAdapter(List<Hero> moviesList,Context context) {
        this.moviesList = moviesList;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.movie_list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Hero movie = moviesList.get(position);
        holder.title.setText(movie.getName());
        holder.genre.setText(movie.getRealname());
        holder.year.setText(movie.getTeam());

        Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(holder.ivImage);
    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }
}                                                                                                                                                        main activity                                                                                                               import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private List<Hero> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;

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

        recyclerView=findViewById(R.id.recycler_view);
        mAdapter = new MoviesAdapter(movieList,MainActivity.this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        //calling the method to display the heroes
        getHeroes();

    }


    private void getHeroes() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();

        ApiInterface api = retrofit.create(ApiInterface.class);

        Call<List<Hero>> call = api.getHeroes();

        call.enqueue(new Callback<List<Hero>>() {
            @Override
            public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
                List<Hero> heroList = response.body();

                //Creating an String array for the ListView
                String[] heroes = new String[heroList.size()];

                //looping through all the heroes and inserting the names inside the string array
                for (int i = 0; i < heroList.size(); i++) {
                    //heroes[i] = heroList.get(i).getName();
                    movieList.add(new Hero( heroList.get(i).getName(), heroList.get(i).getRealname(), heroList.get(i).getTeam()));
                }
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(Call<List<Hero>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}
Hero.java
package com.example.owner.apipractice;
public class Hero {

    private String name;
    private String realname;
    private String team;

    public Hero(String name, String realname, String team) {
        this.name = name;
        this.realname = realname;
        this.team = team;
    }

    private String firstappearance;
    private String createdby;
    private String publisher;
    private String imageurl;
    private String bio;


    public Hero(String name, String realname, String team, String firstappearance, String createdby, String publisher, String imageurl, String bio) {
        this.name = name;
        this.realname = realname;
        this.team = team;
        this.firstappearance = firstappearance;
        this.createdby = createdby;
        this.publisher = publisher;
        this.imageurl = imageurl;
        this.bio = bio;
    }

    public String getName() {
        return name;
    }

    public String getRealname() {
        return realname;
    }

    public String getTeam() {
        return team;
    }

    public String getFirstappearance() {
        return firstappearance;
    }

    public String getCreatedby() {
        return createdby;
    }

    public String getPublisher() {
        return publisher;
    }

    public String getImageurl() {
        return imageurl;
    }

    public String getBio() {
        return bio;
    }
}

Load local JSON file into variable

My solution, as answered here, is to use:

    var json = require('./data.json'); //with path

The file is loaded only once, further requests use cache.

edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs module:

var readJson = (path, cb) => {
  fs.readFile(require.resolve(path), (err, data) => {
    if (err)
      cb(err)
    else
      cb(null, JSON.parse(data))
  })
}

How to make a link open multiple pages when clicked

You need to unblock the pop up windows for your browser and the code could work.

chrome://settings/contentExceptions#popups

Chrome browser setting

How to pass url arguments (query string) to a HTTP request on Angular?

Edit Angular >= 4.3.x

HttpClient has been introduced along with HttpParams. Below an example of use :

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(Old answers)

Edit Angular >= 4.x

requestOptions.search has been deprecated. Use requestOptions.params instead :

let requestOptions = new RequestOptions();
requestOptions.params = params;

Original answer (Angular 2)

You need to import URLSearchParams as below

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

And then build your parameters and make the http request as the following :

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .toPromise()
    .then(response => response.json())
...

jQuery datepicker, onSelect won't work

<script type="text/javascript">
    $(function() {
        $("#datepicker").datepicker({ 
              onSelect: function(value, date) { 
                 window.location = 'day.jsp' ; 
              } 
        });
    });
 </script>

<div id="datepicker"></div>

I think you can try this .It works fine .

Change value in a cell based on value in another cell

by typing yes it wont charge taxes, by typing no it will charge taxes.

=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>

How does Junit @Rule work?

The explanation for how it works:

JUnit wraps your test method in a Statement object so statement and Execute() runs your test. Then instead of calling statement.Execute() directly to run your test, JUnit passes the Statement to a TestRule with the @Rule annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute() method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after.

Now, JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.

mysql: SOURCE error 2?

If you are running dockerized MySQL container such as ones from this official Docker Image registry: https://hub.docker.com/_/mysql/ You may encounter this issue as well.

split string only on first instance of specified character

A simple ES6 way to get both the first key and remaining parts in a string would be:

 const [key, ...rest] = "good_luck_buddy".split('_')
 const value = rest.join('_')
 console.log(key, value) // good, luck_buddy

TensorFlow: "Attempting to use uninitialized value" in variable initialization

It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function is a list of tf.Variable objects, then the line session.run(init) will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters to use initial_parameters_of_hypothesis_function[i].initialized_value(), which adds the necessary dependency:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))

Convert List to Pandas Dataframe Column

Use:

L = ['Thanks You', 'Its fine no problem', 'Are you sure']

#create new df 
df = pd.DataFrame({'col':L})
print (df)

                   col
0           Thanks You
1  Its fine no problem
2         Are you sure

df = pd.DataFrame({'oldcol':[1,2,3]})

#add column to existing df 
df['col'] = L
print (df)
   oldcol                  col
0       1           Thanks You
1       2  Its fine no problem
2       3         Are you sure

Thank you DYZ:

#default column name 0
df = pd.DataFrame(L)
print (df)
                     0
0           Thanks You
1  Its fine no problem
2         Are you sure

How can I get a resource "Folder" from inside my jar File?

Inside my jar file I had a folder called Upload, this folder had three other text files inside it and I needed to have an exactly the same folder and files outside of the jar file, I used the code below:

URL inputUrl = getClass().getResource("/upload/blabla1.txt");
File dest1 = new File("upload/blabla1.txt");
FileUtils.copyURLToFile(inputUrl, dest1);

URL inputUrl2 = getClass().getResource("/upload/blabla2.txt");
File dest2 = new File("upload/blabla2.txt");
FileUtils.copyURLToFile(inputUrl2, dest2);

URL inputUrl3 = getClass().getResource("/upload/blabla3.txt");
File dest3 = new File("upload/Bblabla3.txt");
FileUtils.copyURLToFile(inputUrl3, dest3);

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I also had this problem running unit tests by using ReSharper on Visual Studio 2017 and fixed it with following config:

enter image description here

Also you can change the ReSharper's run test setting: https://resharper-support.jetbrains.com/hc/en-us/articles/207242715-How-to-run-MSTest-tests-using-x64-configuration

How can I catch an error caused by mail()?

You could use the PEAR Mail classes and methods, which allows you to check for errors via:

if (PEAR::isError($mail)) {
    echo("<p>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message successfully sent!</p>");
}

You can find an example here.

UITableView Separator line

Swift 3/4

Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell):

let separatorLine = UIView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2))
separatorLine.backgroundColor = .blue
addSubview(separatorLine)

in viewDidLoad method:

tableView.separatorStyle = .none

Can I write native iPhone apps using Python?

The iPhone SDK agreement is also rather vague about whether you're even allowed to run scripting languages (outside of a WebView's Javascript). My reading is that it is OK - as long as none of the scripts you execute are downloaded from the network (so pre-installed and user-edited scripts seem to be OK).

IANAL etc etc.

Xcode 4: create IPA file instead of .xcarchive

I had the same problem... Had to recreate the project from scratch.

Note: my project was created in XCode 3.1 and was linking against a static library that was being built as a subproject (to a common destination). I changed this to build the source instead when I recreated the XCode project in XCode 4.

Now doing a Product/Archive/Share... gets the option of "iOS App Store Package (.ipa)" directly above "Application" (which is now greyed out) and "Archive" (which exports the .xcarchive).

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

When should I use "this" in a class?

Following are the ways to use ‘this’ keyword in java :

  1. Using this keyword to refer current class instance variables
  2. Using this() to invoke current class constructor
  3. Using this keyword to return the current class instance
  4. Using this keyword as method parameter

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

How to find out the server IP address (using JavaScript) that the browser is connected to?

Can do this thru a plug-in like Java applet or Flash, then have the Javascript call a function in the applet or vice versa (OR have the JS call a function in Flash or other plugin ) and return the IP. This might not be the IP used by the browser for getting the page contents. Also if there are images, css, js -> browser could have made multiple connections. I think most browsers only use the first IP they get from the DNS call (that connected successfully, not sure what happens if one node goes down after few resources are got and still to get others - timers/ ajax that add html that refer to other resources).

If java applet would have to be signed, make a connection to the window.location (got from javascript, in case applet is generic and can be used on any page on any server) else just back to home server and use java.net.Address to get IP.

Java Look and Feel (L&F)

You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:

<dependency>
        <groupId>com.jtattoo</groupId>
        <artifactId>JTattoo</artifactId>
        <version>1.6.11</version>
</dependency>

Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aero.AeroLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.fast.FastLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.mint.MintLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.smart.SmartLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel

Regards

How to access the elements of a function's return array?

The data function is returning an array, so you can access the result of the function in the same way as you would normally access elements of an array:

<?php
...
$result = data();

$a = $result[0];
$b = $result[1];
$c = $result[2];

Or you could use the list() function, as @fredrik recommends, to do the same thing in a line.

Append column to pandas dataframe

Just as a matter of fact:

data_joined = dat1.join(dat2)
print(data_joined)

Loop through each row of a range in Excel

In Loops, I always prefer to use the Cells class, using the R1C1 reference method, like this:

Cells(rr, col).Formula = ...

This allows me to quickly and easily loop over a Range of cells easily:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

How do I set default values for functions parameters in Matlab?

Matlab doesn't provide a mechanism for this, but you can construct one in userland code that's terser than inputParser or "if nargin < 1..." sequences.

function varargout = getargs(args, defaults)
%GETARGS Parse function arguments, with defaults
%
% args is varargin from the caller. By convention, a [] means "use default".
% defaults (optional) is a cell vector of corresponding default values

if nargin < 2;  defaults = {}; end

varargout = cell(1, nargout);
for i = 1:nargout
    if numel(args) >= i && ~isequal(args{i}, [])
        varargout{i} = args{i};
    elseif numel(defaults) >= i
        varargout{i} = defaults{i};
    end
end

Then you can call it in your functions like this:

function y = foo(varargin)
%FOO 
%
% y = foo(a, b, c, d, e, f, g)

[a, b,  c,       d, e, f, g] = getargs(varargin,...
{1, 14, 'dfltc'});

The formatting is a convention that lets you read down from parameter names to their default values. You can extend your getargs() with optional parameter type specifications (for error detection or implicit conversion) and argument count ranges.

There are two drawbacks to this approach. First, it's slow, so you don't want to use it for functions that are called in loops. Second, Matlab's function help - the autocompletion hints on the command line - don't work for varargin functions. But it is pretty convenient.

Get time in milliseconds using C#

I use the following class. I found it on the Internet once, postulated to be the best NOW().

/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
    private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    /// <summary>Get extra long current timestamp</summary>
    public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}

Source unknown.

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

Change the borderColor of the TextBox

Isn't it Simple as this,

txtbox1.BorderColor = System.Drawing.Color.Red;

Count records for every month in a year

SELECT    COUNT(*) 
FROM      table_emp 
WHERE     YEAR(ARR_DATE) = '2012' 
GROUP BY  MONTH(ARR_DATE)

Update elements in a JSONObject

Remove key and then add again the modified key, value pair as shown below :

    JSONObject js = new JSONObject();
    js.put("name", "rai");

    js.remove("name");
    js.put("name", "abc");

I haven't used your example; but conceptually its same.

How to refresh Android listview?

i got some problems with dynamic refresh of my listview.

Call notifyDataSetChanged() on your Adapter.

Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.

notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.

In my second class i used

Runnable run = new Runnable(){
     public void run(){
         contactsActivity.update();
     }
};
contactsActivity.runOnUiThread(run);

to acces the update() from my Activity. This update includes

myAdapter.notifyDataSetChanged();

to tell the Adapter to refresh the view. Worked fine as far as I can say.

how to make jni.h be found?

I don't know if this applies in this case, but sometimes the file got deleted for unknown reasons, copying it again into the respective folder should resolve the problem.

Retrieve a single file from a repository

in git version 1.7.9.5 this seems to work to export a single file from a remote

git archive --remote=ssh://host/pathto/repo.git HEAD README.md

This will cat the contents of the file README.md.

DateTime.Compare how to check if a date is less than 30 days old?

Actually none of these answers worked for me. I solved it by doing like this:

  if ((expireDate.Date - DateTime.Now).Days > -30)
  {
    matchFound = true;
  }

When i tried doing this:

matchFound = (expiryDate - DateTime.Now).Days < 30;

Today, 2011-11-14 and my expiryDate was 2011-10-17 i got that matchFound = -28. Instead of 28. So i inversed the last check.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Looks to be the same question as:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

Java inner class and static nested class

I think people here should notice to Poster that : Static Nest Class just only the first inner class. For example:

 public static class A {} //ERROR

 public class A {
     public class B {
         public static class C {} //ERROR
     }
 }

 public class A {
     public static class B {} //COMPILE !!!

 }

So, summarize, static class doesn't depend which class its contains. So, they cannot in normal class. (because normal class need an instance).

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

mysql-python install error: Cannot open include file 'config-win.h'

Assume you want to install package MySQL-python on Windows, maybe try pip install command with --global-option. See the example command below:

pip install MySQL-python ^
 --force-reinstall --no-cache-dir ^
 --global-option=build_ext ^
 --global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
 --global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
 --verbose

For this example, I fully installed 64-bit version of MySQL Connector C in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\.

By the way, I noticed that pip install MySQL-python by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.

Hope the above might be of some help.

What is the best way to concatenate two vectors?

Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function

http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html

will give you this.

std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);

std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...

BOOST_FOREACH(const int & i, boost::join(v0, v1)){
    cout << i << endl;
}

should give you

1
2
3
4
5
6

Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.

Comparing double values in C#

It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information.

In short – a float/double can't store 0.1 precisely. It will always be a little off.

You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.


You wanted to know the reason:

Float/double are stored as binary fractions, not decimal fractions. To illustrate:

12.34 in decimal notation (what we use) means

1 * 101 + 2 * 100 + 3 * 10-1 + 4 * 10-2

The computer stores floating point numbers in the same way, except it uses base 2: 10.01 means

1 * 21 + 0 * 20 + 0 * 2-1 + 1 * 2-2

Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example, 1/3 in decimal notation is 0.3333333…. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10. In binary notation that is 0.000110011001100….

Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.

Update value of a nested dictionary of varying depth

@FM's answer has the right general idea, i.e. a recursive solution, but somewhat peculiar coding and at least one bug. I'd recommend, instead:

Python 2:

import collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

Python 3:

import collections.abc

def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

The bug shows up when the "update" has a k, v item where v is a dict and k is not originally a key in the dictionary being updated -- @FM's code "skips" this part of the update (because it performs it on an empty new dict which isn't saved or returned anywhere, just lost when the recursive call returns).

My other changes are minor: there is no reason for the if/else construct when .get does the same job faster and cleaner, and isinstance is best applied to abstract base classes (not concrete ones) for generality.

Javascript ajax call on page onload

You can use jQuery to do that for you.

 $(document).ready(function() {
   // put Ajax here.
 });

Check it here:

http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.

PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site

Calculating the difference between two Java date instances

int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Stripping everything but alphanumeric chars from a string in Python

Regular expressions to the rescue:

import re
re.sub(r'\W+', '', your_string)

By Python definition '\W == [^a-zA-Z0-9_], which excludes all numbers, letters and _

Using Enum values as String literals

after many tries I have come with this solution

public static enum Operation {

    Addition, Subtraction, Multiplication, Division,;

    public String getUserFriendlyString() {
        if (this==Addition) {
            return " + ";
        } else if (this==Subtraction) {
            return " - ";
        } else if (this==Multiplication) {
            return " * ";
        } else if (this==Division) {
            return " / ";
        }
        return "undefined";
       }
}

Suppress command line output

Because error messages often go to stderr not stdout.

Change the invocation to this:

taskkill /im "test.exe" /f >nul 2>&1

and all will be better.

That works because stdout is file descriptor 1, and stderr is file descriptor 2 by convention. (0 is stdin, incidentally.) The 2>&1 copies output file descriptor 2 from the new value of 1, which was just redirected to the null device.

This syntax is (loosely) borrowed from many Unix shells, but you do have to be careful because there are subtle differences between the shell syntax and CMD.EXE.

Update: I know the OP understands the special nature of the "file" named NUL I'm writing to here, but a commenter didn't and so let me digress with a little more detail on that aspect.

Going all the way back to the earliest releases of MSDOS, certain file names were preempted by the file system kernel and used to refer to devices. The earliest list of those names included NUL, PRN, CON, AUX and COM1 through COM4. NUL is the null device. It can always be opened for either reading or writing, any amount can be written on it, and reads always succeed but return no data. The others include the parallel printer port, the console, and up to four serial ports. As of MSDOS 5, there were several more reserved names, but the basic convention was very well established.

When Windows was created, it started life as a fairly thin application switching layer on top of the MSDOS kernel, and thus had the same file name restrictions. When Windows NT was created as a true operating system in its own right, names like NUL and COM1 were too widely assumed to work to permit their elimination. However, the idea that new devices would always get names that would block future user of those names for actual files is obviously unreasonable.

Windows NT and all versions that follow (2K, XP, 7, and now 8) all follow use the much more elaborate NT Namespace from kernel code and to carefully constructed and highly non-portable user space code. In that name space, device drivers are visible through the \Device folder. To support the required backward compatibility there is a special mechanism using the \DosDevices folder that implements the list of reserved file names in any file system folder. User code can brows this internal name space using an API layer below the usual Win32 API; a good tool to explore the kernel namespace is WinObj from the SysInternals group at Microsoft.

For a complete description of the rules surrounding legal names of files (and devices) in Windows, this page at MSDN will be both informative and daunting. The rules are a lot more complicated than they ought to be, and it is actually impossible to answer some simple questions such as "how long is the longest legal fully qualified path name?".

Modifying Objects within stream in Java8 while iterating

The functional way would imho be:

import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateTestRun {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("a", "b", "c");
        System.out.println(lines); // [a, b, c]
        Predicate<? super String> predicate = value -> "b".equals(value);
        lines = lines.stream().filter(predicate.negate()).collect(toList());

        System.out.println(lines); // [a, c]
    }
}

In this solution the original list is not modified, but should contain your expected result in a new list that is accessible under the same variable as the old one

Run function in script from command line (Node JS)

Update 2020 - CLI

As @mix3d pointed out you can just run a command where file.js is your file and someFunction is your function optionally followed by parameters separated with spaces

npx run-func file.js someFunction "just some parameter"

That's it.

file.js called in the example above

const someFunction = (param) => console.log('Welcome, your param is', param)

// exporting is crucial
module.exports = { someFunction }

More detailed description

Run directly from CLI (global)

Install

npm i -g run-func

Usage i.e. run function "init", it must be exported, see the bottom

run-func db.js init

or

Run from package.json script (local)

Install

npm i -S run-func

Setup

"scripts": {
   "init": "run-func db.js init"
}

Usage

npm run init

Params

Any following arguments will be passed as function parameters init(param1, param2)

run-func db.js init param1 param2

Important

the function (in this example init) must be exported in the file containing it

module.exports = { init };

or ES6 export

export { init };

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Where does pip install its packages?

One can import the package then consult its help

import statsmodels
help(sm)

At the very bottom of the help there is a section FILE that indicates where this package was installed.

This solution was tested with at least matplotlib (3.1.2) and statsmodels (0.11.1) (python 3.8.2).

How can I switch my git repository to a particular commit

All the above commands create a new branch and with the latest commit being the one specified in the command, but just in case you want your current branch HEAD to move to the specified commit, below is the command:

 git checkout <commit_hash>

It detaches and point the HEAD to specified commit and saves from creating a new branch when the user just wants to view the branch state till that particular commit.


You then might want to go back to the latest commit & fix the detached HEAD:

Fix a Git detached head?

Call a function on click event in Angular 2

Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

@Component({
  templateUrl:"button.html" //this is the component which has the above button html
})

export class App implements OnInit{
  constructor(){}

  ngOnInit(){

  }

  myFunc(){
    console.log("function called");
  }
}

how to change listen port from default 7001 to something different?

As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.

Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm

HTH.

Access POST values in Symfony2 request object

Symfony 2.2

this solution is deprecated since 2.3 and will be removed in 3.0, see documentation

$form->getData();

gives you an array for the form parameters

from symfony2 book page 162 (Chapter 12: Forms)

[...] sometimes, you may just want to use a form without a class, and get back an array of the submitted data. This is actually really easy:

public function contactAction(Request $request) {
  $defaultData = array('message' => 'Type your message here');
  $form = $this->createFormBuilder($defaultData)
  ->add('name', 'text')
  ->add('email', 'email')
  ->add('message', 'textarea')
  ->getForm();
  if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);
    // data is an array with "name", "email", and "message" keys
    $data = $form->getData();
  }
  // ... render the form
}

You can also access POST values (in this case "name") directly through the request object, like so:

$this->get('request')->request->get('name');

Be advised, however, that in most cases using the getData() method is a better choice, since it returns the data (usually an object) after it's been transformed by the form framework.

When you want to access the form token, you have to use the answer of Problematic $postData = $request->request->get('contact'); because the getData() removes the element from the array


Symfony 2.3

since 2.3 you should use handleRequest instead of bindRequest:

 $form->handleRequest($request);

see documentation

How can I represent an 'Enum' in Python?

So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?

class Animal(object):
    values = ['Horse','Dog','Cat']

    class __metaclass__(type):
        def __getattr__(self, name):
            return self.values.index(name)

It keeps me from value-collision in defining my enums.

>>> Animal.Cat
2

There's another handy advantage: really fast reverse lookups:

def name_of(self, i):
    return self.values[i]

How to form tuple column from two columns in Pandas

Get comfortable with zip. It comes in handy when dealing with column data.

df['new_col'] = list(zip(df.lat, df.long))

It's less complicated and faster than using apply or map. Something like np.dstack is twice as fast as zip, but wouldn't give you tuples.

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

What is the difference between a candidate key and a primary key?

There is no difference. A primary key is a candidate key. By convention one candidate key in a relation is usually chosen to be the "primary" one but the choice is essentially arbitrary and a matter of convenience for database users/designers/developers. It doesn't make a "primary" key fundamentally any different to any other candidate key.

Hide all elements with class using plain Javascript

There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.

1.forEach and querySelectorAll('.classname')

document.querySelectorAll('.classname').forEach(function(el) {
   el.style.display = 'none';
});

2.for...of with getElementsByClassName

for (let element of document.getElementsByClassName("classname")){
   element.style.display="none";
}

3.Array.protoype.forEach getElementsByClassName

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
    // Do something amazing below
    el.style.display = 'none';
});

4.[ ].forEach and getElementsByClassName

[].forEach.call(document.getElementsByClassName("classname"), function (el) {
    el.style.display = 'none';
});

i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.

Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.

Android XML Percent Symbol

to escape the percent symbol, you just need %%

for example :

String.format("%1$d%%", 10)

returns "10%"

Twitter Bootstrap Form File Element Upload Button

I use http://gregpike.net/demos/bootstrap-file-input/demo.html:

$('input[type=file]').bootstrapFileInput();

or

$('.file-inputs').bootstrapFileInput();

How to post data to specific URL using WebClient in C#

Using webapiclient with model send serialize json parameter request.

PostModel.cs

    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

WebApiClient.cs

internal class WebApiClient  : IDisposable
  {

    private bool _isDispose;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose(bool disposing)
    {
        if (!_isDispose)
        {

            if (disposing)
            {

            }
        }

        _isDispose = true;
    }

    private void SetHeaderParameters(WebClient client)
    {
        client.Headers.Clear();
        client.Headers.Add("Content-Type", "application/json");
        client.Encoding = Encoding.UTF8;
    }

    public async Task<T> PostJsonWithModelAsync<T>(string address, string data,)
    {
        using (var client = new WebClient())
        {
            SetHeaderParameters(client);
            string result = await client.UploadStringTaskAsync(address, data); //  method:
    //The HTTP method used to send the file to the resource. If null, the default is  POST 
            return JsonConvert.DeserializeObject<T>(result);
        }
    }
}

Business caller method

    public async Task<ResultDTO> GetResultAsync(PostModel model)
    {
        try
        {
            using (var client = new WebApiClient())
            {
                var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
                var response = await client.PostJsonWithModelAsync<ResultDTO>("http://www.website.com/api/create", serializeModel);
                return response;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

Can I escape html special chars in javascript?

_x000D_
_x000D_
function escapeHtml(html){_x000D_
  var text = document.createTextNode(html);_x000D_
  var p = document.createElement('p');_x000D_
  p.appendChild(text);_x000D_
  return p.innerHTML;_x000D_
}_x000D_
_x000D_
// Escape while typing & print result_x000D_
document.querySelector('input').addEventListener('input', e => {_x000D_
  console.clear();_x000D_
  console.log( escapeHtml(e.target.value) );_x000D_
});
_x000D_
<input style='width:90%; padding:6px;' placeholder='&lt;b&gt;cool&lt;/b&gt;'>
_x000D_
_x000D_
_x000D_

error: package javax.servlet does not exist

I got here with a similar problem with my Gradle build and fixed it in a similar way:

Unable to load class hudson.model.User due to missing dependency javax/servlet/ServletException

fixed with:

dependencies {
   implementation('javax.servlet:javax.servlet-api:3.0.1')
}

How can I run a function from a script in command line?

I have a situation where I need a function from bash script which must not be executed before (e.g. by source) and the problem with @$ is that myScript.sh is then run twice, it seems... So I've come up with the idea to get the function out with sed:

sed -n "/^func ()/,/^}/p" myScript.sh

And to execute it at the time I need it, I put it in a file and use source:

sed -n "/^func ()/,/^}/p" myScript.sh > func.sh; source func.sh; rm func.sh

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I found an excellent solution to this problem on Mats Karlsson's blog. The solution is to write a subclass of ActionResult that serializes data via JSON.NET, configuring the latter to follow the camelCase convention:

public class JsonCamelCaseResult : ActionResult
{
    public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
    {
        Data = data;
        JsonRequestBehavior = jsonRequestBehavior;
    }

    public Encoding ContentEncoding { get; set; }

    public string ContentType { get; set; }

    public object Data { get; set; }

    public JsonRequestBehavior JsonRequestBehavior { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
        }

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data == null)
            return;

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
    }
}

Then use this class as follows in your MVC controller method:

public ActionResult GetPerson()
{
    return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

How to use Morgan logger?

Using morgan is pretty much straightforward. As the documentation suggests, there are different ways to get your desired output with morgan. It comes with preconfigured logging methods or you can define one yourself. Eg.

const morgan = require('morgan')

app.use(morgan('tiny')

This will give you the preconfiguration called tiny. You will notice in your terminal what it does. In case you are not satisfied with this and you want deeper e.g. lets say the request url, then this is where tokens come in.

morgan.token('url', function (req, res){ return '/api/myendpoint' })

then use it like so:

app.use(morgan(' :url ')

Check the documentation its all highlighted there.

Changing minDate and maxDate on the fly using jQuery DatePicker

I have changed min date property of date time picker by using this

$('#date').data("DateTimePicker").minDate(startDate);

I hope this one help to someone !

How to position the form in the center screen?

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

php timeout - set_time_limit(0); - don't work

Check the php.ini

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

ini_set('max_execution_time', 0); //0=NOLIMIT

What does "to stub" mean in programming?

Stub is a piece of code which converts the parameters during RPC (Remote procedure call).The parameters of RPC have to be converted because both client and server use different address space. Stub performs this conversion so that server perceive the RPC as a local function call.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Installing Android Studio, does not point to a valid JVM installation error

I had to put backslash at the end of path and it worked for me.

Earlier I was using

C:\Program Files\Java\jdk1.7.0_79

just by putting "\" at the end, worked for me. Now the value of the JAVA_HOME variable is

C:\Program Files\Java\jdk1.7.0_79\

How to query DATETIME field using only date in Microsoft SQL Server?

select * from test 
where date between '03/19/2014' and '03/19/2014 23:59:59'

This is a realy bad answer. For two reasons.

1. What happens with times like 23.59.59.700 etc. There are times larger than 23:59:59 and the next day.

2. The behaviour depends on the datatype. The query behaves differently for datetime/date/datetime2 types.

Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.

select convert (varchar(40),convert(date      , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime  , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))

-- For date the value is 'chopped'. -- For datetime the value is rounded up to the next date. (Nearest value). -- For datetime2 the value is precise.

How connect Postgres to localhost server using pgAdmin on Ubuntu?

You haven't created a user db. If its just a fresh install, the default user is postgres and the password should be blank. After you access it, you can create the users you need.

How to set up fixed width for <td>?

None of this work for me, and have many cols on datatable to make % or sm class equals to 12 elements layout on bootstrap.

I was working with datatables Angular 5 and Bootstrap 4, and have many cols in table. The solution for me was in the TH to add a DIV element with a specific width. For example for the cols "Person Name" and "Event date" I need a specific width, then put a div in the col header, the entire col width then resizes to the width specified from the div on the TH:

<table datatable [dtOptions]="dtOptions" *ngIf="listData" class="table table-hover table-sm table-bordered text-center display" width="100%">
    <thead class="thead-dark">
        <tr>
            <th scope="col">ID </th>
            <th scope="col">Value</th>
            <th scope="col"><div style="width: 600px;">Person Name</div></th>
            <th scope="col"><div style="width: 800px;">Event date</div></th> ...

How to add default value for html <textarea>?

Just in case if you are using Angular.js in your project (as I am) and have a ng-model set for your <textarea>, setting the default just inside like:

<textarea ng-model='foo'>Some default value</textarea>

...will not work!

You need to set the default value to the textarea's ng-model in the respective controller or use ng-init.

Example 1 (using ng-init):

_x000D_
_x000D_
var myApp = angular.module('myApp',[]);_x000D_
_x000D_
myApp.controller('MyCtrl', [ '$scope', function($scope){_x000D_
  // your controller implementation here_x000D_
}]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
    <meta charset="utf-8">_x000D_
    <title>JS Bin</title>_x000D_
  </head>_x000D_
  <body ng-app='myApp'>_x000D_
    <div ng-controller="MyCtrl">_x000D_
      <textarea ng-init='foo="Some default value"' ng-model='foo'></textarea>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Example 2 (without using ng-init):

_x000D_
_x000D_
var myApp = angular.module('myApp',[]);_x000D_
_x000D_
myApp.controller('MyCtrl', [ '$scope', function($scope){_x000D_
  $scope.foo = 'Some default value';_x000D_
}]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
    <meta charset="utf-8">_x000D_
    <title>JS Bin</title>_x000D_
  </head>_x000D_
  <body ng-app='myApp'>_x000D_
    <div ng-controller="MyCtrl">_x000D_
      <textarea ng-model='foo'></textarea>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to reliably open a file in the same directory as a Python script

To quote from the Python documentation:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

sys.path[0] is what you are looking for.