Programs & Examples On #Audioformat

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Note: if you upgrade from spring boot 1 to spring boot 2 there is a ResponseStatusException which has a Http error code and a description.

So, you can effectively use generics they way it is intended.

The only case which is a bit challenging for me, is the response type for a status 204 (ok with no body). I tend to mark those methods as ResponseEntity<?>, because ResponseEntity<Void> is less predictive.

Make a negative number positive

Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);

How to predict input image using trained model in Keras?

That's because you're getting the numeric value associated with the class. For example if you have two classes cats and dogs, Keras will associate them numeric values 0 and 1. To get the mapping between your classes and their associated numeric value, you can use

>>> classes = train_generator.class_indices    
>>> print(classes)
    {'cats': 0, 'dogs': 1}

Now you know the mapping between your classes and indices. So now what you can do is

if classes[0][0] == 1: prediction = 'dog' else: prediction = 'cat'

bootstrap 3 - how do I place the brand in the center of the navbar?

Just create this class and add it to your element to be centered.

.navbar-center {
  margin-left: auto;
  margin-right: auto;
}

What is context in _.each(list, iterator, [context])?

As explained in other answers, context is the this context to be used inside callback passed to each.

I'll explain this with the help of source code of relevant methods from underscore source code

The definition of _.each or _.forEach is as follows:

_.each = _.forEach = function(obj, iteratee, context) {
  iteratee = optimizeCb(iteratee, context);

  var i, length;
  if (isArrayLike(obj)) {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var keys = _.keys(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      iteratee(obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
};

Second statement is important to note here

iteratee = optimizeCb(iteratee, context);

Here, context is passed to another method optimizeCb and the returned function from it is then assigned to iteratee which is called later.

var optimizeCb = function(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1:
      return function(value) {
        return func.call(context, value);
      };
    case 2:
      return function(value, other) {
        return func.call(context, value, other);
      };
    case 3:
      return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
    case 4:
      return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
  }
  return function() {
    return func.apply(context, arguments);
  };
};

As can be seen from the above method definition of optimizeCb, if context is not passed then func is returned as it is. If context is passed, callback function is called as

func.call(context, other_parameters);
          ^^^^^^^

func is called with call() which is used to invoke a method by setting this context of it. So, when this is used inside func, it'll refer to context.

_x000D_
_x000D_
// Without `context`_x000D_
_.each([1], function() {_x000D_
  console.log(this instanceof Window);_x000D_
});_x000D_
_x000D_
_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
  console.log(this);_x000D_
}, arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

You can consider context as the last optional parameter to forEach in JavaScript.

This action could not be completed. Try Again (-22421)

When you receive error "Action could not be completed. Try Again (-22421)", Just try to resubmit same app on iTunes store using XCode again, and you will get the actual error messages next time.

Detailed error message which your received next time will help you what to do actually!!!

If you are receiving same error again and again, you can submit app using "App Loader" and it may success to submit.

[ Take care Point: ]

Please check your app version / build version number is greater than previously submitted version. You can verify it in Xcode -> Project setting -> General section AND iTunes-Connect-Account -> App Package -> Activity tab

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

Move existing, uncommitted work to a new branch in Git

If you commit it, you could also cherry-pick the single commit ID. I do this often when I start work in master, and then want to create a local branch before I push up to my origin/.

git cherry-pick <commitID>

There is alot you can do with cherry-pick, as described here, but this could be a use-case for you.

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

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

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

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

javascript createElement(), style problem

You need to call the appendChild function to append your new element to an existing element in the DOM.

Turn a string into a valid filename?

Why not just wrap the "osopen" with a try/except and let the underlying OS sort out whether the file is valid?

This seems like much less work and is valid no matter which OS you use.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

R: Select values from data table in range

One should also consider another intuitive way to do this using filter() from dplyr. Here are some examples:

set.seed(123)
df <- data.frame(name = sample(letters, 100, TRUE),
                 date = sample(1:500, 100, TRUE))
library(dplyr)
filter(df, date < 50) # date less than 50
filter(df, date %in% 50:100) # date between 50 and 100
filter(df, date %in% 1:50 & name == "r") # date between 1 and 50 AND name is "r"
filter(df, date %in% 1:50 | name == "r") # date between 1 and 50 OR name is "r"

# You can also use the pipe (%>%) operator
df %>% filter(date %in% 1:50 | name == "r")

shell script to remove a file if it already exist

Something like this would work

#!/bin/sh

if [ -fe FILE ]
then 
    rm FILE
fi 

-f checks if it's a regular file

-e checks if the file exist

Introduction to if for more information

EDIT : -e used with -f is redundant, fo using -f alone should work too

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
    {
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
            Math.Cos(longitudeDifferenceInRadians));

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
    }

    private static double ToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

What is an 'undeclared identifier' error and how do I fix it?

I had the same problem with a custom class, which was defined in a namespace. I tried to use the class without the namespace, causing the compiler error "identifier "MyClass" is undefined". Adding

using namespace <MyNamespace>

or using the class like

MyNamespace::MyClass myClass;

solved the problem.

How to construct a std::string from a std::vector<char>?

I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

SQL Server SELECT LAST N Rows

This may not be quite the right fit to the question, but…

OFFSET clause

The OFFSET number clause enables you to skip over a number of rows and then return rows after that.

That doc link is to Postgres; I don't know if this applies to Sybase/MS SQL Server.

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

How to split a string in Haskell?

Example in the ghci:

>  import qualified Text.Regex as R
>  R.splitRegex (R.mkRegex "x") "2x3x777"
>  ["2","3","777"]

Can't update: no tracked branch

This isuse because of coflict merge. If you have new commit in origin and not get those files; also you have changed the local master branch files then you got this error. You should fetch again to a new directory and copy your files into that path. Finally, you should commit and push your changes.

spark submit add multiple jars in classpath

You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .

spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*

Use Awk to extract substring

You do not need any external command at all, just use Parameter Expansion in bash:

hostname=aaa0.bbb.ccc
echo ${hostname%%.*}

How to install numpy on windows using pip install?

First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Make sure, following jar file included in your class path and lib folder.

spring-core-3.0.5.RELEASE.jar

enter image description here

if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
</dependency>

Note : Replace ${org.springframework.version} with version number.

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

What is stdClass in PHP?

stClass is an empty class created by php itself , and should be used by php only, because it is not just an "empty" class , php uses stdClass to convert arrays to object style if you need to use stdClass , I recommend two better options : 1- use arrays (much faster than classes) 2- make your own empty class and use it

//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);

//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';

what makes someone to think about using the object style instead of array style???

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

Compare a date string to datetime in SQL Server?

There are many formats for date in SQL which are being specified. Refer https://msdn.microsoft.com/en-in/library/ms187928.aspx

Converting and comparing varchar column with selected dates.

Syntax:

SELECT * FROM tablename where CONVERT(datetime,columnname,103) 
    between '2016-03-01' and '2016-03-03'
In CONVERT(DATETIME,COLUMNNAME,103) "103" SPECIFIES THE DATE FORMAT as dd/mm/yyyy

Postgres ERROR: could not open file for reading: Permission denied

I resolved the same issue with a recursive chown on the parent folder:

sudo chown -R postgres:postgres /home/my_user/export_folder

(my export being in /home/my_user/export_folder/export_1.csv)

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.

Can I edit an iPad's host file?

You can also make use of a proxy server on your iPhone or iPade via mobile internet (3G) by using a iPhone Mobile proxy generator:

http://iphonesettings.net/mobileproxygenerator.php

Just enter the apn of your carrier (with apn username/password if needed) and the proxy server you want to go through and tap Generate

How to exit a 'git status' list in a terminal?

:q

that's a less command, actually. It uses the same commands as vi.

How do I set/unset a cookie with jQuery?

A simple example of set cookie in your browser:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

Simple just copy/paste and use this code for set your cookie.

ERROR in ./node_modules/css-loader?

I am also facing the same problem, but I resolve.

npm install node-sass  

Above command work for me. As per your synario you can use the blow command.

Try 1

 npm install node-sass

Try 2

remove node_modules folder and run npm install

Try 3

npm rebuild node-sass

Try 4

npm install --save node-sass

For your ref you can go through this github link

Check if input is integer type in C

I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!

#include<stdio.h>

int iFunctErrorCheck(int iLowerBound, int iUpperBound){

int iUserInput=0;
while (iUserInput==0){
    scanf("%i", &iUserInput);
    if (iUserInput==0){
        printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
        getchar();
    }
    if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
        printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
        iUserInput=0;
    }
}
return iUserInput;
}

Pip install Matplotlib error with virtualenv

As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.

The solution:
From github issue:

This bug only occurs if pkg-config is not installed;
a simple
sudo apt-get install pkg-config
will shore up the include paths for now.

After this installation proceeds smoothly.

How can I pass a list as a command-line argument with argparse?

If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,

[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]

then you can use the solution proposed by @sam-mason to this question, shown below:

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])

which gives:

Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])

Comparing arrays in JUnit assertions, concise built-in way?

Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.

Fully change package name including company domain

I found another solution for renaming a package in the entire project:

Open a file in the package. IntelliJ displays the breadcrumbs of the file, above the opened file. On the package you want renamed: Right click > Refactor > Rename. This renames the package/directory throughout the entire project.

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How to return an array from a function?

"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"

template <class X>
  class Array
{
  X     *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(X* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new X [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(X));
            return m_size;
        }
       return 0;
    }
}; 

just for int

class IntArray
{
  int   *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(int* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new int [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(int));
            return m_size;
        }
       return 0;
    }
}; 

example

Array<float> array;
float  *n_data = NULL;
int     data_size;
if(data_size = array.Get(n_data))
{     // work with array    }

delete [] n_data;

example for int

IntArray   array;
int       *n_data = NULL;
int        data_size;
if(data_size = array.Get(n_data))
{  // work with array  }

delete [] n_data;

How to delete a specific file from folder using asp.net

This is how I delete files

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}

Also make sure that the file name you are passing in your delete, is the accurate path

EDIT

You could use the following event instead as well or just use the code in this snippet and use in your method

void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;

    //Debug this line and see what value is returned if it contains the full path.
    //If it does not contain the full path then add the path to the string.
    string fileName = row.Cells[0].Text 

    if(fileName != null || fileName != string.empty)
    {
       if((System.IO.File.Exists(fileName))
           System.IO.File.Delete(fileName);

     }
  }

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

How can I force WebKit to redraw/repaint to propagate style changes?

I came up here because I needed to redraw scrollbars in Chrome after changing its css.

If someone's having the same problem, I solved it by calling this function:

//Hack to force scroll redraw
function scrollReDraw() {
    $('body').css('overflow', 'hidden').height();
    $('body').css('overflow', 'auto');
}

This method is not the best solution, but it may work with everything, hiding and showing the element that needs to be redraw may solve every problem.

Here is the fiddle where I used it: http://jsfiddle.net/promatik/wZwJz/18/

Does a TCP socket connection have a "keep alive"?

TCP sockets remain open till they are closed.

That said, it's very difficult to detect a broken connection (broken, as in a router died, etc, as opposed to closed) without actually sending data, so most applications do some sort of ping/pong reaction every so often just to make sure the connection is still actually alive.

Is it possible to use JavaScript to change the meta-tags of the page?

For anyone trying to change og:title meta tags (or any other). I managed to do it this way:

document.querySelector('meta[property="og:title"]').setAttribute("content", "Example with og title meta tag");

Attention that the 'meta[property="og:title"]' contains the word PROPERTY, and not NAME.

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

How do I set the colour of a label (coloured text) in Java?

JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);

this should work

View RDD contents in Python Spark?

You can simply collect the entire RDD (which will return a list of rows) and print said list:

print(wc.collect())

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked="checked" />

or simply

<input type="checkbox" checked />

for checked checkbox. No checked attribute (<input type="checkbox" />) for unchecked checkbox.

reference: http://www.w3.org/TR/html-markup/input.checkbox.html#input.checkbox.attrs.checked

What is an API key?

Very generally speaking:

An API key simply identifies you.

If there is a public/private distinction, then the public key is one that you can distribute to others, to allow them to get some subset of information about you from the api. The private key is for your use only, and provides access to all of your data.

Flushing footer to bottom of the page, twitter bootstrap

Found the snippets here works really well for bootstrap

Html:

<div id="wrap">
  <div id="main" class="container clear-top">
    <p>Your content here</p>
  </div>
</div>
<footer class="footer"></footer>

CSS:

html, body {
  height: 100%;
}

#wrap {
  min-height: 100%;
}

#main {
  overflow:auto;
  padding-bottom:150px; /* this needs to be bigger than footer height*/
}

.footer {
  position: relative;
  margin-top: -150px; /* negative value of footer height */
  height: 150px;
  clear:both;
  padding-top:20px;
} 

Generate random number between two numbers in JavaScript

This is about nine years late, but randojs.com makes this a simple one-liner:

rando(1, 6)

You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.

<script src="https://randojs.com/1.0.0.js"></script>

Run "mvn clean install" in Eclipse

I use eclipse STS, so the maven plugin comes pre-installed. However, if you aren't using STS (Springsource Tool Suite), you can still install the m2Eclipse plugin. Here is the link:

http://www.eclipse.org/m2e/

Once you have this installed, you should be able to run all the maven commands. To do so, from the package explorer, you would right click on either the maven project or the pom.xml in the maven project, highlight Run As, then click Maven Install.

Hope this helped.

How do I clone a single branch in Git?

Open the cmd.

cd folder_name  # enter the path where to clone the branch

Just one command:

git clone url_of_projecturltoclone -b branch_name

How to obtain a QuerySet of all rows, with specific fields for each one of them?

You can use values_list alongside filter like so;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)

More details here

Android studio, gradle and NDK

In Google IO 2015, Google announced full NDK integration in Android Studio 1.3.

It is now out of preview, and available to everyone: https://developer.android.com/studio/projects/add-native-code.html

Old answer: Gradle automatically calls ndk-build if you have a jni directory in your project sources.

This is working on Android studio 0.5.9 (canary build).

  1. Download the NDK

  2. Either add ANDROID_NDK_HOME to your environment variables or add ndk.dir=/path/to/ndk to your local.properties in your Android Studio project. This allows Android studio to run the ndk automatically.

  3. Download the latest gradle sample projects to see an example of an ndk project. (They're at the bottom of the page). A good sample project is ndkJniLib.

  4. Copy the gradle.build from the NDK sample projects. It'll look something like this. This gradle.build creates a different apk for each architecture. You must select which architecture you want using the build variants pane. build variants pane

    apply plugin: 'android'
    
    dependencies {
        compile project(':lib')
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.2"
    
        // This actual the app version code. Giving ourselves 100,000 values [0, 99999]
        defaultConfig.versionCode = 123
    
        flavorDimensions "api", "abi"
    
        productFlavors {
            gingerbread {
                flavorDimension "api"
                minSdkVersion 10
                versionCode = 1
            }
            icecreamSandwich {
                flavorDimension "api"
                minSdkVersion 14
                versionCode = 2
            }
            x86 {
                flavorDimension "abi"
                ndk {
                    abiFilter "x86"
                }
                // this is the flavor part of the version code.
                // It must be higher than the arm one for devices supporting
                // both, as x86 is preferred.
                versionCode = 3
            }
            arm {
                flavorDimension "abi"
                ndk {
                    abiFilter "armeabi-v7a"
                }
                versionCode = 2
            }
            mips {
                flavorDimension "abi"
                ndk {
                    abiFilter "mips"
                }
                versionCode = 1
            }
            fat {
                flavorDimension "abi"
                // fat binary, lowest version code to be
                // the last option
                versionCode = 0
            }
        }
    
        // make per-variant version code
        applicationVariants.all { variant ->
            // get the version code of each flavor
            def apiVersion = variant.productFlavors.get(0).versionCode
            def abiVersion = variant.productFlavors.get(1).versionCode
    
            // set the composite code
            variant.mergedFlavor.versionCode = apiVersion * 1000000 + abiVersion * 100000 + defaultConfig.versionCode
        }
    
    }
    

Note that this will ignore your Android.mk and Application.mk files. As a workaround, you can tell gradle to disable atuomatic ndk-build call, then specify the directory for ndk sources manually.

sourceSets.main {
    jniLibs.srcDir 'src/main/libs' // use the jni .so compiled from the manual ndk-build command
    jni.srcDirs = [] //disable automatic ndk-build call
}

In addition, you'll probably want to call ndk-build in your gradle build script explicitly, because you just disabled the automatic call.

task ndkBuild(type: Exec) {
   commandLine 'ndk-build', '-C', file('src/main/jni').absolutePath
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

why windows 7 task scheduler task fails with error 2147942667

For me, this was due to the user PATH environment variable, which didn't seem to work even though the user was correct, so I needed to put the entire executable path into the program field.

How to reduce the image size without losing quality in PHP

I'd go for jpeg. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick

Hope this helps

How to apply filters to *ngFor?

A simple solution that works with Angular 6 for filtering a ngFor, it's the following:

_x000D_
_x000D_
<span *ngFor="item of itemsList"  >_x000D_
  <div *ngIf="yourCondition(item)">_x000D_
    _x000D_
    your code_x000D_
    _x000D_
  </div>_x000D_
</span
_x000D_
_x000D_
_x000D_

Spans are useful because does not inherently represent anything.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

To get the insert ignore logic you can do something like below. I found simply inserting from a select statement of literal values worked best, then you can mask out the duplicate keys with a NOT EXISTS clause. To get the update on duplicate logic I suspect a pl/pgsql loop would be necessary.

INSERT INTO manager.vin_manufacturer
(SELECT * FROM( VALUES
  ('935',' Citroën Brazil','Citroën'),
  ('ABC', 'Toyota', 'Toyota'),
  ('ZOM',' OM','OM')
  ) as tmp (vin_manufacturer_id, manufacturer_desc, make_desc)
  WHERE NOT EXISTS (
    --ignore anything that has already been inserted
    SELECT 1 FROM manager.vin_manufacturer m where m.vin_manufacturer_id = tmp.vin_manufacturer_id)
)

How do I disable text selection with CSS or JavaScript?

I'm not sure if you can turn it off, but you can change the colors of it :)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

Then just match the colors to your "darky" design and see what happens :)

Text blinking jQuery

this code is work for me

   $(document).ready(function () {
        setInterval(function(){
            $(".blink").fadeOut(function () {
                $(this).fadeIn();
            });
        } ,100)
    });

A simple algorithm for polygon intersection

You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)

Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.

Now given two polygons in that representation, you can compute the intersection as:

Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.

You get a new polygon following the same representation.

Since convex polygon intersection is easy, this intersection finding should be easy too.

This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.

JavaScript adding decimal numbers issue

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in JavaScript:

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

How to toggle font awesome icon on click?

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

Fixing broken UTF-8 encoding

Another thing to check, which happened to be my solution (found here), is how data is being returned from your server. In my application, I'm using PDO to connect from PHP to MySQL. I needed to add a flag to the connection which said get the data back in UTF-8 format

The answer was

$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass, 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

Call js-function using JQuery timer

function run() {
    window.setTimeout(
         "run()",
         1000
    );
}

SQL: How to properly check if a record exists

I'm using this way:

IIF(EXISTS (SELECT TOP 1 1 
                FROM Users 
                WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

After you edit /etc/php5/apache2/php.ini be sure to restart apache.

You can do so by running:

sudo service apache2 restart

How to set Spinner default value to null?

Base on @Jonik answer I have created fully functional extension to ArrayAdapter

class SpinnerArrayAdapter<T> : ArrayAdapter<T> {

    private val selectText : String
    private val resource: Int
    private val fieldId : Int
    private val inflater : LayoutInflater

    constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId,  objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(true)
        }

        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(false)
        }
        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getCount(): Int {
        return super.getCount() + 1 // adjust for initial selection
    }

    private fun initialSelection(inDropDown: Boolean) : View {
        // Just simple TextView as initial selection.
        val view = TextView(context)
        view.setText(selectText)
        view.setPadding(8, 0, 8, 0)

        if(inDropDown) {
            // Hide when dropdown is open
            view.height = 0
        }
        return view
    }

    private fun createViewFromResource(inflater: LayoutInflater, position: Int,
                                       @Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
        val view: View
        val text: TextView?

        if (convertView == null || (convertView is TextView)) {
            view = inflater.inflate(resource, parent, false)
        } else {
            view = convertView
        }

        try {
            if (fieldId === 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = view as TextView
            } else {
                //  Otherwise, find the TextView field within the layout
                text = view.findViewById(fieldId)

                if (text == null) {
                    throw RuntimeException("Failed to find view with ID "
                            + context.getResources().getResourceName(fieldId)
                            + " in item layout")
                }
            }
        } catch (e: ClassCastException) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
            throw IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e)
        }

        val item = getItem(position)
        if (item is CharSequence) {
            text.text = item
        } else {
            text.text = item!!.toString()
        }

        return view
    }

Python virtualenv questions

on Windows I have python 3.7 installed and I still couldn't activate virtualenv from Gitbash with ./Scripts/activate although it worked from Powershell after running Set-ExecutionPolicy Unrestricted in Powershell and changing the setting to "Yes To All".

I don't like Powershell and I like to use Gitbash, so to activate virtualenv in Gitbash first navigate to your project folder, use ls to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts, once you're in the "Scripts" path use . activate to activate virtualenv. Don't forget the space after the dot.

Turning off auto indent when pasting text into vim

I just put set clipboard=unnamed in my .vimrc. That makes the default paste buffer map to X's clipboard.

So, if I mark a bit of text in a terminal, I can simply press p to paste it in vim. Similarly, I can yank things in vim (e.g. YY to yank the current line into the buffer) and middle click in any window to paste it.

I don't know. I find it super convenient.

How to get client IP address using jQuery

A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.

$.getJSON('getip.php', function(data){
  alert('Your ip is: ' +  data.ip);
});

Then in php you might do:

<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));

How to prevent a browser from storing passwords

I did it by setting the input field as "text", and catching and manipulating the input keys

first activate a function to catch keys

yourInputElement.addEventListener('keydown', onInputPassword);

the onInputPassword function is like this: (assuming that you have the "password" variable defined somewhere)

onInputPassword( event ) {
  let key = event.key;
  event.preventDefault(); // this is to prevent the key to reach the input field

  if( key == "Enter" ) {
    // here you put a call to the function that will do something with the password
  }
  else if( key == "Backspace" ) {
    if( password ) {
      // remove the last character if any
      yourInputElement.value = yourInputElement.value.slice(0, -1);
      password = password.slice(0, -1);
    }
  }
  else if( (key >= '0' && key <= '9') || (key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z') ) {
    // show a fake '*' on input field and store the real password
    yourInputElement.value = yourInputElement.value + "*";
    password += key;
  }
}

so all alphanumeric keys will be added to the password, the 'backspace' key will erase one character, the 'enter' key will terminate, and any other keys will be ignored

don't forget to call removeEventListener('keydown', onInputPassword) somewhere at the end

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

A Simple, 2d cross-platform graphics library for c or c++?

A cross platform 2D graphics library for .Net is The Little Vector Library You could use it in conjunction with Unity 3D (recommended) or Xamarin, for example, to create 2D graphics on a variety of platforms.

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

multiple conditions for JavaScript .includes() method

You can use the .some method referenced here.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

_x000D_
_x000D_
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));

// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
_x000D_
_x000D_

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

How do I add a simple onClick event handler to a canvas element?

As an alternative to alex's answer:

You could use a SVG drawing instead of a Canvas drawing. There you can add events directly to the drawn DOM objects.

see for example:

Making an svg image object clickable with onclick, avoiding absolute positioning

Disabled href tag

if you just want to temporarily disable the link but leave the href there to enable later (which is what I wanted to do) I found that all browsers use the first href. Hence I was able to do:

<a class="ea-link" href="javascript:void(0)" href="/export/">Export</a>

How to print jquery object/array

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

How do I remove a single file from the staging area (undo git add)?

You need to be in the directory of the file and then type the following into the terminal

git checkout -- <file>

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

Difference between multitasking, multithreading and multiprocessing?

Multithreading Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual threads.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

yes, it accepts the tuple of four arguments, if you have Number of training Images(or whatever)=6000, image size=28x28 and a grayscale image you'll have parameters as (6000,28,28,1)

the last argument is 1 for greyscale and 3 for color images.

Can a unit test project load the target application's app.config file?

If you have a solution which contains for example Web Application and Test Project, you probably want that Test Project uses Web Application's web.config.

One way to solve it is to copy web.config to test project and rename it as app.config.

Another and better solution is to modify build chain and make it to make automatic copy of web.config to test projects output directory. To do that, right click Test Application and select properties. Now you should see project properties. Click "Build Events" and then click "Edit Post-build..." button. Write following line to there:

copy "$(SolutionDir)\WebApplication1\web.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"

And click OK. (Note you most probably need to change WebApplication1 as you project name which you want to test). If you have wrong path to web.config then copy fails and you will notice it during unsuccessful build.

Edit:

To Copy from the current Project to the Test Project:

copy "$(ProjectDir)bin\WebProject.dll.config" "$(SolutionDir)WebProject.Tests\bin\Debug\App.Config"

Loop through each row of a range in Excel

Something like this:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

Xcode iOS 8 Keyboard types not supported

For me turning on and off the setting on

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

proved to fix the issue on simulators.

How to send parameters from a notification-click to an activity?

Take a look at this guide (creating a notification) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".

For managing if the activity is already running you have two ways:

  1. Add FLAG_ACTIVITY_SINGLE_TOP flag to the Intent when launching the activity, and then in the activity class implement onNewIntent(Intent intent) event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.

  2. Same as number one, but instead of adding a flag to the Intent you must add "singleTop" in your activity AndroidManifest.xml.

If you use intent extras, remeber to call PendingIntent.getActivity() with the flag PendingIntent.FLAG_UPDATE_CURRENT, otherwise the same extras will be reused for every notification.

AngularJS - How to use $routeParams in generating the templateUrl?

Alright, think I got it...

Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.

So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...

When you set up your module, save the $routeProvider globally:

// app.js:
var routeProvider
    , app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){

        routeProvider = $routeProvider;
        $routeProvider
            .when('/', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/home', {templateUrl: '/', controller: 'AppCtrl'})
            .when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
            .when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
            .when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
            .when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
            .when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
            .when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
            .when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
            .when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
            .when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
            .when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
        .otherwise({redirectTo: '/login'});

});

// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){

    var idParam = $routeParams.id;
    routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
    $location.path('/tasks/' + idParam + '/edit/');

});
...

That may be more info than what was needed...

  • Basically, you'll wanna store your Module's $routeProvider var globally, eg as routeProvider so that it can be accessed by your Controllers.

  • Then you can just use routeProvider and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.

  • Then (inside your Controller), set the templateUrl to the view you want to hit.

  • Take out the controller property of the .when() object, lest you get an infinite request loop.

  • And finally (still inside the Controller), use $location.path() to redirect to the route that was just created.

If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.

And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}.

If you clone this at this time, you'll need mongoDB on your machine to run it.

Hope this solves this issue!

Cody

Don't drink your bathwater.

How to format font style and color in echo

echo "<span style = 'font-color: #ff0000'> Movie List for {$key} 2013 </span>";

Variables are only expanded inside double quotes, not single quotes. Since the above uses double quotes for the PHP string, I switched to single quotes for the embedded HTML, to avoid having to escape the quotes.

The other problem with your code is that <style> tags are for entering CSS blocks, not for styling individual elements. To style an element, you need an element tag with a style attribute; <span> is the simplest element -- it doesn't have any formatting of its own, it just serves as a place to attach attributes.

Another popular way to write it is with string concatenation:

echo '<span style = "font-color: #ff0000"> Movie List for ' . $key . ' 2013 </span>';

Equal sized table cells to fill the entire width of the containing table

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td's). With these two properties set, the table cells will be equal in size.

Refer to the demo.

selecting an entire row based on a variable excel vba

Saw this answer on another site and it works for me as well!

Posted by Shawn on October 14, 2001 1:24 PM

var1 = 1

var2 = 5

Rows(var1 & ":" & var2).Select

That worked for me, looks like you just have to keep the variables outside the quotes and add the and statement (&)

-Shawn

First letter capitalization for EditText

Statically (i.e. in your layout XML file): set android:inputType="textCapSentences" on your EditText.

Programmatically: you have to include InputType.TYPE_CLASS_TEXT in the InputType of the EditText, e.g.

EditText editor = new EditText(this); 
editor.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

Can be combined with text and its variations to request capitalization of the first character of every sentence.

- Google Docs

Auto Generate Database Diagram MySQL

MySQL Workbench worked like a charm.

I just backed up database structure to SQL script and used it in "Create EER Model From SQL Script" of MWB 5.2.37 for Windows.

Locking a file in Python

Alright, so I ended up going with the code I wrote here, on my website link is dead, view on archive.org (also available on GitHub). I can use it in the following fashion:

from filelock import FileLock

with FileLock("myfile.txt.lock"):
    print("Lock acquired.")
    with open("myfile.txt"):
        # work with the file as it is now locked

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

Loop through Map in Groovy?

Another option:

def map = ['a':1, 'b':2, 'c':3]
map.each{
  println it.key +" "+ it.value
}

Filter array to have unique values

_x000D_
_x000D_
arr = ["I", "do", "love", "JavaScript", "and", "I", "also", "do", "love", "Java"];_x000D_
_x000D_
uniqueArr = [... new Set(arr)];_x000D_
_x000D_
// or_x000D_
_x000D_
reallyUniqueArr = arr.filter((item, pos, ar) => ar.indexOf(item) === pos)_x000D_
_x000D_
console.log(`${uniqueArr}\n${reallyUniqueArr}`)
_x000D_
_x000D_
_x000D_

How to change Bootstrap's global default font size?

The recommended way to do this from the current v4 docs is:

$font-size-base: 0.8rem;
$line-height-base: 1;

Be sure to define the variables above the bootstrap css include and they will override the bootstrap.

No need for anything else and this is the cleanest way

It's described quite clearly in the docs https://getbootstrap.com/docs/4.1/content/typography/#global-settings

How to vertically align text in input type="text"?

IF vertical align won't work use padding. padding-top: 10px; it will shift the text to the bottom or padding-bottom: 10px; to shift the text in the text box to top

adjust the padding size till it suit the size you want. Thats the hack

Preventing multiple clicks on button

I found this solution that is simple and worked for me:

<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>

This solution was found in: Original solution

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Happend to me when i took my first first walking attempts with IntelliTest in VS 2017.

Sometimes, when the test project gets auto-created by IntelliTest, the assembly reference to Microsoft.ExtendedReflection (...\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Pex\Microsoft.ExtendedReflection.dll) is missing. When added, the generated Tests will show up in test explorer after recompile.

How to list npm user-installed packages?

To see list of all packages that are installed.

$ npm ls --parseable | awk '{gsub(/\/.*\//,"",$1); print}'| sort -u

show parseable of npm packages list https://docs.npmjs.com/cli/ls#parseable

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

MySQL: When is Flush Privileges in MySQL really needed?

TL;DR

You should use FLUSH PRIVILEGES; only if you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE.

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

Failed to execute 'createObjectURL' on 'URL':

Video with fall back:

try {
  video.srcObject = mediaSource;
} catch (error) {
  video.src = URL.createObjectURL(mediaSource);
}
video.play();

From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject

Find package name for Android apps to use Intent to launch Market app from web

Once you have the package name, as described Chris Smith's answer, you could/should use an intent url for the link. It's a special format URL that will launch the package if the user has already installed it, or open the play store at the application's page if not...

intent://#Intent;package=qualified.package.name;end

The app needs to support this, with an activity tagged as browsable, but many will.

Picking a random element from a set

For fun I wrote a RandomHashSet based on rejection sampling. It's a bit hacky, since HashMap doesn't let us access it's table directly, but it should work just fine.

It doesn't use any extra memory, and lookup time is O(1) amortized. (Because java HashTable is dense).

class RandomHashSet<V> extends AbstractSet<V> {
    private Map<Object,V> map = new HashMap<>();
    public boolean add(V v) {
        return map.put(new WrapKey<V>(v),v) == null;
    }
    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {
            RandKey key = new RandKey();
            @Override public boolean hasNext() {
                return true;
            }
            @Override public V next() {
                while (true) {
                    key.next();
                    V v = map.get(key);
                    if (v != null)
                        return v;
                }
            }
            @Override public void remove() {
                throw new NotImplementedException();
            }
        };
    }
    @Override
    public int size() {
        return map.size();
    }
    static class WrapKey<V> {
        private V v;
        WrapKey(V v) {
            this.v = v;
        }
        @Override public int hashCode() {
            return v.hashCode();
        }
        @Override public boolean equals(Object o) {
            if (o instanceof RandKey)
                return true;
            return v.equals(o);
        }
    }
    static class RandKey {
        private Random rand = new Random();
        int key = rand.nextInt();
        public void next() {
            key = rand.nextInt();
        }
        @Override public int hashCode() {
            return key;
        }
        @Override public boolean equals(Object o) {
            return true;
        }
    }
}

Why is it not advisable to have the database and web server on the same machine?

I agree with Daniel Earwicker - the security question is pretty much flawed.

If you have a single box setup with a webserver and only the database for that webserver on it, if that webserver is compromised you lose both the webserver and only the database for that specific application.

This is exactly the same as what happens if you lose the webserver on a 2-server setup. You lose the web server, and just the database for that specific application.

The argument that 'the rest of the DB server's integrity is maintained' where you have a 2-server setup is irrelevant, because in the first scenario, every other database server relating to every other application (if there are any) remain unaffected as well - being, as they are, hosted elsewhere.

Similarly, to the question posed by Kev 'what about all the other databases residing on the DB server? All you've lost is one database.'

  • if you were hosting an application and database on one server, you would only host databases on that server which related to that application. Therefore, you would not lose any additional databases in a single server setup when compared to a multiple server setup.

By contrast, in a 2 server setup, where the attacker had access to the Web Server, and by proxy, limited rights (in the best case scenario) to the database server, they could put the databases of every other application at risk by carrying out slow, memory intensive queries or maximising the available storage space on the database server. By separating the applications out into their own concerns, very much like virtualisation, you also isolate them for security purposes in a positive way.

What’s the best RESTful method to return total number of items in an object?

I prefer using HTTP Headers for this kind of contextual information.

For the total number of elements, I use the X-total-count header.
For links to next, previous page, etc. I use HTTP Link header:
http://www.w3.org/wiki/LinkHeader

Github does it the same way: https://developer.github.com/v3/#pagination

In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

Inner text shadow with CSS

Try this little gem of a variation:

text-shadow:0 1px 1px rgba(255, 255, 255, 0.5);

I usually take "there's no answer" as a challenge

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

Recursive directory listing in DOS

You can use various options with FINDSTR to remove the lines do not want, like so:

DIR /S | FINDSTR "\-" | FINDSTR /VI DIR

Normal output contains entries like these:

28-Aug-14  05:14 PM    <DIR>          .
28-Aug-14  05:14 PM    <DIR>          ..

You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

What does the "On Error Resume Next" statement do?

It means, when an error happens on the line, it is telling vbscript to continue execution without aborting the script. Sometimes, the On Error follows the Goto label to alter the flow of execution, something like this in a Sub code block, now you know why and how the usage of GOTO can result in spaghetti code:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB code...

   REM More VB Code...

Exit_MySubRoutine:

   REM Disable the Error Handler!

   On Error Goto 0

   REM Leave....
   Exit Sub

ErrorHandler:

   REM Do something about the Error

   Goto Exit_MySubRoutine
End Sub

Insert line after first match using sed

A POSIX compliant one using the s command:

sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file

Add onclick event to newly added element in JavaScript

In case you do not want to write all the code you have once written in the function you called. Please use the following code, using jQuery:

$(element).on('click', function () { add_img(); });

creating a random number using MYSQL

You could create a random number using FLOOR(RAND() * n) as randnum (n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)...

How do I get AWS_ACCESS_KEY_ID for Amazon?

  1. Open the AWS Console
  2. Click on your username near the top right and select My Security Credentials
  3. Click on Users in the sidebar
  4. Click on your username
  5. Click on the Security Credentials tab
  6. Click Create Access Key
  7. Click Show User Security Credentials

There are No resources that can be added or removed from the server

The only thing that worked for me was creating a

.java-version

file with "oracle64-1.8.0.112" as the only entry ( use something that is 1.6+ )

Make sure you have dynamic web module facet turned on.

Python function to convert seconds into minutes, hours, and days

These functions are fairly compact and only use standard Python 2.6 and later.

def ddhhmmss(seconds):
    """Convert seconds to a time string "[[[DD:]HH:]MM:]SS".
    """
    dhms = ''
    for scale in 86400, 3600, 60:
        result, seconds = divmod(seconds, scale)
        if dhms != '' or result > 0:
            dhms += '{0:02d}:'.format(result)
    dhms += '{0:02d}'.format(seconds)
    return dhms


def seconds(dhms):
    """Convert a time string "[[[DD:]HH:]MM:]SS" to seconds.
    """
    components = [int(i) for i in dhms.split(':')]
    pad = 4 - len(components)
    if pad < 0:
        raise ValueError('Too many components to match [[[DD:]HH:]MM:]SS')
    components = [0] * pad + components
    return sum(i * j for i, j in zip((86400, 3600, 60, 1), components))

And here are tests to go with them. I'm using the pytest package as a simple way to test exceptions.

import ddhhmmss

import pytest


def test_ddhhmmss():
    assert ddhhmmss.ddhhmmss(0) == '00'
    assert ddhhmmss.ddhhmmss(2) == '02'
    assert ddhhmmss.ddhhmmss(12 * 60) == '12:00'
    assert ddhhmmss.ddhhmmss(3600) == '01:00:00'
    assert ddhhmmss.ddhhmmss(10 * 86400) == '10:00:00:00'
    assert ddhhmmss.ddhhmmss(86400 + 5 * 3600 + 30 * 60 + 1) == '01:05:30:01'
    assert ddhhmmss.ddhhmmss(365 * 86400) == '365:00:00:00'


def test_seconds():
    assert ddhhmmss.seconds('00') == 0
    assert ddhhmmss.seconds('02') == 2
    assert ddhhmmss.seconds('12:00') == 12 * 60
    assert ddhhmmss.seconds('01:00:00') == 3600
    assert ddhhmmss.seconds('1:0:0') == 3600
    assert ddhhmmss.seconds('3600') == 3600
    assert ddhhmmss.seconds('60:0') == 3600
    assert ddhhmmss.seconds('10:00:00:00') == 10 * 86400
    assert ddhhmmss.seconds('1:05:30:01') == 86400 + 5 * 3600 + 30 * 60 + 1
    assert ddhhmmss.seconds('365:00:00:00') == 365 * 86400


def test_seconds_raises():
    with pytest.raises(ValueError):
        ddhhmmss.seconds('')
    with pytest.raises(ValueError):
        ddhhmmss.seconds('foo')
    with pytest.raises(ValueError):
        ddhhmmss.seconds('1:00:00:00:00')

How to remove default mouse-over effect on WPF buttons?

This Link helped me alot http://www.codescratcher.com/wpf/remove-default-mouse-over-effect-on-wpf-buttons/

Define a style in UserControl.Resources or Window.Resources

 <Window.Resources>
        <Style x:Key="MyButton" TargetType="Button">
            <Setter Property="OverridesDefaultStyle" Value="True" />
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Opacity" Value="0.8" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

Then add the style to your button this way Style="{StaticResource MyButton}"

<Button Name="btnSecond" Width="350" Height="120" Margin="15" Style="{StaticResource MyButton}">
    <Button.Background>
        <ImageBrush ImageSource="/Remove_Default_Button_Effect;component/Images/WithStyle.jpg"></ImageBrush>
    </Button.Background>
</Button>

How to tell if a string is not defined in a Bash shell script

~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~> 

-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

Alternate word:

~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED

Default value:

~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED

Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

How to disable JavaScript in Chrome Developer Tools?

The fast way:

1) just click on CTRL + SHIFT + P

2) fill the field by the 3 letters dis and will appear this box and select the item Disable Javascript

disable javascript .

that's all folks!

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

adding onclick event to dynamically added button?

This code work good to me and look more simple. Necessary to call a function with specific parameter.

var btn = document.createElement("BUTTON");  //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);   

btn.onclick = function(){myFunction(myparameter)};  
document.getElementById("myView").appendChild(btn);//to show on myView

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

What is a lambda (function)?

A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.

For instance, here's a C# piece of code that doesn't use a lambda:

public Int32 Add(Int32 a, Int32 b)
{
    return a + b;
}

public Int32 Sub(Int32 a, Int32 b)
{
    return a - b;
}

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, Add);
    Calculator(10, 23, Sub);
}

This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.

In C# 2.0 we got anonymous methods, which shortens the above code to:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a + b;
    });
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a - b;
    });
}

And then in C# 3.0 we got lambdas which makes the code even shorter:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, (a, b) => a + b);
    Calculator(10, 23, (a, b) => a - b);
}

Remove the title bar in Windows Forms

Set FormsBorderStyle of the Form to None.

If you do, it's up to you how to implement the dragging and closing functionality of the window.

What are the benefits of using C# vs F# or F# vs C#?

You're asking for a comparison between a procedural language and a functional language so I feel your question can be answered here: What is the difference between procedural programming and functional programming?

As to why MS created F# the answer is simply: Creating a functional language with access to the .Net library simply expanded their market base. And seeing how the syntax is nearly identical to OCaml, it really didn't require much effort on their part.

What's the difference between KeyDown and KeyPress in .NET?

Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.

Put another way, KeyDown + KeyUp = Keypress

How to get the start time of a long-running Linux process?

ls -ltrh /proc | grep YOUR-PID-HERE

For example, my Google Chrome's PID is 11583:

ls -l /proc | grep 11583
dr-xr-xr-x  7 adam       adam                     0 2011-04-20 16:34 11583

Getting list of items inside div using Selenium Webdriver

alternatively, you can try writing a specific element:

    //label[1] is the first element.
    el =  await driver.findElement(By.xpath("//div[@class=\"facetContainerDiv\"]/div/label[1]/input")));
    await el.click();

More information can be found here: https://www.browserstack.com/guide/locators-in-selenium

How to generate random positive and negative numbers in Java

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

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

Perfectly simple use of aggregate (equivalent to fold in other languages):

var firstBorn = People.Aggregate((min, x) => x.DateOfBirth < min.DateOfBirth ? x : min);

The only downside is that the property is accessed twice per sequence element, which might be expensive. That's hard to fix.

Increase permgen space

You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.

Using Git, show all commits that are in one branch, but not the other(s)

I'd like to count the commits too, so here's how to do that:

Count how many commits are on the current branch (HEAD), but NOT on master:

git log --oneline ^master HEAD | wc -l

wc -l means "word count"--count the number of 'l'ines.

And of course to see the whole log messages, as other answers have given:

git log ^master HEAD

...or in a condensed --oneline form:

git log --oneline ^master HEAD

If you don't want to count merge commits either, you can exclude those with --no-merges:

git log --oneline --no-merges ^master HEAD | wc -l

etc.

Git merge reports "Already up-to-date" though there is a difference

The message “Already up-to-date” means that all the changes from the branch you’re trying to merge have already been merged to the branch you’re currently on. More specifically it means that the branch you’re trying to merge is a parent of your current branch. Congratulations, that’s the easiest merge you’ll ever do. :)

Use gitk to take a look at your repository. The label for the “test” branch should be somewhere below your “master” branch label.

Your branch is up-to-date with respect to its parent. According to merge there are no new changes in the parent since the last merge. That does not mean the branches are the same, because you can have plenty of changes in your working branch and it sounds like you do.

Edit 10/12/2019:

Per Charles Drake in the comment to this answer, one solution to remediate the problem is:

git checkout master
git reset --hard test

This brings it back to the 'test' level.

Then do:

git push --force origin master

in order to force changes back to the central repo.

Scala how can I count the number of occurrences in a list

list.groupBy(i=>i).mapValues(_.size)

gives

Map[Int, Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)

Note that you can replace (i=>i) with built in identity function:

list.groupBy(identity).mapValues(_.size)

AttributeError: can't set attribute in python

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

Does C# have an equivalent to JavaScript's encodeURIComponent()?

Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.

How to clear the entire array?

You can either use the Erase or ReDim statements to clear the array. Examples of each are shown in the MSDN documentation. For example:

Dim threeDimArray(9, 9, 9), twoDimArray(9, 9) As Integer
Erase threeDimArray, twoDimArray
ReDim threeDimArray(4, 4, 9)

To remove a collection, you iterate over its items and use the Remove method:

For i = 1 to MyCollection.Count
  MyCollection.Remove 1 ' Remove first item
Next i

Convert Variable Name to String?

Here is a succinct variation that lets you specify any directory. The issue with using directories to find anything is that multiple variables can have the same value. So this code returns a list of possible variables.

def varname( var, dir=locals()):
  return [ key for key, val in dir.items() if id( val) == id( var)]

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

Find and Replace text in the entire table using a MySQL query

Put this in a php file and run it and it should do what you want it to do.

// Connect to your MySQL database.
$hostname = "localhost";
$username = "db_username";
$password = "db_password";
$database = "db_name";

mysql_connect($hostname, $username, $password);

// The find and replace strings.
$find = "find_this_text";
$replace = "replace_with_this_text";

$loop = mysql_query("
    SELECT
        concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
    FROM
        information_schema.columns
    WHERE
        table_schema = '{$database}'")
or die ('Cant loop through dbfields: ' . mysql_error());

while ($query = mysql_fetch_assoc($loop))
{
        mysql_query($query['s']);
}

How to completely uninstall kubernetes

In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):

kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*   
sudo apt-get autoremove  
sudo rm -rf ~/.kube

And restart the computer.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I think the right way to find the internal Java used by the Android Studio is to

  1. Open Android Studio
  2. Go to File->Other Settings->Default Project Structure/JDK Location:
  3. and copy what ever string is specified there

This will not require memorising the folder or searching for java and also these steps wil take of any future changes to the java location by the Android Studio team changes I suppose

How to fire an event when v-model changes?

This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input 
  type="radio" 
  name="optionsRadios" 
  id="optionsRadios2" 
  value=""
  v-model="srStatus" 
  v-on:change="foo"> //here

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){
    foo();
},

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

What is the "right" way to iterate through an array in Ruby?

The other answers are just fine, but I wanted to point out one other peripheral thing: Arrays are ordered, whereas Hashes are not in 1.8. (In Ruby 1.9, Hashes are ordered by insertion order of keys.) So it wouldn't make sense prior to 1.9 to iterate over a Hash in the same way/sequence as Arrays, which have always had a definite ordering. I don't know what the default order is for PHP associative arrays (apparently my google fu isn't strong enough to figure that out, either), but I don't know how you can consider regular PHP arrays and PHP associative arrays to be "the same" in this context, since the order for associative arrays seems undefined.

As such, the Ruby way seems more clear and intuitive to me. :)

What is the difference between sscanf or atoi to convert a string to an integer?

If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

How to find sum of multiple columns in a table in SQL Server 2005?

You must also be aware of null records:

SELECT  (ISNULL(Val1,0) + ISNULL(Val2,0) + ISNULL(Val3,0)) as 'Total'
FROM Emp

Usage of ISNULL:

ISNULL(col_Name, replace value)

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

... Could not load file or assembly 'X' or one of its dependencies ...

Most likely it fails to load another dependency.

you could try to check the dependencies with a dependency walker.

I.e: https://www.dependencywalker.com/

Also check your build configuration (x86 / 64)

Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.

See here: Detected DLLs that are from the internet and "blocked" by CASPOL

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

TCPDF Save file to folder?

If you still get

TCPDF ERROR: Unable to create output file: myfile.pdf

you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:

$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);

Failed to find target with hash string 'android-25'

I had similar issue for android-29. My issue occurred because when AS was unzipping one downloaded SDK I had stopped it. For solving the issue disable gradle offline mode then sync with gradle files. You may need to set proxy and enable it.

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]
    </div>
</div>

Css:

.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    </div>_x000D_
_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
    quidem._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/M5cTN/

Get the cell value of a GridView row

Have you tried Cell[0]? Remember indexes start at 0, not 1.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Just write

print_r($myarray); //it will display you content of an array $myarray

exit(); //it will not execute further codes after displaying your array

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

How to compare DateTime in C#?

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.


The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

Equality:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

bash export command

if u cant use " export " cmd
then Just use:

setenv path /dir

like this

setenv ORACLE_HOME /data/u01/apps/oracle/11.2.0.3.0

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

Create Test Class in IntelliJ

Alternatively you could also position the cursor onto the class name and press alt+enter (Show intention actions and quick fixes). It will suggest to Create Test.

At least works in IDEA version 12.

jQuery show/hide not working

Just add the document ready function, this way it waits until the DOM has been loaded, also by using the :visible pseudo you can write a simple show and hide function.

Sample

 $(document).ready(function(){

    $( '.expand' ).click(function() {
         if($( '.img_display_content' ).is(":visible")){
              $( '.img_display_content' ).hide();
         } else{
              $( '.img_display_content' ).show();
         }

    });
});

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

How can I configure my makefile for debug and release builds?

Completing the answers from earlier... You need to reference the variables you define info in your commands...

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

all: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

CommandParser.tab.o: CommandParser.y
    bison -d CommandParser.y
    $(CXX) -c CommandParser.tab.c

Command.o: Command.cpp
    $(CXX) -c Command.cpp

clean:
    rm -f CommandParser.tab.* CommandParser.yy.* output *.o

How can I access global variable inside class in Python

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.

How to call a Web Service Method?

James' answer is correct, of course, but I should remind you that the whole ASMX thing is, if not obsolete, at least not the current method. I strongly suggest that you look into WCF, if only to avoid learning things you will need to forget.

favicon not working in IE

Care to share the URL? Many browsers cope with favicons in (e.g.) png format while IE had often troubles. - Also older versions of IE did not check the html source for the location of the favicon but just single-mindedly tried to get "/favicon.ico" from the webserver.

Angular - Set headers for every request

There were some changes for angular 2.0.1 and higher:

    import {RequestOptions, RequestMethod, Headers} from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule }     from '@angular/http';
    import { AppRoutingModule } from './app.routing.module';   
    import { AppComponent }  from './app.component';

    //you can move this class to a better place
    class GlobalHttpOptions extends RequestOptions {
        constructor() { 
          super({ 
            method: RequestMethod.Get,
            headers: new Headers({
              'MyHeader': 'MyHeaderValue',
            })
          });
        }
      }

    @NgModule({

      imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
      declarations: [ AppComponent],
      bootstrap:    [ AppComponent ],
      providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
    })

    export class AppModule { }

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

LIMIT 10..20 in SQL Server

From the MS SQL Server online documentation (http://technet.microsoft.com/en-us/library/ms186734.aspx ), here is their example that I have tested and works, for retrieving a specific set of rows. ROW_NUMBER requires an OVER, but you can order by whatever you like:

WITH OrderedOrders AS
(
  SELECT SalesOrderID, OrderDate,
  ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
  FROM Sales.SalesOrderHeader 
) 
SELECT SalesOrderID, OrderDate, RowNumber  
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60;

How to build an APK file in Eclipse?

When you run your application, your phone should be detected and you should be given the option to run on your phone instead of on the emulator.

More instructions on getting your phone recognized: http://developer.android.com/guide/developing/device.html

When you want to export a signed version of the APK file (for uploading to the market or putting on a website), right-click on the project in Eclipse, choose export, and then choose "Export Android Application".

More details: http://developer.android.com/guide/publishing/app-signing.html#ExportWizard

Can I dispatch an action in reducer?

You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

How to change onClick handler dynamically?

I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:

document.getElementById("foo").onclick = function (event){alert('foo');};

or in jQuery:

$('#foo').click(function(event) { alert('foo'); }