Programs & Examples On #Defaultmodelbinder

0

An item with the same key has already been added

I had a similar problem and found that it was because I had a similarly named public property (that should have been private) that only differed in case.

public string PropertyName {get;set;} // actually set propertyName, get propertyName
public string propertyName {get;set;}

should have been

public string PropertyName {get;set;} 
private string propertyName {get;set;}

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

add javax.xml.bind dependency in pom.xml

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>

View RDD contents in Python Spark?

By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)

https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html

To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

Add quotation at the start and end of each line in Notepad++

You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:

  1. Find (in regular expression mode):

    (.+)
    

    Replace with:

    "\1"
    

    This adds the quotes:

    "AliceBlue"
    "AntiqueWhite"
    "Aqua"
    "Aquamarine"
    "Azure"
    "Beige"
    "Bisque"
    "Black"
    "BlanchedAlmond"
    
  2. Find (in extended mode):

    \r\n
    

    Replace with (with a space after the comma, not shown):

    , 
    

    This converts the lines into a comma-separated list:

    "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
    

  3. Add the var myArray = assignment and braces manually:

    var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
    

PHP array delete by value (not key)

If you don't know its key it means it doesn't matter.

You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

How to access random item in list?

I usually use this little collection of extension methods:

public static class EnumerableExtension
{
    public static T PickRandom<T>(this IEnumerable<T> source)
    {
        return source.PickRandom(1).Single();
    }

    public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
    {
        return source.Shuffle().Take(count);
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.OrderBy(x => Guid.NewGuid());
    }
}

For a strongly typed list, this would allow you to write:

var strings = new List<string>();
var randomString = strings.PickRandom();

If all you have is an ArrayList, you can cast it:

var strings = myArrayList.Cast<string>();

How to hide navigation bar permanently in android activity?

For people looking at a simpler solution, I think you can just have this one line of code in onStart()

  getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

It's called Immersive mode. You may look at the official documentation for other possibilities.

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

How to create a POJO?

POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.

Properties of POJO

  1. All properties must be public setter and getter methods
  2. All instance variables should be private
  3. Should not Extend prespecified classes.
  4. Should not Implement prespecified interfaces.
  5. Should not contain prespecified annotations.
  6. It may not have any argument constructors

Example of POJO

public class POJO {

    private String value;

    public String getValue() {
         return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

how to remove pagination in datatable

if you want to remove pagination and but want ordering of dataTable then add this script at the end of your page!

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function() {        _x000D_
    $('#table_id').DataTable({_x000D_
        "paging":   false,_x000D_
       "info":     false_x000D_
    } );_x000D_
      _x000D_
  } );_x000D_
</script>
_x000D_
_x000D_
_x000D_

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:

driver.manage().timeouts().implicitlyWait( ... )

How to display .svg image using swift

SVG file support is added to Xcode 12.

enter image description here

Declare and initialize a Dictionary in Typescript

For using dictionary object in typescript you can use interface as below:

interface Dictionary<T> {
    [Key: string]: T;
}

and, use this for your class property type.

export class SearchParameters {
    SearchFor: Dictionary<string> = {};
}

to use and initialize this class,

getUsers(): Observable<any> {
        var searchParams = new SearchParameters();
        searchParams.SearchFor['userId'] = '1';
        searchParams.SearchFor['userName'] = 'xyz';

        return this.http.post(searchParams, 'users/search')
            .map(res => {
                return res;
            })
            .catch(this.handleError.bind(this));
    }

Executing Javascript code "on the spot" in Chrome?

I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.

Python speed testing - Time Difference - milliseconds

You could use timeit like this to test a script named module.py

$ python -mtimeit -s 'import module'

Hide text using css

Do not use { display:none; } It makes the content inaccessible. You want screen-readers to see your content, and visually style it by replacing the text with an image (like a logo). By using text-indent: -999px; or a similar method, the text is still there — just not visually there. Use display:none, and the text is gone.

Installing SetupTools on 64-bit Windows

Create a file named python2.7.reg (registry file) and put this content into it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\MainPythonDocumentation]
@="C:\\Python27\\Doc\\python26.chm"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"

And make sure every path is right!

Then run (merge) it and done :)

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would break up

public static void main(String args[])

in parts:

public

It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in your current class.


static

When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.


void

Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.


main

It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.


String args[]

These are the arguments of type String that your Java application accepts when you run it.

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

Use PHP to convert PNG to JPG with compression?

I know it's not an exact answer to the OP, but as answers have already be given...

Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit, max_execution_time, ...

I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )

Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)

You'd have to write a shell-script that goes through all .png files, and gives them to either

  • convert to create a new .jpg file for each .png file
  • or mogrify to directly work on the original file and override it.


As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^


I've use the shell script + convert/mogrify a few times (having them run for something like 10 hours one time), and they do the job really well :-)

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

How can I make my match non greedy in vim?

If you're more comfortable PCRE regex syntax, which

  1. supports the non-greedy operator ?, as you asked in OP; and
  2. doesn't require backwhacking grouping and cardinality operators (an utterly counterintuitive vim syntax requirement since you're not matching literal characters but specifying operators); and
  3. you have [g]vim compiled with perl feature, test using

    :ver and inspect features; if +perl is there you're good to go)

try search/replace using

:perldo s///

Example. Swap src and alt attributes in img tag:

<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>

:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/

<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>

SDK Location not found Android Studio + Gradle

I noticed that I get this error when I'm working on a new computer if I try to build from the command line first. However, if I build from Android Studio, it retrieves the SDK and creates the directory automatically. Then when I build from the command line it works.

How can I make a thumbnail <img> show a full size image when clicked?

The

<a href="image2.gif" ><img src="image1.gif"/></a>

technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

difference between variables inside and outside of __init__()

Example code:

class inside:
    def __init__(self):
        self.l = []

    def insert(self, element):
        self.l.append(element)


class outside:
    l = []             # static variable - the same for all instances

    def insert(self, element):
        self.l.append(element)


def main():
    x = inside()
    x.insert(8)
    print(x.l)      # [8]
    y = inside()
    print(y.l)      # []
    # ----------------------------
    x = outside()
    x.insert(8)
    print(x.l)      # [8]
    y = outside()
    print(y.l)      # [8]           # here is the difference


if __name__ == '__main__':
    main()

getString Outside of a Context or Activity

I used getContext().getApplicationContext().getString(R.string.nameOfString); It works for me.

How to loop through a plain JavaScript object with the objects as members?

I think it's worth pointing out that jQuery sorts this out nicely with $.each().

See: .each()

Example:

$('.foo').each(function() {
    console.log($(this));
});

$(this) being the single item inside the object. Swap $('.foo') to a variable if you don't want to use jQuery's selector engine.

The remote end hung up unexpectedly while git cloning

This worked for me, setting up Googles nameserver because no standard nameserver was specified, followed by restarting networking:

sudo echo "dns-nameservers 8.8.8.8" >> /etc/network/interfaces && sudo ifdown venet0:0 && sudo ifup venet0:0

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

R define dimensions of empty data frame

df = data.frame(matrix("", ncol = 3, nrow = 10)  

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);

Colors in JavaScript console

I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}.

This worked like a charm:

var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
    if (/^\{/.test(split)) {
        cssRules.push('color:blue');
    } else {
        cssRules.push('color:inherit')
    }
    styledText += `%c${split} `
});
console.log(styledText , ...cssRules)

enter image description here

technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons

Nesting await in Parallel.ForEach

Wrap the Parallel.Foreach into a Task.Run() and instead of the await keyword use [yourasyncmethod].Result

(you need to do the Task.Run thing to not block the UI thread)

Something like this:

var yourForeachTask = Task.Run(() =>
        {
            Parallel.ForEach(ids, i =>
            {
                ICustomerRepo repo = new CustomerRepo();
                var cust = repo.GetCustomer(i).Result;
                customers.Add(cust);
            });
        });
await yourForeachTask;

How to find time complexity of an algorithm

When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.

For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.

Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:

  • Constant time has an order of growth 1, for example: a = b + c.

  • Logarithmic time has an order of growth LogN, it usually occurs when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.

  • Linear, order of growth is N, for example

    int p = 0;
    for (int i = 1; i < N; i++)
      p = p + 2;
    
  • Linearithmic, order of growth is n*logN, usually occurs in divide and conquer algorithms.

  • Cubic, order of growth N^3, classic example is a triple loop where you check all triplets:

    int x = 0;
    for (int i = 0; i < N; i++)
       for (int j = 0; j < N; j++)
          for (int k = 0; k < N; k++)
              x = x + 2
    
  • Exponential, order of growth 2^N, usually occurs when you do exhaustive search, for example check subsets of some set.

How do you reinstall an app's dependencies using npm?

The right way is to execute npm update. It's a really powerful command, it updates the missing packages and also checks if a newer version of package already installed can be used.

Read Intro to NPM to understand what you can do with npm.

RelativeLayout center vertical

use

 android:layout_centerVertical="true"

Calling a php function by onclick event

Use this html code it will surely help you

<input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />

one limitation is that it is taking more time to run so wait for few seconds it will work

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

Symfony2 Setting a default choice field selection

I think you should simply use $breed->setSpecies($species), for instance in my form I have:

$m = new Member();
$m->setBirthDate(new \DateTime);
$form = $this->createForm(new MemberType, $m);

and that sets my default selection to the current date. Should work the same way for external entities...

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

How to set editable true/false EditText in Android programmatically?

Fetch the KeyListener value of EditText by editText.getKeyListener() and store in the KeyListener type variable, which will contain the Editable property value:

KeyListener variable;
variable = editText.getKeyListener(); 

Set the Editable property of EditText to false as:

 edittext.setKeyListener(null);

Now set Editable property of EditText to true as:

editText.setKeyListener(variable);  

Note: In XML the default Editable property of EditText should be true.

Java get String CompareTo as a comparator object

The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

Copying HTML code in Google Chrome's inspect element

Do the following:

  1. Select the top most element, you want to copy. (To copy all, select <html>)
  2. Right click.
  3. Select Edit as HTML
  4. New sub-window opens up with the HTML text.
  5. This is your chance. Press CTRL+A/CTRL+C and copy the entire text field to a different window.

This is a hacky way, but it's the easiest way to do this.

How do you force a makefile to rebuild a target

You could declare one or more of your targets to be phony.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

...

A phony target should not be a prerequisite of a real target file; if it is, its recipe will be run every time make goes to update that file. As long as a phony target is never a prerequisite of a real target, the phony target recipe will be executed only when the phony target is a specified goal

How to get the file name from a full path using JavaScript?

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

var leafname= pathname.split('\\').pop().split('/').pop();

Reset ID autoincrement ? phpmyadmin

I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

Joining two lists together

The two options I use are:

list1.AddRange(list2);

or

list1.Concat(list2);

However I noticed as I used that when using the AddRange method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.

(Message Google Translated)
The array dimensions exceeded the supported range.

Using Concat solved that issue.

Using union and order by clause in mysql

This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause

Calculate distance between two latitude-longitude points? (Haversine formula)

You can use the build in CLLocationDistance to calculate this:

CLLocation *location1 = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];
[self distanceInMetersFromLocation:location1 toLocation:location2]

- (int)distanceInMetersFromLocation:(CLLocation*)location1 toLocation:(CLLocation*)location2 {
    CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];
    return distanceInMeters;
}

In your case if you want kilometers just divide by 1000.

Asking the user for input until they give a valid response

Functional approach or "look mum no loops!":

from itertools import chain, repeat

prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number:  a
Not a number! Try again:  b
Not a number! Try again:  1
1

or if you want to have a "bad input" message separated from an input prompt as in other answers:

prompt_msg = "Enter a number: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number:  a
Sorry, I didn't understand that.
Enter a number:  b
Sorry, I didn't understand that.
Enter a number:  1
1

How does it work?

  1. prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
    
    This combination of itertools.chain and itertools.repeat will create an iterator which will yield strings "Enter a number: " once, and "Not a number! Try again: " an infinite number of times:
    for prompt in prompts:
        print(prompt)
    
    Enter a number: 
    Not a number! Try again: 
    Not a number! Try again: 
    Not a number! Try again: 
    # ... and so on
    
  2. replies = map(input, prompts) - here map will apply all the prompts strings from the previous step to the input function. E.g.:
    for reply in replies:
        print(reply)
    
    Enter a number:  a
    a
    Not a number! Try again:  1
    1
    Not a number! Try again:  it doesn't care now
    it doesn't care now
    # and so on...
    
  3. We use filter and str.isdigit to filter out those strings that contain only digits:
    only_digits = filter(str.isdigit, replies)
    for reply in only_digits:
        print(reply)
    
    Enter a number:  a
    Not a number! Try again:  1
    1
    Not a number! Try again:  2
    2
    Not a number! Try again:  b
    Not a number! Try again: # and so on...
    
    And to get only the first digits-only string we use next.

Other validation rules:

  1. String methods: Of course you can use other string methods like str.isalpha to get only alphabetic strings, or str.isupper to get only uppercase. See docs for the full list.

  2. Membership testing:
    There are several different ways to perform it. One of them is by using __contains__ method:

    from itertools import chain, repeat
    
    fruits = {'apple', 'orange', 'peach'}
    prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
    replies = map(input, prompts)
    valid_response = next(filter(fruits.__contains__, replies))
    print(valid_response)
    
    Enter a fruit:  1
    I don't know this one! Try again:  foo
    I don't know this one! Try again:  apple
    apple
    
  3. Numbers comparison:
    There are useful comparison methods which we can use here. For example, for __lt__ (<):

    from itertools import chain, repeat
    
    prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:"))
    replies = map(input, prompts)
    numeric_strings = filter(str.isnumeric, replies)
    numbers = map(float, numeric_strings)
    is_positive = (0.).__lt__
    valid_response = next(filter(is_positive, numbers))
    print(valid_response)
    
    Enter a positive number: a
    I need a positive number! Try again: -5
    I need a positive number! Try again: 0
    I need a positive number! Try again: 5
    5.0
    

    Or, if you don't like using dunder methods (dunder = double-underscore), you can always define your own function, or use the ones from the operator module.

  4. Path existance:
    Here one can use pathlib library and its Path.exists method:

    from itertools import chain, repeat
    from pathlib import Path
    
    prompts = chain(["Enter a path: "], repeat("This path doesn't exist! Try again: "))
    replies = map(input, prompts)
    paths = map(Path, replies)
    valid_response = next(filter(Path.exists, paths))
    print(valid_response)
    
    Enter a path:  a b c
    This path doesn't exist! Try again:  1
    This path doesn't exist! Try again:  existing_file.txt
    existing_file.txt
    

Limiting number of tries:

If you don't want to torture a user by asking him something an infinite number of times, you can specify a limit in a call of itertools.repeat. This can be combined with providing a default value to the next function:

from itertools import chain, repeat

prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies), None)
print("You've failed miserably!" if valid_response is None else 'Well done!')
Enter a number: a
Not a number! Try again: b
Not a number! Try again: c
You've failed miserably!

Preprocessing input data:

Sometimes we don't want to reject an input if the user accidentally supplied it IN CAPS or with a space in the beginning or an end of the string. To take these simple mistakes into account we can preprocess the input data by applying str.lower and str.strip methods. For example, for the case of membership testing the code will look like this:

from itertools import chain, repeat

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
lowercased_replies = map(str.lower, replies)
stripped_replies = map(str.strip, lowercased_replies)
valid_response = next(filter(fruits.__contains__, stripped_replies))
print(valid_response)
Enter a fruit:  duck
I don't know this one! Try again:     Orange
orange

In the case when you have many functions to use for preprocessing, it might be easier to use a function performing a function composition. For example, using the one from here:

from itertools import chain, repeat

from lz.functional import compose

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
process = compose(str.strip, str.lower)  # you can add more functions here
processed_replies = map(process, replies)
valid_response = next(filter(fruits.__contains__, processed_replies))
print(valid_response)
Enter a fruit:  potato
I don't know this one! Try again:   PEACH
peach

Combining validation rules:

For a simple case, for example, when the program asks for age between 1 and 120, one can just add another filter:

from itertools import chain, repeat

prompt_msg = "Enter your age (1-120): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
numeric_replies = filter(str.isdigit, replies)
ages = map(int, numeric_replies)
positive_ages = filter((0).__lt__, ages)
not_too_big_ages = filter((120).__ge__, positive_ages)
valid_response = next(not_too_big_ages)
print(valid_response)

But in the case when there are many rules, it's better to implement a function performing a logical conjunction. In the following example I will use a ready one from here:

from functools import partial
from itertools import chain, repeat

from lz.logical import conjoin


def is_one_letter(string: str) -> bool:
    return len(string) == 1


rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__]

prompt_msg = "Enter a letter (C-P): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(conjoin(*rules), replies))
print(valid_response)
Enter a letter (C-P):  5
Wrong input.
Enter a letter (C-P):  f
Wrong input.
Enter a letter (C-P):  CDE
Wrong input.
Enter a letter (C-P):  Q
Wrong input.
Enter a letter (C-P):  N
N

Unfortunately, if someone needs a custom message for each failed case, then, I'm afraid, there is no pretty functional way. Or, at least, I couldn't find one.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.

Chrome javascript debugger breakpoints don't do anything?

This may be a Chrome bug. Unfortunately Chrome routinely breaks debugging. It often has some kind of memory leak and it often breaks or changes every few releases.

Debugging with formatted sources is currently extremely unreliable.

It's possible you're also trying to break on dead code.

To be certain it's not the browser you should also try to debug it in firefox.

Where do I configure log4j in a JUnit test class?

I use system properties in log4j.xml:

...
<param name="File" value="${catalina.home}/logs/root.log"/>
...

and start tests with:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemProperties>
            <property>
                <name>catalina.home</name>
                <value>${project.build.directory}</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

How do I get the collection of Model State Errors in ASP.NET MVC?

Putting together several answers from above, this is what I ended up using:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.

enter image description here

Swift addsubview and remove it

You have to use the viewWithTag function to find the view with the given tag.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let point = touch.locationInView(self.view)

    if let viewWithTag = self.view.viewWithTag(100) {
        print("Tag 100")
        viewWithTag.removeFromSuperview()
    } else {
        print("tag not found")
    }
}

Getting an element from a Set

Here's what you can do if you have a NavigableSet (e.g. a TreeSet):

public static <E> E get(NavigableSet<E> set, E key) {
    return set.tailSet(key, true).floor(key);
}

The things are slightly trickier for HashSet and its descendants like LinkedHashSet:

import java.util.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {
    private static final Field mapField;
    private static final Method hashMethod;
    private static final Method getNodeMethod;
    private static final Field keyField;
    static {
        try {
            mapField = HashSet.class.getDeclaredField("map");
            mapField.setAccessible(true);
            hashMethod = HashMap.class.getDeclaredMethod("hash", Object.class);
            hashMethod.setAccessible(true);
            getNodeMethod = HashMap.class.getDeclaredMethod("getNode",
                    Integer.TYPE, Object.class);
            getNodeMethod.setAccessible(true);
            keyField = Class.forName("java.util.HashMap$Node").getDeclaredField("key");
            keyField.setAccessible(true);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    public static <E> E get(HashSet<E> set, E key) {
        try {
            Object map = mapField.get(set);
            Object hash = hashMethod.invoke(null, key);
            Object node = getNodeMethod.invoke(map, hash, key);
            if (node == null)
                return null;
            @SuppressWarnings("unchecked")
            E result = (E)keyField.get(node);
            return result;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    public static <E> E get(NavigableSet<E> set, E key) {
        return set.tailSet(key, true).floor(key);
    }

    public static void main(String[] args) {
        HashSet<Integer> s = new HashSet<>();
//      HashSet<Integer> s = new LinkedHashSet<>();
//      TreeSet<Integer> s = new TreeSet<>();
        for (int i = 0; i < 100_000; i++)
            s.add(i);
        Integer key = java.awt.event.KeyEvent.VK_FIND;
        Integer hidden = get(s, key);
        System.out.println(key);
        System.out.println(hidden);
        System.out.println(key.equals(hidden));
        System.out.println(key == hidden);
    }
}

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

How to find out what this MySQL Error is trying to say:

#1064 - You have an error in your SQL syntax;

This error has no clues in it. You have to double check all of these items to see where your mistake is:

  1. You have omitted, or included an unnecessary symbol: !@#$%^&*()-_=+[]{}\|;:'",<>/?
  2. A misplaced, missing or unnecessary keyword: select, into, or countless others.
  3. You have unicode characters that look like ascii characters in your query but are not recognized.
  4. Misplaced, missing or unnecessary whitespace or newlines between keywords.
  5. Unmatched single quotes, double quotes, parenthesis or braces.

Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.

What is the difference between exit(0) and exit(1) in C?

exit(0) behave like return 0 in main() function, exit(1) behave like return 1. The standard is, that main function return 0, if program ended successfully while non-zero value means that program was terminated with some kind of error.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)

Just go through these links,

Run Android on Your Windows Mobile Phone

full tutorial on how to put android on windows mobile touch pro 2

How to install Android on most Windows Mobile phones

Update:

For Windows 7 to Android device, this also possible, (You need to do some hack for this)

Just go through these links,

Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]

HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND

Install windows phone 7 on android and iphones | Tips and Tricks

How to install Windows Phone 7 on HTC HD2? (Video)


To Install Android on your iOS Devices (This also possible...)

Look at How To Install Android on your iOS Devices

Android 2.2 Froyo running on Iphone

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_

How to Create simple drag and Drop in angularjs

Modified from the angular-drag-and-drop-lists examples page

Markup

<div class="row">
    <div ng-repeat="(listName, list) in models.lists" class="col-md-6">
        <ul dnd-list="list">
            <li ng-repeat="item in list" 
                dnd-draggable="item" 
                dnd-moved="list.splice($index, 1)" 
                dnd-effect-allowed="move" 
                dnd-selected="models.selected = item" 
                ng-class="{'selected': models.selected === item}" 
                draggable="true">{{item.label}}</li>
        </ul>
    </div>
</div>

Angular

var app = angular.module('angular-starter', [
    'ui.router',
    'dndLists'
]);

app.controller('MainCtrl', function($scope){

    $scope.models = {
        selected: null,
        lists: {"A": [], "B": []}
    };

    // Generate initial model
    for (var i = 1; i <= 3; ++i) {
        $scope.models.lists.A.push({label: "Item A" + i});
        $scope.models.lists.B.push({label: "Item B" + i});
    }

    // Model to JSON for demo purpose
    $scope.$watch('models', function(model) {
        $scope.modelAsJson = angular.toJson(model, true);
    }, true);
});

Library can be installed via bower or npm: angular-drag-and-drop-lists

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

In my case, the error message was implying that I was working in a headless console. So plt.show() could not work. What worked was calling plt.savefig:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [5,7,4])
plt.savefig("mygraph.png")

I found the answer on a github repository.

PHP validation/regex for URL

For anyone developing with WordPress, just use

esc_url_raw($url) === $url

to validate a URL (here's WordPress' documentation on esc_url_raw). It handles URLs much better than filter_var($url, FILTER_VALIDATE_URL) because it is unicode and XSS-safe. (Here is a good article mentioning all the problems with filter_var).

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

pandas GroupBy columns with NaN (missing) values

One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan yields False, so the replace function doesn't actually do anything.

What worked for me was this:

df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)

(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)

Python Decimals format

If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

CSS / HTML Navigation and Logo on same line

1) you can float the image to the left:

<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">

2)You can use an HTML table to place elements on one line.

Code below

  <div class="navigation-bar">
    <div id="navigation-container">
      <table>
        <tr>
          <td><img src="http://i.imgur.com/hCrQkJi.png"></td>
          <td><ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Get in Touch</a></li>
        </ul>
          </td></tr></table>
    </div>

How to input automatically when running a shell over SSH?

For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:

test.sh <<!
y
pasword
!

The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.

Is there a date format to display the day of the week in java?

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US )  )

java.time

The modern approach uses the java.time classes.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;

Note how we specify a Locale such as Locale.CANADA_FRENCH to determine the human language used to translate the name of the day.

DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;

ISO 8601

By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d.

2018-W01-2

Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.

The single digit on the end is day-of-week, 1-7 for Monday-Sunday.

Add the ThreeTen-Extra library class to your project for the YearWeek class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Creating a very simple 1 username/password login in php

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in

How to find all occurrences of an element in a list

more_itertools.locate finds indices for all items that satisfy a condition.

from more_itertools import locate


list(locate([0, 1, 1, 0, 1, 0, 0]))
# [1, 2, 4]

list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
# [1, 3]

more_itertools is a third-party library > pip install more_itertools.

Delete worksheet in Excel using VBA

Try this code:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

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

You can run your .bat file through a .vbs file
Copy the following code into your .vbs file :

Dim WshShell
Dim obj
Set WshShell = WScript.CreateObject("WScript.Shell") 
obj = WshShell.Run("C:\Users\file1.bat", 0) 
obj = WshShell.Run("C:\Users\file2.bat", 0)  and so on
set WshShell = Nothing 

Is floating point math broken?

A lot of good answers have been posted, but I'd like to append one more.

Not all numbers can be represented via floats/doubles For example, the number "0.2" will be represented as "0.200000003" in single precision in IEEE754 float point standard.

Model for store real numbers under the hood represent float numbers as

enter image description here

Even though you can type 0.2 easily, FLT_RADIX and DBL_RADIX is 2; not 10 for a computer with FPU which uses "IEEE Standard for Binary Floating-Point Arithmetic (ISO/IEEE Std 754-1985)".

So it is a bit hard to represent such numbers exactly. Even if you specify this variable explicitly without any intermediate calculation.

Using sudo with Python script

Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!

If what you really want is a password-less mount for that volume, maybe sudo isn't needed at all! So may I suggest other approaches?

  • Use /etc/fstab as mensi suggested. Use options user and noauto to let regular users mount that volume.

  • Use Polkit for passwordless actions: Configure a .policy file for your script with <allow_any>yes</allow_any> and drop at /usr/share/polkit-1/actions

  • Edit /etc/sudoers to allow your user to use sudo without typing your password. As @Anders suggested, you can restrict such usage to specific commands, thus avoiding unlimited passwordless root priviledges in your account. See this answer for more details on /etc/sudoers.

All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.

As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Merge a Branch into Trunk

Your svn merge syntax is wrong.

You want to checkout a working copy of trunk and then use the svn merge --reintegrate option:

$ pwd
/home/user/project-trunk

$ svn update  # (make sure the working copy is up to date)
At revision <N>.

$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U    foo.c
U    bar.c
 U   .

$ # build, test, verify, ...

$ svn commit -m "Merge branch_1 back into trunk!"
Sending        .
Sending        foo.c
Sending        bar.c
Transmitting file data ..
Committed revision <N+1>.

See the SVN book chapter on merging for more details.


Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate

Decode Hex String in Python 3

Something like:

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

Just put the actual encoding you are using.

Rails select helper - Default selected value, how?

Mike Bethany's answer above worked to set a default value when a new record was being created and still have the value the user selected show in the edit form. However, I added a model validation and it would not let me submit the form. Here's what worked for me to have a model validation on the field and to show a default value as well as the value the user selected when in edit mode.

  <div class="field">
    <%= f.label :project_id, 'my project id', class: "control-label" %><br>
    <% if @work.new_record? %>
      <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], true), {}, required: true, class: "form-control" %><br>
    <% else %>
      <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], @work.project_id), {}, required: true, class: "form-control" %><br>
    <% end %>
  </div>

model validation

  validates :project_id, presence: true

WARNING: Can't verify CSRF token authenticity rails

I'm using Rails 4.2.4 and couldn't work out why I was getting:

Can't verify CSRF token authenticity

I have in the layout:

<%= csrf_meta_tags %>

In the controller:

protect_from_forgery with: :exception

Invoking tcpdump -A -s 999 -i lo port 3000 was showing the header being set ( despite not needing to set the headers with ajaxSetup - it was done already):

X-CSRF-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
DNT: 1
Content-Length: 125
authenticity_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In the end it was failing because I had cookies switched off. CSRF doesn't work without cookies being enabled, so this is another possible cause if you're seeing this error.

server error:405 - HTTP verb used to access this page is not allowed

Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb

the solution would be to rename the page into .php or .aspx and you should be good to go :)

How to define partitioning of DataFrame?

Spark >= 2.3.0

SPARK-22614 exposes range partitioning.

val partitionedByRange = df.repartitionByRange(42, $"k")

partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
//    +- LocalRelation [_1#2, _2#3]
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
// 
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]

SPARK-22389 exposes external format partitioning in the Data Source API v2.

Spark >= 1.6.0

In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition method:

val df = Seq(
  ("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")

val partitioned = df.repartition($"k")
partitioned.explain

// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- Scan PhysicalRDD[_1#5,_2#6]

Unlike RDDs Spark Dataset (including Dataset[Row] a.k.a DataFrame) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.

Spark < 1.6.0:

One thing you can do is to pre-partition input data before you create a DataFrame

import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner

val schema = StructType(Seq(
  StructField("x", StringType, false),
  StructField("y", LongType, false),
  StructField("z", DoubleType, false)
))

val rdd = sc.parallelize(Seq(
  Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
  Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))

val partitioner = new HashPartitioner(5) 

val partitioned = rdd.map(r => (r.getString(0), r))
  .partitionBy(partitioner)
  .values

val df = sqlContext.createDataFrame(partitioned, schema)

Since DataFrame creation from an RDD requires only a simple map phase existing partition layout should be preserved*:

assert(df.rdd.partitions == partitioned.partitions)

The same way you can repartition existing DataFrame:

sqlContext.createDataFrame(
  df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
  df.schema
)

So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:

  1. Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.

    • joins in some scenarios, but it would require an internal support,
    • window functions calls with matching partitioner. Same as above, limited to a single window definition. It is already partitioned internally though, so pre-partitioning may be redundant,
    • simple aggregations with GROUP BY - it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce) (current behavior) vs reduceByKey (pre-partitioning). Unlikely to be useful in practice.
    • data compression with SqlContext.cacheTable. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions could improve compression ratio.
  2. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.

  3. A whole point of using a high level declarative API is to isolate yourself from a low level implementation details. As already mentioned by @dwysakowicz and @RomiKuntsman an optimization is a job of the Catalyst Optimizer. It is a pretty sophisticated beast and I really doubt you can easily improve on that without diving much deeper into its internals.

Related concepts

Partitioning with JDBC sources:

JDBC data sources support predicates argument. It can be used as follows:

sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)

It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.

partitionBy method in DataFrameWriter:

Spark DataFrameWriter provides partitionBy method which can be used to "partition" data on write. It separates data on write using provided set of columns

val df = Seq(
  ("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")

df.write.partitionBy("k").json("/tmp/foo.json")

This enables predicate push down on read for queries based on key:

val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")

but it is not equivalent to DataFrame.repartition. In particular aggregations like:

val cnts = df1.groupBy($"k").sum()

will still require TungstenExchange:

cnts.explain

// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
//    +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
//       +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json

bucketBy method in DataFrameWriter (Spark >= 2.0):

bucketBy has similar applications as partitionBy but it is available only for tables (saveAsTable). Bucketing information can used to optimize joins:

// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)

df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")

// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
//    :- *Sort [k#41 ASC NULLS FIRST], false, 0
//    :  +- *Project [k#41, v#42]
//    :     +- *Filter isnotnull(k#41)
//    :        +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
//    +- *Sort [k#46 ASC NULLS FIRST], false, 0
//       +- *Project [k#46, v2#47]
//          +- *Filter isnotnull(k#46)
//             +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>

* By partition layout I mean only a data distribution. partitioned RDD has no longer a partitioner. ** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.

Removing all non-numeric characters from string in Python

>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'

How to change users in TortoiseSVN

After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.

https://web.archive.org/web/20160614002053/http://windows.microsoft.com/en-us/windows7/remove-stored-passwords-certificates-and-other-credentials

Disable Input fields in reactive form

This worked for me: this.form.get('first').disable({onlySelf: true});

When is TCP option SO_LINGER (0) required?

When linger is on but the timeout is zero the TCP stack doesn't wait for pending data to be sent before closing the connection. Data could be lost due to this but by setting linger this way you're accepting this and asking that the connection be reset straight away rather than closed gracefully. This causes an RST to be sent rather than the usual FIN.

Thanks to EJP for his comment, see here for details.

Converting PKCS#12 certificate into PEM using OpenSSL

Try:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes

After that you have:

  • certificate in newfile.crt.pem
  • private key in newfile.key.pem

To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:

openssl pkcs12 -in path.p12 -out newfile.pem -nodes

Or, if you want to provide a password for the private key, omit -nodes and input a password:

openssl pkcs12 -in path.p12 -out newfile.pem

If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

How do I convert a string to enum in TypeScript?

I got it working using the following code.

var green= "Green";
var color : Color= <Color>Color[green];

Go build: "Cannot find package" (even though GOPATH is set)

TL;DR: Follow Go conventions! (lesson learned the hard way), check for old go versions and remove them. Install latest.

For me the solution was different. I worked on a shared Linux server and after verifying my GOPATH and other environment variables several times it still didn't work. I encountered several errors including 'Cannot find package' and 'unrecognized import path'. After trying to reinstall with this solution by the instructions on golang.org (including the uninstall part) still encountered problems.

Took me some time to realize that there's still an old version that hasn't been uninstalled (running go version then which go again... DAHH) which got me to this question and finally solved.

How to make a edittext box in a dialog

Simplest of all would be.

  • Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.

    Inflate this view and set this to AlertDialog

Lets start with Layout file first.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">


    <EditText
        android:id="@+id/etComments"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter comments(Optional)"
        android:inputType="textMultiLine"
        android:lines="8"
        android:maxLines="3"
        android:minLines="6"
        android:scrollbars="vertical" />

</LinearLayout>

final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");


final EditText etComments = (EditText) view.findViewById(R.id.etComments);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});


alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        alertDialog.dismiss()
    }
});


alertDialog.setView(view);
alertDialog.show();

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code and start over.

For a slightly easier approach, you can use ast.parse module to parse the expression, and then the ast.NodeVisitor or ast.NodeTransformer to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile and eval to get the result.

The code is a bit different from literal_eval in that this code actually uses eval, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__ is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num (float and integer), list and dictionary literals.

Also, works the same on 2.7 and 3.3

import ast
import decimal

source = "(Decimal('11.66985'), Decimal('1e-8'),"\
    "(1,), (1,2,3), 1.2, [1,2,3], {1:2})"

tree = ast.parse(source, mode='eval')

# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
    ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
    ALLOWED_NODE_TYPES = set([
        'Expression', # a top node for an expression
        'Tuple',      # makes a tuple
        'Call',       # a function call (hint, Decimal())
        'Name',       # an identifier...
        'Load',       # loads a value of a variable with given identifier
        'Str',        # a string literal

        'Num',        # allow numbers too
        'List',       # and list literals
        'Dict',       # and dicts...
    ])

    def visit_Name(self, node):
        if not node.id in self.ALLOWED_NAMES:
            raise RuntimeError("Name access to %s is not allowed" % node.id)

        # traverse to child nodes
        return self.generic_visit(node)

    def generic_visit(self, node):
        nodetype = type(node).__name__
        if nodetype not in self.ALLOWED_NODE_TYPES:
            raise RuntimeError("Invalid expression: %s not allowed" % nodetype)

        return ast.NodeTransformer.generic_visit(self, node)


transformer = Transformer()

# raises RuntimeError on invalid code
transformer.visit(tree)

# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')

# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))

print(result)

How to verify that a specific method was not called using Mockito?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

There are actually many ways to achieve this, however it's (arguably) cleaner to use the

verify(yourMock, times(0)).someMethod();

method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:

verify(yourMock, times(5)).someMethod();

Alternatives are:

verify(yourMock, never()).someMethod();

Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:

verifyZeroInteractions(yourMock)

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Adding to an ArrayList Java

You should be able to do something like:

ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
    list.add(s);
}

How to change the href for a hyperlink using jQuery

Stop using jQuery just for the sake of it! This is so simple with JavaScript only.

document.querySelector('#the-link').setAttribute('href', 'http://google.com');

https://jsfiddle.net/bo77f8mg/1/

What is the difference between association, aggregation and composition?

From a post by Robert Martin in comp.object:

Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.

//[Example:]

//|A|----------->|B|

class A
{
  private:
    B* itsB;
};

Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).

//[Example:]

//|Node|<>-------->|Node|

class Node
{
  private:
    vector<Node*> itsNodes;
};

The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.

Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

//[Example:]

//|Car|<#>-------->|Carburetor|

class Car
{
  public:
    virtual ~Car() {delete itsCarb;}
  private:
    Carburetor* itsCarb
};

How do I completely rename an Xcode project (i.e. inclusive of folders)?

Step 1 - Rename the project

  1. Click on the project you want to rename in the "Project navigator" in the left panel of the Xcode window.
  2. In the right panel, select the "File inspector", and the name of your project should be found under "Identity and Type". Change it to your new name.
  3. When the dialog asks whether to rename or not rename the project's content items, click "Rename". Say yes to any warning about uncommitted changes.

Step 2 - Rename the scheme

  1. At the top of the window, next to the "Stop" button, there is a scheme for your product under its old name; click on it, then choose "Manage Schemes…".
  2. Click on the old name in the scheme and it will become editable; change the name and click "Close".

Step 3 - Rename the folder with your assets

  1. Quit Xcode. Rename the master folder that contains all your project files.
  2. In the correctly-named master folder, beside your newly-named .xcodeproj file, there is probably a wrongly-named OLD folder containing your source files. Rename the OLD folder to your new name (if you use Git, you could run git mv oldname newname so that Git recognizes this is a move, rather than deleting/adding new files).
  3. Re-open the project in Xcode. If you see a warning "The folder OLD does not exist", dismiss the warning. The source files in the renamed folder will be grayed out because the path has broken.
  4. In the "Project navigator" in the left-hand panel, click on the top-level folder representing the OLD folder you renamed.
  5. In the right-hand panel, under "Identity and Type", change the "Name" field from the OLD name to the new name.
  6. Just below that field is a "Location" menu. If the full path has not corrected itself, click on the nearby folder icon and choose the renamed folder.

Step 4 - Rename the Build plist data

  1. Click on the project in the "Project navigator" on the left, and in the main panel select "Build Settings".
  2. Search for "plist" in the settings.
  3. In the Packaging section, you will see Info.plist and Product Bundle Identifier.
  4. If there is a name entered in Info.plist, update it.
  5. Do the same for Product Bundle Identifier, unless it is utilizing the ${PRODUCT_NAME} variable. In that case, search for "product" in the settings and update Product Name. If Product Name is based on ${TARGET_NAME}, click on the actual target item in the TARGETS list on the left of the settings pane and edit it, and all related settings will update immediately.
  6. Search the settings for "prefix" and ensure that Prefix Header's path is also updated to the new name.
  7. If you use SwiftUI, search for "Development Assets" and update the path.

Step 5 - Repeat step 3 for tests (if you have them)

Step 6 - Repeat step 3 for core data if its name matches project name (if you have it)

Step 7 - Clean and rebuild your project

  1. Command + Shift + K to clean
  2. Command + B to build

How to install an apk on the emulator in Android Studio?

Start your Emulator from Android Studio Tools->Android-> AVD Manager then select an emulator image and start it.

After emulator is started just drag and drop the APK Very simple.

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

"Could not get any response" response when using postman with subdomain

None of these solutions works for me. Postman is not sending any request to the server because postman is not finding the host. So, if you modify your /etc/hosts to 127.0.0.1 localhost 127.0.0.1 subdomain.localhost

It works for me.

How to consume a SOAP web service in Java

There are many options to consume a SOAP web service with Stub or Java classes created based on WSDL. But if anyone wants to do this without any Java class created, this article is very helpful. Code Snippet from the article:

public String someMethod() throws MalformedURLException, IOException {

//Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = "<Endpoint of the webservice to be consumed>";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = "entire SOAP Request";

byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "<SOAP action of the webservice to be consumed>";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.

//Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
  isr = new InputStreamReader(httpConn.getInputStream());
} else {
  isr = new InputStreamReader(httpConn.getErrorStream());
}

BufferedReader in = new BufferedReader(isr);

//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString); // Write a separate method to parse the xml input.
NodeList nodeLst = document.getElementsByTagName("<TagName of the element to be retrieved>");
String elementValue = nodeLst.item(0).getTextContent();
System.out.println(elementValue);

//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString); // Write a separate method to format the XML input.
System.out.println(formattedSOAPResponse);
return elementValue;
}

For those who're looking for a similar kind of solution with file upload while consuming a SOAP API, please refer to this post: How to attach a file (pdf, jpg, etc) in a SOAP POST request?

How to fill a datatable with List<T>

Try this

static DataTable ConvertToDatatable(List<Item> list)
{
    DataTable dt = new DataTable();

    dt.Columns.Add("Name");
    dt.Columns.Add("Price");
    dt.Columns.Add("URL");
    foreach (var item in list)
    {
        var row = dt.NewRow();

        row["Name"] = item.Name;
        row["Price"] = Convert.ToString(item.Price);
        row["URL"] = item.URL;

        dt.Rows.Add(row);
    }

    return dt;
}

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.

Steps:

git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

java.nio.file.Path for a classpath resource

You can not create URI from resources inside of the jar file. You can simply write it to the temp file and then use it (java8):

Path path = File.createTempFile("some", "address").toPath();
Files.copy(ClassLoader.getSystemResourceAsStream("/path/to/resource"), path, StandardCopyOption.REPLACE_EXISTING);

How can I delete a service in Windows?

Here is a vbs script that was passed down to me:

Set servicelist = GetObject("winmgmts:").InstancesOf ("Win32_Service")

for each service in servicelist
    sname = lcase(service.name)
    If sname = "NameOfMyService" Then 
        msgbox(sname)
        service.delete ' the internal name of your service
    end if
next

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

How to select Python version in PyCharm?

This can also happen in Intellij Ultimate, which has PyCharm integrated. The issue is as diagnosed above, you have the wrong interpreter selected.

The exact method to fix this for any given project is to go to Project Settings...Project and adjust the Project SDK. You can add a New Project SDK if you don't have Python 3 added by navigating to the python3 binary. This will fix the errors listed above. A shortcut to Project Settings is the blue checkerboard-type icon.

You can also add Python 3 as the default interpreter for Python projects. On OSX this is in File..Other Settings...Default Project Structure. There you can set the Project SDK which will now apply on each new project. It can be different on other platforms, but still similar.

Microsoft Web API: How do you do a Server.MapPath?

I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath in WebApiHttpApplication; e.g. in Application_Start().

I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath() is probably the preferred solution.

Is there a way to catch the back button event in javascript?

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Accidentally committed .idea directory files into git

Its better to perform this over Master branch

Edit .gitignore file. Add the below line in it.

.idea

Remove .idea folder from remote repo. using below command.

git rm -r --cached .idea

For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them

Stage .gitignore file. Using below command

git add .gitignore

Commit

git commit -m 'Removed .idea folder'

Push to remote

git push origin master

Reading a resource file from within jar

If you are using spring, then you can use the the following method to read file from src/main/resources:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.core.io.ClassPathResource;

  public String readFileToString(String path) throws IOException {

    StringBuilder resultBuilder = new StringBuilder("");
    ClassPathResource resource = new ClassPathResource(path);

    try (
        InputStream inputStream = resource.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

      String line;

      while ((line = bufferedReader.readLine()) != null) {
        resultBuilder.append(line);
      }

    }

    return resultBuilder.toString();
  }

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

How to break out of multiple loops?

Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

Behaviour of increment and decrement operators in Python

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

Using CSS :before and :after pseudo-elements with inline CSS?

You can't create pseudo elements in inline css.

However, if you can create a pseudo element in a stylesheet, then there's a way to style it inline by setting an inline style to its parent element, and then using inherit keyword to style the pseudo element, like this:

<parent style="background-image:url(path/to/file); background-size:0px;"></p>

<style> 
   parent:before{
      content:'';
      background-image:inherit;
      (other)
   }
</style>

sometimes this can be handy.

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

How to enable curl in Wamp server

I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.

Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

Go to "Fixed curl extensions" and download the extension that matches your PHP version.

Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)

Restart Apache

Done!

Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html

Cheers!

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Disable single warning error

as @rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop

this info comes from here

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

Check if table exists without using "select from"

After reading all of the above, I prefer the following statement:

SELECT EXISTS(
       SELECT * FROM information_schema.tables 
       WHERE table_schema = 'db' 
       AND table_name = 'table'
);

It indicates exactly what you want to do and it actually returns a 'boolean'.

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

Find and kill a process in one line using bash and regex

My task was kill everything matching regexp that is placed in specific directory (after selenium tests not everything got stop). This worked for me:

for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

String replacement in batch file

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

Variable number of arguments in C++?

in c++11 you can do:

void foo(const std::list<std::string> & myArguments) {
   //do whatever you want, with all the convenience of lists
}

foo({"arg1","arg2"});

list initializer FTW!

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

How to get the width of a react element

    class MyComponent extends Component {
      constructor(props){
        super(props)
        this.myInput = React.createRef()
      }

      componentDidMount () {
        console.log(this.myInput.current.offsetWidth)
      }

      render () {
        return (
        // new way - as of [email protected]
        <div ref={this.myInput}>some elem</div>
        // legacy way
        // <div ref={(ref) => this.myInput = ref}>some elem</div>
        )
      }
    }

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

Select from one table matching criteria in another?

select a.id, a.object
from table_A a
inner join table_B b on a.id=b.id
where b.tag = 'chair';

403 Forbidden vs 401 Unauthorized HTTP responses

Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.

403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.

If HTTP authentication is not in use and the service a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.

Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):

3.1. 401 Unauthorized

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.

The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404
(Not Found) can be used instead.

In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons
unrelated to the credentials.

An origin server that wishes to "hide" the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).

Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help... or it might not.

I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today's Web apps build custom authentication schemes using for example forms and cookies.

Remove empty elements from an array in Javascript

Simple ES6

['a','b','',,,'w','b'].filter(v => v);

How can I list all collections in the MongoDB shell?

You can use show tables or show collections.

SQL multiple column ordering

You can use multiple ordering on multiple condition,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

jquery mobile background image

I found this answer works for me

<style type="text/css">
#background{ 
position: fixed; 
top: 0; 
left: 0; 
width: 100% !important; 
height: 100% !important; 
background: url(mobile-images/limo-service.jpg) no-repeat center center fixed !important; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover; 
z-index: -1; 
} 
.ui-page{ 
background:none; 
}
</style>    

also add id="background" to the div for your content section

<div data-role="page" data-theme="a">
  <div data-role="main" class="ui-content" id="background">
  </div>
</div>

Node - how to run app.js?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Illegal mix of collations MySQL Error

You should set both your table encoding and connection encoding to UTF-8:

ALTER TABLE keywords CHARACTER SET UTF8; -- run once

and

SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';

Git, How to reset origin/master to a commit?

Assuming that your branch is called master both here and remotely, and that your remote is called origin you could do:

git reset --hard <commit-hash>
git push -f origin master

However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.

how to remove new lines and returns from php string?

$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));

What happens if you don't commit a transaction to a database (say, SQL Server)?

When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

bash: pip: command not found

Check out How to Install Pip article article for more information.

As of 2019,

Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run get-pip.py using the following command:
sudo python get-pip.py

After you done installing, run this command to check if pip is installed.
pip --version

Remove get-pip.py file after installing pip.
rm get-pip.py

Pip website

Build an iOS app without owning a mac?

Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:

1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.

2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal

3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.

I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.

Change project name on Android Studio

I just went into the manifest and changed android:label="...." to the name of the application. Once Id changed this, the title and the actual app name changed to that :)

Datatype for storing ip address in SQL Server

I'm using varchar(15) so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.

Here is the select statement:

select * From dbo.Server 
where  [IP] = ('132.46.151.181')
Go

How to get exact browser name and version?

I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).

function getBrowserInfo(){
    $browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');

    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $ub = 'Unknown';
    $version = "";
    $platform = 'Unknown';

    $deviceType='Desktop';

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){

        $deviceType='Mobile';

    }

    if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
        $deviceType='Tablet';
    }

    if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
        $deviceType='Tablet';
    }

    //$detect = new Mobile_Detect();
    
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';

    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';

    } elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the user agent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'IE'; 
        $ub = "MSIE";

    } else if(preg_match('/Firefox/i',$u_agent))
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 

    } else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Chrome'; 
        $ub = "Chrome"; 

    } else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Safari'; 
        $ub = "Safari"; 

    } else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 

    } else if(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 

    } else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
    {
        $bname = 'Internet Explorer'; 
        $ub = 'Internet Explorer'; 
    } 
    

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];

        } else {
            $version= @$matches['version'][1];
        }

    } else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'user_agent' => $u_agent,
        'browser'      => $bname,
        'browser_version'   => $version,
        'os_platform'  => $platform,
        'pattern'   => $pattern,
        'device'    => $deviceType
    );
}

This solved my problem of browser detection, I hope, this will also help you. Thank you.

How to select only 1 row from oracle sql?

The answer is:

You should use nested query as:

SELECT *
FROM ANY_TABLE_X 
WHERE ANY_COLUMN_X = (SELECT MAX(ANY_COLUMN_X) FROM ANY_TABLE_X) 

=> In PL/SQL "ROWNUM = 1" is NOT equal to "TOP 1" of TSQL.

So you can't use a query like this: "select * from any_table_x where rownum=1 order by any_column_x;" Because oracle gets first row then applies order by clause.

find if an integer exists in a list of integers

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7}); // 1

List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2

var i = 5;
var x = ints.Contains(i);   // return true or false

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

I have tried all the solutions and this one worked for me

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage

"static const" vs "#define" vs "enum"

I wrote quick test program to demonstrate one difference:

#include <stdio.h>

enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};

#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32

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

   printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);

   return(0);
}

This compiles with these errors and warnings:

main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
      ^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
      ^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
        ^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
        ^

Note that enum gives an error when define gives a warning.

Open JQuery Datepicker by clicking on an image w/ no input field

To change the "..." when the mouse hovers over the calendar icon, You need to add the following in the datepicker options:

    showOn: 'button',
    buttonText: 'Click to show the calendar',
    buttonImageOnly: true, 
    buttonImage: 'images/cal2.png',

Script to get the HTTP status code of a list of urls?

wget -S -i *file* will get you the headers from each url in a file.

Filter though grep for the status code specifically.

How to use "/" (directory separator) in both Linux and Windows in Python?

Don't build directory and file names your self, use python's included libraries.

In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

Your example would be

pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)

With ng-bind-html-unsafe removed, how do I inject HTML?

You can use filter like this

angular.module('app').filter('trustAs', ['$sce', 
    function($sce) {
        return function (input, type) {
            if (typeof input === "string") {
                return $sce.trustAs(type || 'html', input);
            }
            console.log("trustAs filter. Error. input isn't a string");
            return "";
        };
    }
]);

usage

<div ng-bind-html="myData | trustAs"></div>

it can be used for other resource types, for example source link for iframes and other types declared here

How can I merge properties of two JavaScript objects dynamically?

Three ways you can do that:-

Approach 1:-

// using spread ...
    let obj1 = {
        ...obj2
    };

Approach2:-

// using  Object.assign() method
let obj1 = Object.assign({}, obj2);

Approach3:-

// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));

How to replace multiple white spaces with one white space

You can try this:

    /// <summary>
    /// Remove all extra spaces and tabs between words in the specified string!
    /// </summary>
    /// <param name="str">The specified string.</param>
    public static string RemoveExtraSpaces(string str)
    {
        str = str.Trim();
        StringBuilder sb = new StringBuilder();
        bool space = false;
        foreach (char c in str)
        {
            if (char.IsWhiteSpace(c) || c == (char)9) { space = true; }
            else { if (space) { sb.Append(' '); }; sb.Append(c); space = false; };
        }
        return sb.ToString();
    }

CMake is not able to find BOOST libraries

I had the same issue inside an alpine docker container, my solution was to add the boost-dev apk library because libboost-dev was not available.

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Regex: ignore case sensitivity

You can practice Regex In Visual Studio and Visual Studio Code using find/replace.

You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here

Visual Studio 2019 Community

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

IsNullOrEmpty with Object

I found that DataGridViewTextBox values and some JSON objects don't equal Null but instead are "{}" values. Comparing them to Null doesn't work but using these do the trick:

if (cell.Value is System.DBNull)

if (cell.Value == System.DBNull.Value)

A good excerpt I found concerning the difference between Null and DBNull:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

You can learn more about the DBNull class here.

Inserting Data into Hive Table

You can use following lines of code to insert values into an already existing table. Here the table is db_name.table_name having two columns, and I am inserting 'All','done' as a row in the table.

insert into table db_name.table_name
select 'ALL','Done';

Hope this was helpful.

How do I implement IEnumerable<T>

Why do you do it manually? yield return automates the entire process of handling iterators. (I also wrote about it on my blog, including a look at the compiler generated code).

If you really want to do it yourself, you have to return a generic enumerator too. You won't be able to use an ArrayList any more since that's non-generic. Change it to a List<MyObject> instead. That of course assumes that you only have objects of type MyObject (or derived types) in your collection.

Reporting Services Remove Time from DateTime in Expression

My solution for a Date/Time parameter:

=CDate(Today())

The trick is to convert back to a DateTime as recommend Perhentian.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

you can try to use

  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

instead of

androidTestCompile 'com.android.support.test:runner:0.4.1'

androidTestCompile 'com.android.support.test:rules:0.4.1'

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.1'

How do you determine what SQL Tables have an identity column programmatically

The following query work for me:

select  TABLE_NAME tabla,COLUMN_NAME columna
from    INFORMATION_SCHEMA.COLUMNS
where   COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME

PHP PDO: charset, set names?

I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.

Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:

// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
  $this->exec('SET NAMES utf8');
}

python plot normal distribution

I have just come back to this and I had to install scipy as matplotlib.mlab gave me the error message MatplotlibDeprecationWarning: scipy.stats.norm.pdf when trying example above. So the sample is now:

%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats


mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma))

plt.show()

Unique random string generation

My one stop solution for Linux commands on windows is scoop. Install scoop from scoop.sh

scoop install openssl
openssl rand -base64 32
Dca3c3pptVkcb8fx243wN/3f/rQxx/rWYL8y7rZrGrA=

Read and write into a file using VBScript

You could open two textstreams, one for reading

Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)

and one for appending

Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)

The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

how to open a page in new tab on button click in asp.net?

Why not just call window.open straight from OnClick?

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="window.open('New.aspx')" />

How to use addTarget method in swift 3

Try this

button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

Just add parenthesis with name of method.

Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'

"R cannot be resolved to a variable"?

Check the androidmanifest.xml file and layoutfolder xml files. They should be created properly as the starting and ending clause in xml should be placed properly. Update the files, clean and build. And all set!

How to play .mp4 video in videoview in android?

In Kotlin you can do as

 val videoView = findViewById<VideoView>(R.id.videoView)

       // If url is from raw
   /* val url = "android.resource://" + packageName
        .toString() + "/" + R.raw.video*/

    // If url is from network
    val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"

    val video =
        Uri.parse(url)
    videoView.setVideoURI(video)
    videoView.setOnPreparedListener{
        videoView.start()
    }

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Spring Boot - Loading Initial Data

If you want to insert only few rows and u have JPA Setup. You can use below

    @SpringBootApplication
        @Slf4j
        public class HospitalManagementApplication {

            public static void main(String[] args) {
                SpringApplication.run(HospitalManagementApplication.class, args);
            }            

            @Bean
            ApplicationRunner init(PatientRepository repository) {
                return (ApplicationArguments args) ->  dataSetup(repository);
            } 

            public void dataSetup(PatientRepository repository){
            //inserts

     }

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

Doing

SET FOREIGN_KEY_CHECKS=0;

before the Operation can also do the trick.

How to delete cookies on an ASP.NET website

This is what I use:

    private void ExpireAllCookies()
    {
        if (HttpContext.Current != null)
        {
            int cookieCount = HttpContext.Current.Request.Cookies.Count;
            for (var i = 0; i < cookieCount; i++)
            {
                var cookie = HttpContext.Current.Request.Cookies[i];
                if (cookie != null)
                {
                    var expiredCookie = new HttpCookie(cookie.Name) {
                        Expires = DateTime.Now.AddDays(-1),
                        Domain = cookie.Domain
                    };
                    HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
                }
            }

            // clear cookies server side
            HttpContext.Current.Request.Cookies.Clear();
        }
    }

Formatting floats without trailing zeros

If you can live with 3. and 3.0 appearing as "3.0", a very simple approach that right-strips zeros from float representations:

print("%s"%3.140)

(thanks @ellimilial for pointing out the exceptions)

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

PHPMailer character encoding issues

When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ:

$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;

Android ViewPager with bottom dots

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

                switch (position) {
    case 0:
        img_page1.setImageResource(R.drawable.dot_selected);
        img_page2.setImageResource(R.drawable.dot);
        img_page3.setImageResource(R.drawable.dot);
        img_page4.setImageResource(R.drawable.dot);
        break;

    case 1:
        img_page1.setImageResource(R.drawable.dot);
        img_page2.setImageResource(R.drawable.dot_selected);
        img_page3.setImageResource(R.drawable.dot);
        img_page4.setImageResource(R.drawable.dot);
        break;

    case 2:
        img_page1.setImageResource(R.drawable.dot);
        img_page2.setImageResource(R.drawable.dot);
        img_page3.setImageResource(R.drawable.dot_selected);
        img_page4.setImageResource(R.drawable.dot);
        break;

    case 3:
        img_page1.setImageResource(R.drawable.dot);
        img_page2.setImageResource(R.drawable.dot);
        img_page3.setImageResource(R.drawable.dot);
        img_page4.setImageResource(R.drawable.dot_selected);
        break;

    default:
        break;
    }


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

C# SQL Server - Passing a list to a stored procedure

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

You can use git log with the pathnames of the respective folders:

git log A B

The log will only show commits made in A and B. I usually throw in --stat to make things a little prettier, which helps for quick commit reviews.

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

Is object empty?

How bad is this?

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

    return true; // empty
}