Programs & Examples On #Indexof

indexof is a method in programming languages like Java, C#, JavaScript, etc. that returns the first occurrence of a letter in a string, or the first occurrence of an element in a list.

Index of element in NumPy array

I'm torn between these two ways of implementing an index of a NumPy array:

idx = list(classes).index(var)
idx = np.where(classes == var)

Both take the same number of characters, but the first method returns an int instead of a numpy.ndarray.

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Getting Index of an item in an arraylist;

.indexOf() works well. If you want an example here is one:

  ArrayList<String> example = new ArrayList<String>();
  example.add("AB");
  example.add("CD");
  example.add("EF");
  example.add("GH");
  example.add("IJ");
  example.add("KL");
  example.add("MN");

  System.out.println("Index of 'AB': "+example.indexOf("AB"));
  System.out.println("Index of 'KL': "+example.indexOf("KL"));
  System.out.println("Index of 'AA': "+example.indexOf("AA"));
  System.out.println("Index of 'EF': "+example.indexOf("EF"));

will give you an output of

Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

Note: This method returns -1 if the specified element is not present in the list.

How to find the array index with a value?

Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,

var studentsArray =
     [
    {
    "rollnumber": 1,
    "name": "dj",
    "subject": "physics"
   },
   {
   "rollnumber": 2,
  "name": "tanmay",
  "subject": "biology"
   },
  {
   "rollnumber": 3,
   "name": "amit",
   "subject": "chemistry"
   },
  ];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.

function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

    for (var i = 0; i < arraytosearch.length; i++) {

    if (arraytosearch[i][key] == valuetosearch) {
    return i;
    }
    }
    return null;
    }

You can use the function to find index of a particular element as below,

var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

Where is Java's Array indexOf?

int findIndex(int myElement, int[] someArray){
 int index = 0;
 for(int n: someArray){
   if(myElement == n) return index;
   else index++;
 }
}

Note: you can use this method for arrays of type int, you can also use this algorithm for other types with minor changes

indexOf and lastIndexOf in PHP?

In php:

  • stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.

  • strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.

Sample code:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

Output: Fist index = 2 Last index = 13

How to find indices of all occurrences of one string in another in JavaScript?

var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
    indices.push(result.index);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {_x000D_
    var searchStrLen = searchStr.length;_x000D_
    if (searchStrLen == 0) {_x000D_
        return [];_x000D_
    }_x000D_
    var startIndex = 0, index, indices = [];_x000D_
    if (!caseSensitive) {_x000D_
        str = str.toLowerCase();_x000D_
        searchStr = searchStr.toLowerCase();_x000D_
    }_x000D_
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {_x000D_
        indices.push(index);_x000D_
        startIndex = index + searchStrLen;_x000D_
    }_x000D_
    return indices;_x000D_
}_x000D_
_x000D_
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");_x000D_
_x000D_
document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Well, as you are just looking to match the position of a character , regex is possibly overkill.

I presume all you want is, instead of "find first of these this character" , just find first of these characters.

This of course is the simple answer, but does what your question sets out to do, albeit without the regex part ( because you didn't clarify why specifically it had to be a regex )

function mIndexOf( str , chars, offset )
{
   var first  = -1; 
   for( var i = 0; i < chars.length;  i++ )
   {
      var p = str.indexOf( chars[i] , offset ); 
      if( p < first || first === -1 )
      {
           first = p;
      }
   }
   return first; 
}
String.prototype.mIndexOf = function( chars, offset )
{
   return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching.  
};
mIndexOf( "hello world", ['a','o','w'], 0 );
>> 4 
mIndexOf( "hello world", ['a'], 0 );
>> -1 
mIndexOf( "hello world", ['a','o','w'], 4 );
>> 4
mIndexOf( "hello world", ['a','o','w'], 5 );
>> 6
mIndexOf( "hello world", ['a','o','w'], 7 );
>> -1 
mIndexOf( "hello world", ['a','o','w','d'], 7 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 10 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 11 );
>> -1

In an array of objects, fastest way to find the index of an object whose attributes match a search

The new Array method .filter() would work well for this:

var filteredArray = array.filter(function (element) { 
    return element.id === 0;
});

jQuery can also do this with .grep()

edit: it is worth mentioning that both of these functions just iterate under the hood, there won't be a noticeable performance difference between them and rolling your own filter function, but why re-invent the wheel.

Get value of a string after last slash in JavaScript

Try this:

_x000D_
_x000D_
const url = "files/images/gallery/image.jpg";_x000D_
_x000D_
console.log(url.split("/").pop());
_x000D_
_x000D_
_x000D_

How to trim a file extension from a String in JavaScript?

I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.

Why doesn't indexOf work on an array IE8?

The problem

IE<=8 simply doesn't have an indexOf() method for arrays.


The solution

If you need indexOf in IE<=8, you should consider using the following polyfill, which is recommended at the MDN :

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement, fromIndex) {
        var k;
        if (this == null) {
            throw new TypeError('"this" is null or not defined');
        }
        var o = Object(this);
        var len = o.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = +fromIndex || 0;
        if (Math.abs(n) === Infinity) {
            n = 0;
        }
        if (n >= len) {
            return -1;
        }
        k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
        while (k < len) {
            if (k in o && o[k] === searchElement) {
                return k;
            }
            k++;
        }
        return -1;
    };
}

Minified :

Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

How to get the index of an element in an IEnumerable?

Stumbled across this today in a search for answers and I thought I'd add my version to the list (No pun intended). It utlises the null conditional operator of c#6.0

IEnumerable<Item> collection = GetTheCollection();

var index = collection
.Select((item,idx) => new { Item = item, Index = idx })
//or .FirstOrDefault(_ =>  _.Item.Prop == something)
.FirstOrDefault(_ => _.Item == itemToFind)?.Index ?? -1;

I've done some 'racing of the old horses' (testing) and for large collections (~100,000), worst case scenario that item you want is at the end, this is 2x faster than doing ToList().FindIndex(). If the Item you want is in the middle its ~4x faster.

For smaller collections (~10,000) it seems to be only marginally faster

Heres how I tested it https://gist.github.com/insulind/16310945247fcf13ba186a45734f254e

Finding second occurrence of a substring in a string in Java

i think a loop can be used.

1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop

if-else statement inside jsx: ReactJS

You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View

render() {
    return (
      <View style={styles.container}>
      {this.state.page === 'news'? <Text>data</Text>: null}
      </View>

     )
}

psql: FATAL: database "<user>" does not exist

As the createdb documentation states:

The first database is always created by the initdb command when the data storage area is initialized... This database is called postgres.

So if certain OS/postgresql distributions do that differently, it is certainly not the default/standard (just verified that initdb on openSUSE 13.1 creates the DB "postgres", but not "<user>"). Long story short, psql -d postgres is expected to be used when using a user other than "postgres".

Obviously the accepted answer, running createdb to create a DB named like the user, works as well, but creates a superfluous DB.

How can I delete a newline if it is the last character in a file?

A very simple method for single-line files, requiring GNU echo from coreutils:

/bin/echo -n $(cat $file)

How to increase buffer size in Oracle SQL Developer to view all records?

You can also edit the preferences file by hand to set the Array Fetch Size to any value.

Mine is found at C:\Users\<user>\AppData\Roaming\SQL Developer\system4.0.2.15.21\o.sqldeveloper.12.2.0.15.21\product-preferences.xml on Win 7 (x64).

The value is on line 372 for me and reads <value n="ARRAYFETCHSIZE" v="200"/>

I have changed it to 2000 and it works for me.

I had to restart SQL Developer.

Disable building workspace process in Eclipse

Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.

You can also disable it through the menu "Project / Build automatically".

But I would recommend first to check:

  • if a Project Clean all / Build result in the same kind of long wait (after disabling this option)
  • if you have (this time with building automatically activated) some validation options you could disable to see if they have an influence on the global compilation time (Preferences / Validations, or Preferences / XML / ... if you have WTP installed)
  • if a fresh eclipse installation referencing the same workspace (see this eclipse.ini for more) results in the same issue (with building automatically activated)

Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:

There is an important difference between build interrupt and cancel.

  • When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
    As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.

  • The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
    In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.

 

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

how do you increase the height of an html textbox

<input type="text" style="font-size:xxpt;height:xxpx">

Just replace "xx" with whatever values you wish.

Parsing JSON from URL

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

How to install requests module in Python 3.4, instead of 2.7

i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified . You are unable to install requests in python 3.4 because your python libraries are not updated . use this command apt-get install python3-requests Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.

Are loops really faster in reverse?

First, i++ and i-- take exactly the same time on any programming language, including JavaScript.

The following code take much different time.

Fast:

for (var i = 0, len = Things.length - 1; i <= len; i++) { Things[i] };

Slow:

for (var i = 0; i <= Things.length - 1; i++) { Things[i] };

Therefore the following code take different time too.

Fast:

for (var i = Things.length - 1; i >= 0; i--) { Things[i] };

Slow:

for (var i = 0; i <= Things.length - 1; i++) { Things[i] };

P.S. Slow is slow only for a few languages (JavaScript engines) because of compiler's optimization. The best way is to use '<' instead '<=' (or '=') and '--i' instead 'i--'.

Referring to the null object in Python

It's not called null as in other languages, but None. There is always only one instance of this object, so you can check for equivalence with x is None (identity comparison) instead of x == None, if you want.

What does the "@" symbol do in Powershell?

While the above responses provide most of the answer it is useful--even this late to the question--to provide the full answer, to wit:

Array sub-expression (see about_arrays)

Forces the value to be an array, even if a singleton or a null, e.g. $a = @(ps | where name -like 'foo')

Hash initializer (see about_hash_tables)

Initializes a hash table with key-value pairs, e.g. $HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"; WhatIf = $true }

Splatting (see about_splatting)

Let's you invoke a cmdlet with parameters from an array or a hash-table rather than the more customary individually enumerated parameters, e.g. using the hash table just above, Copy-Item @HashArguments

Here strings (see about_quoting_rules)

Let's you create strings with easily embedded quotes, typically used for multi-line strings, e.g.:

$data = @"
line one
line two
something "quoted" here
"@

Because this type of question (what does 'x' notation mean in PowerShell?) is so common here on StackOverflow as well as in many reader comments, I put together a lexicon of PowerShell punctuation, just published on Simple-Talk.com. Read all about @ as well as % and # and $_ and ? and more at The Complete Guide to PowerShell Punctuation. Attached to the article is this wallchart that gives you everything on a single sheet: enter image description here

Open a facebook link by native Facebook app on iOS

I did this in MonoTouch in the following method, I'm sure a pure Obj-C based approach wouldn't be too different. I used this inside a class which had changing URLs at times which is why I just didn't put it in a if/elseif statement.

NSString *myUrls = @"fb://profile/100000369031300|http://www.facebook.com/ytn3rd";
NSArray *urls = [myUrls componentsSeparatedByString:@"|"];
for (NSString *url in urls){
    NSURL *nsurl = [NSURL URLWithString:url];
    if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
        [[UIApplication sharedApplication] openURL:nsurl];
        break;
    }
}

The break is not always called before your app changes to Safari/Facebook. I assume your program will halt there and call it when you come back to it.

iOS Simulator to test website on Mac

iPhoney is designed specifically for Mac users

you can read about it and download it here

HashMap: One Key, multiple Values

You can do something like this (add access modifiers as required):

Map<String,Map<String,String>> complexMap=new HashMap<String,Map<String,String>>();

You can insert data like this:

    Map<String,String> componentMap = new HashMap<String,String>();
    componentMap.put("foo","bar");
    componentMap.put("secondFoo","secondBar");
    complexMap.put("superFoo",componentMap);

The Generated Data Structure would be:

{superFoo={secondFoo=secondBar, foo=bar}}

This way each value for the key should have a unique identifier. Also gives O(1) for fetches,if keys are known.

How to download file in swift?

Try This Code only Swift 3.0 First Create NS Object File Copy this code in created File

import UIKit

class Downloader : NSObject, URLSessionDownloadDelegate {

    var url : URL?
    // will be used to do whatever is needed once download is complete
    var obj1 : NSObject?

    init(_ obj1 : NSObject)
    {
        self.obj1 = obj1
    }

    //is called once the download is complete
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
    {
        //copy downloaded data to your documents directory with same names as source file
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        let destinationUrl = documentsUrl!.appendingPathComponent(url!.lastPathComponent)
        let dataFromURL = NSData(contentsOf: location)
        dataFromURL?.write(to: destinationUrl, atomically: true)

        //now it is time to do what is needed to be done after the download
        //obj1!.callWhatIsNeeded()
    }

    //this is to track progress
    private func URLSession(session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    {
    }

    // if there is an error during download this will be called
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    {
        if(error != nil)
        {
            //handle the error
            print("Download completed with error: \(error!.localizedDescription)");
        }
    }

    //method to be called to download
    func download(url: URL)
    {
        self.url = url

        //download identifier can be customized. I used the "ulr.absoluteString"
        let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
        let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
        let task = session.downloadTask(with: url)
        task.resume()
    }}

then Copy Below Code And put code in place of you want to download file

 object = "http://www.mywebsite.com/myfile.pdf"
       let url1 = URL(string: object!)
        Downloader(url1! as NSObject).download(url: url1!)

How can I select the row with the highest ID in MySQL?

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

How is a CRC32 checksum calculated?

Then there is always Rosetta Code, which shows crc32 implemented in dozens of computer languages. https://rosettacode.org/wiki/CRC-32 and has links to many explanations and implementations.

IIS Request Timeout on long ASP.NET operation

Remove ~ character in location so

path="~/Admin/SomePage.aspx"

becomes

path="Admin/SomePage.aspx"

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

How to create python bytes object from long hex string?

import binascii

binascii.a2b_hex(hex_string)

Thats the way I did it.

Git push requires username and password

As many users has said, you just have to change your Git repository URL from HTTPS to SSH.

If you haven't generated a SSH key in your machine, then your are going to have to do it.

Just as an additional information, after doing this change I still was getting the same error:

Permission Denied.

In my case, the problem was that I was using the Windows Shell to execute the ngh command; since this command should open a prompt to request the SSH phrase and the Windows Shell doesn't open these kinds of prompts, the authentication just failed.

So, I just had to open the Git shell and execute the ngh command there, put the SSH phrase in the prompt every time it asked for it and "voilà"... It just worked fine!

Integrate ZXing in Android Studio

Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        // https://mvnrepository.com/artifact/com.google.zxing/core
        compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
        // https://mvnrepository.com/artifact/com.google.zxing/android-core
        compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'

    }

You can always find latest version core and android core from below links:

https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.google.zxing:android-core:3.3.0'
}

Integrating CSS star rating into an HTML form

This is very easy to use, just copy-paste the code. You can use your own star image in background.

I have created a variable var userRating. you can use this variable to get value from stars.

Enjoy!! :)

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    // Check Radio-box_x000D_
    $(".rating input:radio").attr("checked", false);_x000D_
_x000D_
    $('.rating input').click(function () {_x000D_
        $(".rating span").removeClass('checked');_x000D_
        $(this).parent().addClass('checked');_x000D_
    });_x000D_
_x000D_
    $('input:radio').change(_x000D_
      function(){_x000D_
        var userRating = this.value;_x000D_
        alert(userRating);_x000D_
    }); _x000D_
});
_x000D_
.rating {_x000D_
    float:left;_x000D_
    width:300px;_x000D_
}_x000D_
.rating span { float:right; position:relative; }_x000D_
.rating span input {_x000D_
    position:absolute;_x000D_
    top:0px;_x000D_
    left:0px;_x000D_
    opacity:0;_x000D_
}_x000D_
.rating span label {_x000D_
    display:inline-block;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    text-align:center;_x000D_
    color:#FFF;_x000D_
    background:#ccc;_x000D_
    font-size:30px;_x000D_
    margin-right:2px;_x000D_
    line-height:30px;_x000D_
    border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
}_x000D_
.rating span:hover ~ span label,_x000D_
.rating span:hover label,_x000D_
.rating span.checked label,_x000D_
.rating span.checked ~ span label {_x000D_
    background:#F90;_x000D_
    color:#FFF;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="rating">_x000D_
    <span><input type="radio" name="rating" id="str5" value="5"><label for="str5"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str4" value="4"><label for="str4"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str3" value="3"><label for="str3"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str2" value="2"><label for="str2"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str1" value="1"><label for="str1"></label></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to connect to remote Redis server?

redis-cli -h XXX.XXX.XXX.XXX -p YYYY

xxx.xxx.xxx.xxx is the IP address and yyyy is the port

EXAMPLE from my dev environment

redis-cli -h 10.144.62.3 -p 30000

REDIS CLI COMMANDS

Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.

redis-cli -h redis15.localnet.org -p 6390 ping

SET NOCOUNT ON usage

I know it's pretty old question. but just for update.

Best way to use "SET NOCOUNT ON" is to put it up as a first statement in your SP and setting it OFF again just before the last SELECT statement.

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

How does RewriteBase work in .htaccess

In my own words, after reading the docs and experimenting:

You can use RewriteBase to provide a base for your rewrites. Consider this

# invoke rewrite engine
    RewriteEngine On
    RewriteBase /~new/

# add trailing slash if missing
    rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

This is a real rule I used to ensure that URLs have a trailing slash. This will convert

http://www.example.com/~new/page

to

http://www.example.com/~new/page/

By having the RewriteBase there, you make the relative path come off the RewriteBase parameter.

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

What is a "static" function in C?

"What is a “static” function in C?"

Let's start at the beginning.

It´s all based upon a thing called "linkage":

"An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. 29)There are three kinds of linkage: external, internal, and none."

Source: C18, 6.2.2/1


"In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity."

Source: C18, 6.2.2/2


If a function is defined without a storage-class specifier, the function has external linkage by default:

"If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern."

Source: C18, 6.2.2/5

That means that - if your program is contained of several translation units/source files (.c or .cpp) - the function is visible in all translation units/source files your program has.

This can be a problem in some cases. What if you want to use f.e. two different function (definitions), but with the same function name in two different contexts (actually the file-context).

In C and C++, the static storage-class qualifier applied to a function at file scope (not a static member function of a class in C++ or a function within another block) now comes to help and signifies that the respective function is only visible inside of the translation unit/source file it was defined in and not in the other TLUs/files.

"If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage. 30)"


  1. A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.

Source: C18, 6.2.2/3


Thus, A static function only makes sense, iff:

  1. Your program is contained of several translation units/source files (.c or .cpp).

and

  1. You want to limit the scope of a function to the file, in which the specific function is defined.

If not both of these requirements match, you don't need to wrap your head around about qualifying a function as static.


Side Notes:

  • As already mentioned, A static function has absolutely no difference at all between C and C++, as this is a feature C++ inherited from C.

It does not matter that in the C++ community, there is a heartbreaking debate about the depreciation of qualifying functions as static in comparison to the use of unnamed namespaces instead, first initialized by a misplaced paragraph in the C++03 standard, declaring the use of static functions as deprecated which soon was revised by the committee itself and removed in C++11.

This was subject to various SO questions:

Unnamed/anonymous namespaces vs. static functions

Superiority of unnamed namespace over static?

Why an unnamed namespace is a "superior" alternative to static?

Deprecation of the static keyword... no more?

In fact, it is not deprecated per C++ standard yet. Thus, the use of static functions is still legit. Even if unnamed namespaces have advantages, the discussion about using or not using static functions in C++ is subject to one´s one mind (opinion-based) and with that not suitable for this website.

How can I return the difference between two lists?

You can use CollectionUtils from Apache Commons Collections 4.0:

new ArrayList<>(CollectionUtils.subtract(a, b))

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

How do you use "git --bare init" repository?

I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.

Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.

I've tried to add some notes along the way for those less familiar with git.

1. Initialise the bare repo...

> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/

This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.

Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.

2a. Create a new working folder (no existing files) by cloning the empty repo

git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.

This command will only work if /path/to/work does not exist or is an empty folder. Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work and run git status, you'll get something like:

On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)

but this is a lie. You are not really on branch master (because git branch returns nothing) and so far, there are no commits.

Next, copy/move/create some files in the working folder, add them to git and create the first commit.

> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
 1 file changed, 1 insertion(+)
 create mode 100644 afile.txt

The git config commands are only needed if you haven't already told git who you are. Note that if you now run git branch, you'll now see the master branch listed. Now run git status:

On branch master
Your branch is based on 'origin/master', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

nothing to commit, working directory clean

This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.

> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master

At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

> git pull
Already up-to-date.
> git push origin master
Everything up-to-date

2b. Create a working folder from existing files If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.

> cd /path/to/work_with_stuff
> git init 
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"

[master (root-commit) 614ab02] added stuff
 20 files changed, 1431 insertions(+)
 create mode 100644 stuff.txt
...

At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.

> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Note the -u flag on git push to set the (new) tracked upstream branch. Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.

Viewing full version tree in git

There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":

[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

if...else within JSP or JSTL

Should I use JSTL ?

Yes.

You can use <c:if> and <c:choose> tags to make conditional rendering in jsp using JSTL.

To simulate if , you can use:

<c:if test="condition"></c:if>

To simulate if...else, you can use:

<c:choose>
    <c:when test="${param.enter=='1'}">
        pizza. 
        <br />
    </c:when>    
    <c:otherwise>
        pizzas. 
        <br />
    </c:otherwise>
</c:choose>

How to display a json array in table format?

DEMO

var obj=[
        {
            id : "001",
            name : "apple",
            category : "fruit",
            color : "red"
        },
        {
            id : "002",
            name : "melon",
            category : "fruit",
            color : "green"
        },
        {
            id : "003",
            name : "banana",
            category : "fruit",
            color : "yellow"
        }
    ]
    var tbl=$("<table/>").attr("id","mytable");
    $("#div1").append(tbl);
    for(var i=0;i<obj.length;i++)
    {
        var tr="<tr>";
        var td1="<td>"+obj[i]["id"]+"</td>";
        var td2="<td>"+obj[i]["name"]+"</td>";
        var td3="<td>"+obj[i]["color"]+"</td></tr>";

       $("#mytable").append(tr+td1+td2+td3); 

    }   

How to create PDF files in Python

You can try this(Python-for-PDF-Generation) or you can try PyQt, which has support for printing to pdf.

Python for PDF Generation

The Portable Document Format (PDF) lets you create documents that look exactly the same on every platform. Sometimes a PDF document needs to be generated dynamically, however, and that can be quite a challenge. Fortunately, there are libraries that can help. This article examines one of those for Python.

Read more at http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/#whoCFCPh3TAks368.99

Is it safe to delete a NULL pointer?

From the C++0x draft Standard.

$5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"

Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.

As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

first remove the unstable version:

adb uninstall problematic-package-name

; and then reinstall the apk.

Programmatically set the initial view controller using Storyboards

Swift 4, Xcode 9

in file AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let firstVC = storyboard.instantiateViewController(withIdentifier: "firstViewController") as! firstViewController
    self.window?.rootViewController = firstVC
}

How to print the data in byte array as characters?

byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
    System.out.format("%d ", c);
}
System.out.println();

gets you

1 -2 5 66 

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

How to force remounting on React components?

Use setState in your view to change employed property of state. This is example of React render engine.

 someFunctionWhichChangeParamEmployed(isEmployed) {
      this.setState({
          employed: isEmployed
      });
 }

 getInitialState() {
      return {
          employed: true
      }
 },

 render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

JavaScript single line 'if' statement - best syntax, this alternative?

As a lot of people have said, if you're looking for an actual 1 line if then:

    if (Boolean_expression) do.something();

is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):

    (Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();

ALSO:

    var something = (Boolean_expression) ? trueValueHardware : falseATRON;

However, I saw one very cool example. Shouts to @Peter-Oslson for &&

    (Boolean_expression) && do.something();

Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan

How to automatically select all text on focus in WPF TextBox?

An easy way to override the mouseDown and select all after doubleclick is:

public class DoubleClickTextBox: TextBox
{

    public override void EndInit()
    {
        base.EndInit();            
    }

    protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e)
    {
        base.OnMouseEnter(e);
        this.Cursor = Cursors.Arrow;
    }
    protected override void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e)
    {

    }

    protected override void OnMouseDoubleClick(System.Windows.Input.MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        this.SelectAll();
    }
}

How do I get TimeSpan in minutes given two Dates?

double totalMinutes = (end-start).TotalMinutes;

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Can CSS detect the number of children an element has?

No, there is nothing like this in CSS. You can, however, use JavaScript to calculate the number of children and apply styles.

Error Running React Native App From Terminal (iOS)

By default, after installing Xcode command-line not selected, so open Xcode and go to Preferences >> Locations and set Command Line Tools...

This worked for me in MAC High Sierra, Xcode Version 9.3:

Xcode Preferences

Press i to open iOS emulator...

Press a to open Android device or emulator, or i to open iOS emulator.

And You can see a cool new iPhone simulator like below image:

React Native prints, I'm Alireza Dezfoolian, a Front End Developer!

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

How to establish ssh key pair when "Host key verification failed"

Also sometimes there is situation when you are working on serial console, then checking above command in verbose mode -v will show you /dev/tty does not exists, while it does.

In above case just remove /dev/tty and create a symlink of /dev/ttyS0 to /dev/tty.

Add a auto increment primary key to existing table in oracle

If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row

UPDATE table_name
   SET new_pk_column = sequence_name.nextval;

Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)

ALTER TABLE table_name
  ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )

If you want to generate the key automatically, you'd need to add a trigger

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  :new.new_pk_column := sequence_name.nextval;
END;

If you are on an older version of Oracle, the syntax is a bit more cumbersome

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  SELECT sequence_name.nextval
    INTO :new.new_pk_column
    FROM dual;
END;

Inserting a blank table row with a smaller height

You don't need an extra table row to create space inside a table. See this jsFiddle.
(I made the gap light grey in colour, so you can see it, but you can change that to transparent.)

Using a table row just for display purposes is table abuse!

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Sum of values in an array using jQuery

var total = 0;
$.each(someArray,function() {
    total += parseInt(this, 10);
});

Could not find module FindOpenCV.cmake ( Error in configuration process)

On my Fedora machine, when I typed "make" I got an error saying it could not find "cv.h". I fixed this by modifying my "OpenCVConfig.cmake" file.

Before:

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib64")

After:

SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")

SET(OpenCV_LIB_DIR "/usr/lib64")

Disable button after click in JQuery

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

How do I compare strings in GoLang?

Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:

Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..) seems like the most performant choice):

goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4               10000        182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4        10000        114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4                10000       2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4               10000       3592486 ns/op

BenchmarkStringOps/one_string_in_caps::equality_op-4               10000        417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4        10000        153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4                10000       3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4               10000       3861189 ns/op

BenchmarkStringOps/weird_casing_situation::equality_op-4           10000        619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4    10000        148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4            10000       3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4           10000       3637832 ns/op

Since there are quite a few options, so here's the code to generate benchmarks.

package main

import (
    "fmt"
    "strings"
    "testing"

    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func BenchmarkStringOps(b *testing.B) {
    foldCaser := cases.Fold()
    lowerCaser := cases.Lower(language.English)

    tests := []struct{
        description string
        first, second string
    }{
        {
            description: "both strings equal",
            first: "aaaa",
            second: "aaaa",
        },
        {
            description: "one string in caps",
            first: "aaaa",
            second: "AAAA",
        },
        {
            description: "weird casing situation",
            first: "aAaA",
            second: "AaAa",
        },
    }

    for _, tt := range tests {
        b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringEqualsOperation(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsEqualFold(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
            }
        })

        b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
            }
        })
    }
}

func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.ToLower(first) == strings.ToLower(second)
    }
}

func benchmarkStringsEqualFold(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.EqualFold(first, second)
    }
}

func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

What is the difference between match_parent and fill_parent?

Both, FILL_PARENT and MATCH_PARENT are the same properties. FILL_PARENT was deprecated in API level 8.

How to Change Margin of TextView

TextView does not support setMargins. Android docs say:

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

Pandas Replace NaN with blank/empty string

import numpy as np
df1 = df.replace(np.nan, '', regex=True)

This might help. It will replace all NaNs with an empty string.

pull out p-values and r-squared from a linear regression

I came across this question while exploring suggested solutions for a similar problem; I presume that for future reference it may be worthwhile to update the available list of answer with a solution utilising the broom package.

Sample code

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
require(broom)
glance(fit)

Results

>> glance(fit)
  r.squared adj.r.squared    sigma statistic    p.value df    logLik      AIC      BIC deviance df.residual
1 0.5442762     0.5396729 1.502943  118.2368 1.3719e-18  2 -183.4527 372.9055 380.7508 223.6251          99

Side notes

I find the glance function is useful as it neatly summarises the key values. The results are stored as a data.frame which makes further manipulation easy:

>> class(glance(fit))
[1] "data.frame"

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

What are the differences between "=" and "<-" assignment operators in R?

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Storing Data in MySQL as JSON

I would say the only two reasons to consider this are:

  • performance just isn't good enough with a normalised approach
  • you cannot readily model your particularly fluid/flexible/changing data

I wrote a bit about my own approach here:

What scalability problems have you encountered using a NoSQL data store?

(see the top answer)

Even JSON wasn't quite fast enough so we used a custom-text-format approach. Worked / continues to work well for us.

Is there a reason you're not using something like MongoDB? (could be MySQL is "required"; just curious)

Delete directories recursively in Java

While files can easily be deleted using file.delete(), directories are required to be empty to be deleted. Use recursion to do this easily. For example:

public static void clearFolders(String[] args) {
        for(String st : args){
            File folder = new File(st);
            if (folder.isDirectory()) {
                File[] files = folder.listFiles();
                if(files!=null) { 
                    for(File f: files) {
                        if (f.isDirectory()){
                            clearFolders(new String[]{f.getAbsolutePath()});
                            f.delete();
                        } else {
                            f.delete();
                        }
                    }
                }
            }
        }
    }

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I'm not 100% sure, but I believe the error was caused by some client-side JavaScript that was turning exports into an object. Some code in the Slick plugin (see below) calls the require function if exports is not undefined.

Here's the portion of code I had to change in slick.js. You can see I am just commenting out the if statements, and, instead, I'm just calling factory(jQuery).

;(function(factory) {
console.log('slick in factory', define, 'exports', exports, 'factory', factory);
'use strict';
// if (typeof define === 'function' && define.amd) {
//     define(['jquery'], factory);
// } else if (typeof exports !== 'undefined') {
//     module.exports = factory(require('jquery'));
// } else {
//     factory(jQuery);
// }
factory(jQuery);
}

MongoDB SELECT COUNT GROUP BY

This type of query worked for me:

 db.events.aggregate({$group: {_id : "$date", number:  { $sum : 1} }} )

See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

FileProvider - IllegalArgumentException: Failed to find configured root

It depends what kind of storage you want to do, INTERNAL or EXTERNAL

for EXTERNAL STORAGE

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="my_images" path="my_images" />
</paths>

but for INTERNAL STORAGE, be careful with the path, because it uses getFilesDir() method which mean that your file will be located in the root directory for the app ("/")

  File storeDir = getFilesDir(); // path "/"

So your provider file must be like this:

<paths>
    <files-path name="my_images" path="/" />
</paths>

How to use a Java8 lambda to sort a stream in reverse order?

In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8

import java.util.Comparator;;
import java.util.stream.Collectors;

Arrays.asList(files).stream()
    .sorted(Comparator.comparing(File::getLastModified).reversed())
    .collect(Collectors.toList());

How to make a owl carousel with arrows instead of next previous

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

How can I use Guzzle to send a POST request in JSON?

The answer from @user3379466 can be made to work by setting $data as follows:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

How can I select an element in a component template?

For people trying to grab the component instance inside a *ngIf or *ngSwitchCase, you can follow this trick.

Create an init directive.

import {
    Directive,
    EventEmitter,
    Output,
    OnInit,
    ElementRef
} from '@angular/core';

@Directive({
    selector: '[init]'
})
export class InitDirective implements OnInit {
    constructor(private ref: ElementRef) {}

    @Output() init: EventEmitter<ElementRef> = new EventEmitter<ElementRef>();

    ngOnInit() {
        this.init.emit(this.ref);
    }
}

Export your component with a name such as myComponent

@Component({
    selector: 'wm-my-component',
    templateUrl: 'my-component.component.html',
    styleUrls: ['my-component.component.css'],
    exportAs: 'myComponent'
})
export class MyComponent { ... }

Use this template to get the ElementRef AND MyComponent instance

<div [ngSwitch]="type">
    <wm-my-component
           #myComponent="myComponent"
           *ngSwitchCase="Type.MyType"
           (init)="init($event, myComponent)">
    </wm-my-component>
</div>

Use this code in TypeScript

init(myComponentRef: ElementRef, myComponent: MyComponent) {
}

What does 'corrupted double-linked list' mean

I have found the answer to my question myself:)

So what I didn't understand was how the glibc could differentiate between a Segfault and a corrupted double-linked list, because according to my understanding, from perspective of glibc they should look like the same thing. Because if I implement a double-linked list inside my program, how could the glibc possibly know that this is a double-linked list, instead of any other struct? It probably can't, so thats why i was confused.

Now I've looked at malloc/malloc.c inside the glibc's code, and I see the following:

1543 /* Take a chunk off a bin list */
1544 #define unlink(P, BK, FD) {                                            \
1545   FD = P->fd;                                                          \
1546   BK = P->bk;                                                          \
1547   if (__builtin_expect (FD->bk != P || BK->fd != P, 0))                \
1548     malloc_printerr (check_action, "corrupted double-linked list", P); \
1549   else {                                                               \
1550     FD->bk = BK;                                                       \
1551     BK->fd = FD;                                                       \

So now this suddenly makes sense. The reason why glibc can know that this is a double-linked list is because the list is part of glibc itself. I've been confused because I thought glibc can somehow detect that some programming is building a double-linked list, which I wouldn't understand how that works. But if this double-linked list that it is talking about, is part of glibc itself, of course it can know it's a double-linked list.

I still don't know what has triggered this error. But at least I understand the difference between corrupted double-linked list and a Segfault, and how the glibc can know this struct is supposed to be a double-linked list:)

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

How to install JDK 11 under Ubuntu?

I came here looking for the answer and since no one put the command for the oracle Java 11 but only openjava 11 I figured out how to do it on Ubuntu, the syntax is as following:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt update
sudo apt install oracle-java11-installer

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

How to get Top 5 records in SqLite?

TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).

select * from `Table_Name` LIMIT 5;

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

How do I remove background-image in css?

Replace the rule you have with the following:

div:not(#a) { // add your bg image here //}

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Is it possible to change the package name of an Android app on Google Play?

No, you cannot change package name unless you're okay with publishing it as a new app in Play Store:

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application. Android manual confirms it as well here:

Caution: Once you publish your application, you cannot change the package name. The package name defines your application's identity, so if you change it, then it is considered to be a different application and users of the previous version cannot update to the new version. If you're okay with publishing new version of your app as a completely new entity, you can do it of course - just remove old app from Play Store (if you want) and publish new one, with different package name.

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

Create a simple 10 second countdown

_x000D_
_x000D_
var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
_x000D_
_x000D_

How to convert strings into integers in Python?

See this function

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

Then

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

You can also check

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

How to do case insensitive string comparison?

Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:

  1. Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
  2. In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
  3. In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.

Taking points (1) and (2) into consideration, an example would be:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}

How do I add an existing Solution to GitHub from Visual Studio 2013

Well, I understand this question is Visual Studio GUI related, but maybe the asker can try this trick also. Just giving a different perspective in solving this problem.

I like to use terminal a lot for GIT, so here are the simple steps:

Pre-requisites...

  • If it's Linux or MAC, you should have git packages installed on your machine
  • If it's Windows, you can try to download git bash software

Now,

  1. Goto Github.com
  2. In your account, create a New Repository
  3. Don't create any file inside the repository. Keep it empty. Copy its URL. It should be something like https://github.com/Username/ProjectName.git

  4. Open up the terminal and redirect to your Visual Studio Project directory

  5. Configure your credentials

    git config --global user.name "your_git_username"
    git config --global user.email "your_git_email"
    
  6. Then type these commands

    git init
    git add .
    git commit -m "First Migration Commit"
    git remote add origin paste_your_URL_here
    git push -u origin master
    

Done...Hope this helps

How can I get the client's IP address in ASP.NET MVC?

The simple answer is to use the HttpRequest.UserHostAddress property.

Example: From within a Controller:

using System;
using System.Web.Mvc;

namespace Mvc.Controllers
{
    public class HomeController : ClientController
    {
        public ActionResult Index()
        {
            string ip = Request.UserHostAddress;

            ...
        }
    }
}

Example: From within a helper class:

using System.Web;

namespace Mvc.Helpers
{
    public static class HelperClass
    {
        public static string GetIPHelper()
        {
            string ip = HttpContext.Current.Request.UserHostAddress;
            ..
        }
    }
}

BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.

Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.


Original Answer

Request.UserHostAddress

The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:

public static string getIPAddress(HttpRequestBase request)
{
    string szRemoteAddr = request.UserHostAddress;
    string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
    string szIP = "";

    if (szXForwardedFor == null)
    {
        szIP = szRemoteAddr;
    }
    else
    {
        szIP = szXForwardedFor;
        if (szIP.IndexOf(",") > 0)
        {
            string [] arIPs = szIP.Split(',');

            foreach (string item in arIPs)
            {
                if (!isPrivateIP(item))
                {
                    return item;
                }
            }
        }
    }
    return szIP;
}

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

File opens instead of downloading in internet explorer in a href link

The download attribute is not supported in IE (see http://caniuse.com/#search=download%20attribute).

That suggests the download attribute is only supported by firefox, chrome, opera and the latest version of blackberry's browser.

For other browsers you'll need to use more traditional methods to force download. That is server side code is necessary to set an appropriate Content-Type and Content-Disposition header to tell (or trick depending on your point of view) the browser to download the item. Headers should look like this:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

(thanks to antyrat for the copy and paste of the headers)

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

Jenkins fails when running "service start jenkins"

I had below error:

Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.

Solution was to revert the NAME to jenkins in the below file (Earlier I have changed it to 'NAME=ubuntu'):

sudo vi /etc/default/jenkins
    NAME=jenkins

Now restart passed:

sudo service jenkins restart
sudo systemctl restart jenkins.service

Hope that helps.

how to set font size based on container size?

It cannot be accomplished with css font-size

Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs.

So I solved my problem like this:

# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`

test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH

Et voilà !

How can I pass a parameter in Action?

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

And the caller code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

Check if a file exists with wildcard in shell script

I use this:

filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`  
if [ $filescount -gt 0 ]; then  
    blah  
fi

How do I get my Maven Integration tests to run

You can follow the maven documentation to run the unit tests with the build and run the integration tests separately.

<project>
    <properties>
        <skipTests>true</skipTests>
    </properties>
    [...]
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.20.1</version>
                <configuration>
                    <skipITs>${skipTests}</skipITs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    [...]
</project>

This will allow you to run with all integration tests disabled by default. To run them, you use this command:

mvn install -DskipTests=false

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

Does "display:none" prevent an image from loading?

Quirks Mode: images and display: none

When image has display: none or is inside an element with display:none, the browser may opt not to download the image until the display is set to another value.

Only Opera downloads the image when you switch the display to block. All other browsers download it immediately.

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

id1.keySet().stream()
        .filter(x -> x == 1)
        .map(x -> id1.get(x))
        .collect(Collectors.toList())

What is "entropy and information gain"?

Informally

entropy is availability of information or knowledge, Lack of information will leads to difficulties in prediction of future which is high entropy (next word prediction in text mining) and availability of information/knowledge will help us more realistic prediction of future (low entropy).

Relevant information of any type will reduce entropy and helps us predict more realistic future, that information can be word "meat" is present in sentence or word "meat" is not present. This is called Information Gain


Formally

entropy is lack of order of predicability

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

If You Are Able to Edit the Offending Stylesheet

If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.

If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.

If You Are Not Able to Edit the Offending Stylesheet

If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important keyword.

An example:

.override {
    border: 1px solid #000 !important;
}

.a_class {
    border: 2px solid red;
}

And the HTML:

<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>

Live example

Try to use !important only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

How to create a drop-down list?

In Kotlin you can do as:

First, put this code in your layout

   <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

Then you can do in onCreate() in Activity as ->

   val spinner = findViewById<Spinner>(R.id.spinner)
    val items = arrayOf("500g", "1kg", "2kg")
    val adapter = ArrayAdapter<String>(
        this,
        android.R.layout.simple_spinner_dropdown_item,
        items
    )
    spinner.setAdapter(adapter)

You can get listener from dropdown as:

 spinner.onItemSelectedListener = object : OnItemSelectedListener {
        override fun onItemSelected(
            arg0: AdapterView<*>?,
            arg1: View?,
            arg2: Int,
            arg3: Long
        ) {
            // Do what you want
            val items = spinner.selectedItem.toString()
            
        }

        override fun onNothingSelected(arg0: AdapterView<*>?) {}
    }

What are ABAP and SAP?

SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).

ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.

SAP and ABAP abstract the DB and run atop various underlying DBMSs.

SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.

Escape double quotes in a string

Please explain your problem. You say:

But this involves adding character " to the string.

What problem is that? You can't type string foo = "Foo"bar"";, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:

@"""".Length == "\"".Length == 1

How do I convert NSMutableArray to NSArray?

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

Table is marked as crashed and should be repaired

This means your MySQL table is corrupted and you need to repair it. Use

myisamchk -r /DB_NAME/wp_posts

from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

function bytes2Size(byteVal){
    var units=["Bytes", "KB", "MB", "GB", "TB"];
    var kounter=0;
    var kb= 1024;
    var div=byteVal/1;
    while(div>=kb){
        kounter++;
        div= div/kb;
    }
    return div.toFixed(1) + " " + units[kounter];
}

select data up to a space?

If the first column is always the same size (including the spaces), then you can just take those characters (via LEFT) and clean up the spaces (with RTRIM):

SELECT RTRIM(LEFT(YourColumn, YourColumnSize))

Alternatively, you can extract the second (or third, etc.) column (using SUBSTRING):

SELECT RTRIM(SUBSTRING(YourColumn, PreviousColumnSizes, YourColumnSize))

One benefit of this approach (especially if YourColumn is the result of a computation) is that YourColumn is only specified once.

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

react hooks useEffect() cleanup for only componentWillUnmount?

useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

enter image description here

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

Creating a SearchView that looks like the material design guidelines

After a week of puzzling over this. I think I've figured it out.
I'm now using just an EditText inside of the Toolbar. This was suggested to me by oj88 on reddit.

I now have this:
New SearchView

First inside onCreate() of my activity I added the EditText with an image view on the right hand side to the Toolbar like this:

    // Setup search container view
    searchContainer = new LinearLayout(this);
    Toolbar.LayoutParams containerParams = new Toolbar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    containerParams.gravity = Gravity.CENTER_VERTICAL;
    searchContainer.setLayoutParams(containerParams);

    // Setup search view
    toolbarSearchView = new EditText(this);
    // Set width / height / gravity
    int[] textSizeAttr = new int[]{android.R.attr.actionBarSize};
    int indexOfAttrTextSize = 0;
    TypedArray a = obtainStyledAttributes(new TypedValue().data, textSizeAttr);
    int actionBarHeight = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
    a.recycle();
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, actionBarHeight);
    params.gravity = Gravity.CENTER_VERTICAL;
    params.weight = 1;
    toolbarSearchView.setLayoutParams(params);

    // Setup display
    toolbarSearchView.setBackgroundColor(Color.TRANSPARENT);
    toolbarSearchView.setPadding(2, 0, 0, 0);
    toolbarSearchView.setTextColor(Color.WHITE);
    toolbarSearchView.setGravity(Gravity.CENTER_VERTICAL);
    toolbarSearchView.setSingleLine(true);
    toolbarSearchView.setImeActionLabel("Search", EditorInfo.IME_ACTION_UNSPECIFIED);
    toolbarSearchView.setHint("Search");
    toolbarSearchView.setHintTextColor(Color.parseColor("#b3ffffff"));
    try {
        // Set cursor colour to white
        // https://stackoverflow.com/a/26544231/1692770
        // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
        Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
        f.setAccessible(true);
        f.set(toolbarSearchView, R.drawable.edittext_whitecursor);
    } catch (Exception ignored) {
    }

    // Search text changed listener
    toolbarSearchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.container);
            if (mainFragment != null && mainFragment instanceof MainListFragment) {
                ((MainListFragment) mainFragment).search(s.toString());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            // https://stackoverflow.com/a/6438918/1692770
            if (s.toString().length() <= 0) {
                toolbarSearchView.setHintTextColor(Color.parseColor("#b3ffffff"));
            }
        }
    });
    ((LinearLayout) searchContainer).addView(toolbarSearchView);

    // Setup the clear button
    searchClearButton = new ImageView(this);
    Resources r = getResources();
    int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, r.getDisplayMetrics());
    LinearLayout.LayoutParams clearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    clearParams.gravity = Gravity.CENTER;
    searchClearButton.setLayoutParams(clearParams);
    searchClearButton.setImageResource(R.drawable.ic_close_white_24dp); // TODO: Get this image from here: https://github.com/google/material-design-icons
    searchClearButton.setPadding(px, 0, px, 0);
    searchClearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toolbarSearchView.setText("");
        }
    });
    ((LinearLayout) searchContainer).addView(searchClearButton);

    // Add search view to toolbar and hide it
    searchContainer.setVisibility(View.GONE);
    toolbar.addView(searchContainer);

This worked, but then I came across an issue where onOptionsItemSelected() wasn't being called when I tapped on the home button. So I wasn't able to cancel the search by pressing the home button. I tried a few different ways of registering the click listener on the home button but they didn't work.

Eventually I found out that the ActionBarDrawerToggle I had was interfering with things, so I removed it. This listener then started working:

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // toolbarHomeButtonAnimating is a boolean that is initialized as false. It's used to stop the user pressing the home button while it is animating and breaking things.
            if (!toolbarHomeButtonAnimating) {
                // Here you'll want to check if you have a search query set, if you don't then hide the search box.
                // My main fragment handles this stuff, so I call its methods.
                FragmentManager fragmentManager = getFragmentManager();
                final Fragment fragment = fragmentManager.findFragmentById(R.id.container);
                if (fragment != null && fragment instanceof MainListFragment) {
                    if (((MainListFragment) fragment).hasSearchQuery() || searchContainer.getVisibility() == View.VISIBLE) {
                        displaySearchView(false);
                        return;
                    }
                }
            }

            if (mDrawerLayout.isDrawerOpen(findViewById(R.id.navigation_drawer)))
                mDrawerLayout.closeDrawer(findViewById(R.id.navigation_drawer));
            else
                mDrawerLayout.openDrawer(findViewById(R.id.navigation_drawer));
        }
    });

So I can now cancel the search with the home button, but I can't press the back button to cancel it yet. So I added this to onBackPressed():

    FragmentManager fragmentManager = getFragmentManager();
    final Fragment mainFragment = fragmentManager.findFragmentById(R.id.container);
    if (mainFragment != null && mainFragment instanceof MainListFragment) {
        if (((MainListFragment) mainFragment).hasSearchQuery() || searchContainer.getVisibility() == View.VISIBLE) {
            displaySearchView(false);
            return;
        }
    }

I created this method to toggle visibility of the EditText and menu item:

public void displaySearchView(boolean visible) {
    if (visible) {
        // Stops user from being able to open drawer while searching
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        // Hide search button, display EditText
        menu.findItem(R.id.action_search).setVisible(false);
        searchContainer.setVisibility(View.VISIBLE);

        // Animate the home icon to the back arrow
        toggleActionBarIcon(ActionDrawableState.ARROW, mDrawerToggle, true);

        // Shift focus to the search EditText
        toolbarSearchView.requestFocus();

        // Pop up the soft keyboard
        new Handler().postDelayed(new Runnable() {
            public void run() {
                toolbarSearchView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0));
                toolbarSearchView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0));
            }
        }, 200);
    } else {
        // Allows user to open drawer again
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        // Hide the EditText and put the search button back on the Toolbar.
        // This sometimes fails when it isn't postDelayed(), don't know why.
        toolbarSearchView.postDelayed(new Runnable() {
            @Override
            public void run() {
                toolbarSearchView.setText("");
                searchContainer.setVisibility(View.GONE);
                menu.findItem(R.id.action_search).setVisible(true);
            }
        }, 200);

        // Turn the home button back into a drawer icon
        toggleActionBarIcon(ActionDrawableState.BURGER, mDrawerToggle, true);

        // Hide the keyboard because the search box has been hidden
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(toolbarSearchView.getWindowToken(), 0);
    }
}

I needed a way to toggle the home button on the toolbar between the drawer icon and the back button. I eventually found the method below in this SO answer. Though I modified it slightly to made more sense to me:

private enum ActionDrawableState {
    BURGER, ARROW
}

/**
 * Modified version of this, https://stackoverflow.com/a/26836272/1692770<br>
 * I flipped the start offset around for the animations because it seemed like it was the wrong way around to me.<br>
 * I also added a listener to the animation so I can find out when the home button has finished rotating.
 */
private void toggleActionBarIcon(final ActionDrawableState state, final ActionBarDrawerToggle toggle, boolean animate) {
    if (animate) {
        float start = state == ActionDrawableState.BURGER ? 1.0f : 0f;
        float end = Math.abs(start - 1);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ValueAnimator offsetAnimator = ValueAnimator.ofFloat(start, end);
            offsetAnimator.setDuration(300);
            offsetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
            offsetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float offset = (Float) animation.getAnimatedValue();
                    toggle.onDrawerSlide(null, offset);
                }
            });
            offsetAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    toolbarHomeButtonAnimating = false;
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            toolbarHomeButtonAnimating = true;
            offsetAnimator.start();
        }
    } else {
        if (state == ActionDrawableState.BURGER) {
            toggle.onDrawerClosed(null);
        } else {
            toggle.onDrawerOpened(null);
        }
    }
}

This works, I've managed to work out a few bugs that I found along the way. I don't think it's 100% but it works well enough for me.

EDIT: If you want to add the search view in XML instead of Java do this:

toolbar.xml:

<android.support.v7.widget.Toolbar 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    contentInsetLeft="72dp"
    contentInsetStart="72dp"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:minHeight="?attr/actionBarSize"
    app:contentInsetLeft="72dp"
    app:contentInsetStart="72dp"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"
    app:theme="@style/ActionBarThemeOverlay">

    <LinearLayout
        android:id="@+id/search_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/search_view"
            android:layout_width="0dp"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:gravity="center_vertical"
            android:hint="Search"
            android:imeOptions="actionSearch"
            android:inputType="text"
            android:maxLines="1"
            android:paddingLeft="2dp"
            android:singleLine="true"
            android:textColor="#ffffff"
            android:textColorHint="#b3ffffff" />

        <ImageView
            android:id="@+id/search_clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:src="@drawable/ic_close_white_24dp" />
    </LinearLayout>
</android.support.v7.widget.Toolbar>

onCreate() of your Activity:

    searchContainer = findViewById(R.id.search_container);
    toolbarSearchView = (EditText) findViewById(R.id.search_view);
    searchClearButton = (ImageView) findViewById(R.id.search_clear);

    // Setup search container view
    try {
        // Set cursor colour to white
        // https://stackoverflow.com/a/26544231/1692770
        // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
        Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
        f.setAccessible(true);
        f.set(toolbarSearchView, R.drawable.edittext_whitecursor);
    } catch (Exception ignored) {
    }

    // Search text changed listener
    toolbarSearchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.container);
            if (mainFragment != null && mainFragment instanceof MainListFragment) {
                ((MainListFragment) mainFragment).search(s.toString());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    // Clear search text when clear button is tapped
    searchClearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toolbarSearchView.setText("");
        }
    });

    // Hide the search view
    searchContainer.setVisibility(View.GONE);

Call ASP.NET function from JavaScript?

Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

It is a little tricky though... :)

i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}

ii. This should add (using Tab-Tab) this function to your code file:

public void RaisePostBackEvent(string eventArgument) { }

iii. In your onclick event in JavaScript, write the following code:

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Handling ExecuteScalar() when no results are returned

sql = "select username from usermst where userid=2"
var _getusername = command.ExecuteScalar();
if(_getusername != DBNull.Value)
{
    getusername = _getusername.ToString();
}  

Update using LINQ to SQL

In the absence of more detailed info:

using(var dbContext = new dbDataContext())
{
    var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
    if(data != null)
    {
        data.SomeField = newValue;
    }
    dbContext.SubmitChanges();
}

What is the difference between vmalloc and kmalloc?

The kmalloc() & vmalloc() functions are a simple interface for obtaining kernel memory in byte-sized chunks.

  1. The kmalloc() function guarantees that the pages are physically contiguous (and virtually contiguous).

  2. The vmalloc() function works in a similar fashion to kmalloc(), except it allocates memory that is only virtually contiguous and not necessarily physically contiguous.

Conditionally formatting cells if their value equals any value of another column

Here is the formula

create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A

=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))


enter image description here

here is the example sheet to download if you encounter problems


UPDATE
here is @pnuts's suggestion which works perfect as well:

=MATCH(A1,B:B,0)>0


Pretty-Printing JSON with PHP

If you are working with MVC

try doing this in your controller

public function getLatestUsers() {
    header('Content-Type: application/json');
    echo $this->model->getLatestUsers(); // this returns json_encode($somedata, JSON_PRETTY_PRINT)
}

then if you call /getLatestUsers you will get a pretty JSON output ;)

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

C# Dictionary get item by index

Is it useful to look beyond the exact question asked to alternatives that might better suit the need? Create your own class or struct, then make an array of those to operate on instead of being stuck with the operation of the KeyValuePair collection behavior of the Dictionary type.

Using a struct instead of a class will allow equality comparison of two different cards without implementing your own comparison code.

public struct Card
{
  public string Name;
  public int Value;

}

private int random()
{
  // Whatever
  return 1;
}

private static Card[] Cards = new Card[]
{
    new Card() { Name = "7", Value = 7 },
    new Card() { Name = "8", Value = 8 },
    new Card() { Name = "9", Value = 9 },
    new Card() { Name = "10", Value = 10 },
    new Card() { Name = "J", Value = 1 },
    new Card() { Name = "Q", Value = 1 },
    new Card() { Name = "K", Value = 1 },
    new Card() { Name = "A", Value = 1 }
};

private void CardDemo()
{
  int value, maxVal;
  string name;
  Card card, card2;
  List<Card> lowCards;

  value = Cards[random()].Value;
  name = Cards[random()].Name;
  card = Cards[random()];
  card2 = Cards[1];
  // card.Equals(card2) returns true
  lowCards = Cards.Where(x => x.Value == 1).ToList();
  maxVal = Cards.Max(x => x.Value);

}

Convert string into integer in bash script - "Leading Zero" number error

In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash - Use bc An arbitrary precision calculator language

Example:

a="000001"
b=$(echo $a | bc)
echo $b

Output: 1

From Bash manual:

"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"

Forcing Internet Explorer 9 to use standards document mode

I have faced issue like my main page index.jsp contains the below line but eventhough rendering was not proper in IE. Found the issue and I have added the code in all the files which I included in index.jsp. Hurray! it worked.

So You need to add below code in all the files which you include into the page otherwise it wont work.

    <!doctype html>
    <head>
      <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>

Get the number of rows in a HTML table

Try:

var count = $('#gvPerformanceResult tr').length;

Modify SVG fill color when being served as Background-Image

A lot of IFs, but if your pre base64 encoded SVG starts:

<svg fill="#000000

Then the base64 encoded string will start:

PHN2ZyBmaWxsPSIjMDAwMDAw

if the pre-encoded string starts:

<svg fill="#bfa76e

then this encodes to:

PHN2ZyBmaWxsPSIjYmZhNzZl

Both encoded strings start the same:

PHN2ZyBmaWxsPSIj

The quirk of base64 encoding is every 3 input characters become 4 output characters. With the SVG starting like this then the 6-character hex fill color starts exactly on an encoding block 'boundary'. Therefore you can easily do a cross-browser JS replace:

output = input.replace(/MDAwMDAw/, "YmZhNzZl");

But tnt-rox answer above is the way to go moving forward.

Spring Boot how to hide passwords in properties file

In case you are using quite popular in Spring Boot environment Kubernetes (K8S) or OpenShift, there's a possibility to store and retrieve application properties on runtime. This technique called secrets. In your configuration yaml file for Kubernetes or OpenShift you declare variable and placeholder for it, and on K8S\OpenShift side declare actual value which corresponds to this placeholder. For implementation details, see: K8S: https://kubernetes.io/docs/concepts/configuration/secret/ OpenShift: https://docs.openshift.com/container-platform/3.11/dev_guide/secrets.html

Sending HTTP POST Request In Java

Updated Answer:

Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.

By the way, you can access the full documentation for more examples here.

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

Original Answer:

I recommend to use Apache HttpClient. its faster and easier to implement.

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

for more information check this url: http://hc.apache.org/

Generate a random point within a circle (uniformly)

I am still not sure about the exact '(2/R2)×r' but what is apparent is the number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r.

check this way...number of points at some angle theta and between r (0.1r to 0.2r) i.e. fraction of the r and number of points between r (0.6r to 0.7r) would be equal if you use standard generation, since the difference is only 0.1r between two intervals. but since area covered between points (0.6r to 0.7r) will be much larger than area covered between 0.1r to 0.2r, the equal number of points will be sparsely spaced in larger area, this I assume you already know, So the function to generate the random points must not be linear but quadratic, (since number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r), so in this case it will be inverse of quadratic, since the delta we have (0.1r) in both intervals must be square of some function so it can act as seed value for linear generation of points (since afterwords, this seed is used linearly in sin and cos function), so we know, dr must be quadratic value and to make this seed quadratic, we need to originate this values from square root of r not r itself, I hope this makes it little more clear.

Exec : display stdout "live"

Don't use exec. Use spawn which is an EventEmmiter object. Then you can listen to stdout/stderr events (spawn.stdout.on('data',callback..)) as they happen.

From NodeJS documentation:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('child process exited with code ' + code.toString());
});

exec buffers the output and usually returns it when the command has finished executing.

Should I use <i> tag for icons instead of <span>?

I also found this to be useful when i wanted to place an icon with absolute positioning inside a link <a> tag.

I thought about the <img> tag first, but default styling of those tags inside links typically have border styling and/or shadow effects. Plus, it feels wrong to use an <img> tag without defining an "src" attribute whereas i'm using a background-image style sheet declaration so that the image doesn't ghost and drag.

At this point you're thinking of tags like <span> or <i> - in which case <i> makes so much sense as this type of icon.

All in all i think its benefit besides being intuitive is that it requires minimal style sheet adjustments to make this tag work as an icon.

How to set the value for Radio Buttons When edit?

<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

In my case I was trying ssh like this

ssh [email protected]:22 

when the correct format is:

ssh [email protected] -p 22 

Detecting iOS / Android Operating system

For this and other kind of client detections I suggest this js library: http://hictech.github.io/navJs/tester/index.html

For your specific answer use:

navJS.isIOS() || navJS.isAndroid()

Pandas: Subtracting two date columns and the result being an integer

Create a vectorized method

def calc_xb_minus_xa(df):
    time_dict = {
        '<Minute>': 'm',
        '<Hour>': 'h',
        '<Day>': 'D',
        '<Week>': 'W',
        '<Month>': 'M',
        '<Year>': 'Y'
    }

    time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
    offset_base_name = str(to_offset(time_delta).base)
    time_term = time_dict.get(offset_base_name)

    result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
    return result

Then in your df do:

df['x'] = calc_xb_minus_xa(df)

This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df

Get a list of resources from classpath directory

Custom Scanner

Implement your own scanner. For example:

(limitations of this solution are mentioned in the comments)

private List<String> getResourceFiles(String path) throws IOException {
    List<String> filenames = new ArrayList<>();

    try (
            InputStream in = getResourceAsStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
        String resource;

        while ((resource = br.readLine()) != null) {
            filenames.add(resource);
        }
    }

    return filenames;
}

private InputStream getResourceAsStream(String resource) {
    final InputStream in
            = getContextClassLoader().getResourceAsStream(resource);

    return in == null ? getClass().getResourceAsStream(resource) : in;
}

private ClassLoader getContextClassLoader() {
    return Thread.currentThread().getContextClassLoader();
}

Spring Framework

Use PathMatchingResourcePatternResolver from Spring Framework.

Ronmamo Reflections

The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

How do I programmatically "restart" an Android app?

I have slightly modified Ilya_Gazman answer to use new APIs (IntentCompat is deprecated starting API 26). Runtime.getRuntime().exit(0) seems to be better than System.exit(0).

 public static void triggerRebirth(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
    ComponentName componentName = intent.getComponent();
    Intent mainIntent = Intent.makeRestartActivityTask(componentName);
    context.startActivity(mainIntent);
    Runtime.getRuntime().exit(0);
}

Android Studio: Unable to start the daemon process

You need to install all necessary packages with Android SDK Manager:

  • Android SDK Tools

  • Android SDK Platform-tools

  • Android SDK Build-tools

  • SDK Platform

  • ARM\Intel System Image

  • Android Support Repository

  • Android Support Library

How can I expose more than 1 port with Docker?

Step1

In your Dockerfile, you can use the verb EXPOSE to expose multiple ports.
e.g.

EXPOSE 3000 80 443 22

Step2

You then would like to build an new image based on above Dockerfile.
e.g.

docker build -t foo:tag .

Step3

Then you can use the -p to map host port with the container port, as defined in above EXPOSE of Dockerfile.
e.g.

docker run -p 3001:3000 -p 23:22

In case you would like to expose a range of continuous ports, you can run docker like this:

docker run -it -p 7100-7120:7100-7120/tcp 

Jquery Change Height based on Browser Size/Resize

If you are using jQuery 1.2 or newer, you can simply use these:

$(window).width();
$(document).width();
$(window).height();
$(document).height();

From there it is a simple matter to decide the height of your element.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

SSL InsecurePlatform error when using Requests package

This came up for me on Ubuntu 14.04 (with Python 2.7.6) last week after i did a apt-get dist-upgrade that included libssl1.1:amd64 from deb.sury.org.

Since I run certbot-auto renew from a cron job, I also use the --no-self-upgrade to cut down on unscheduled maintenance. This seems to have been the source of the trouble.

To fix the error, all I needed to do was become root (with su's --login switch) and let certbot-auto upgrade itself. I.e:

sudo su --login
/usr/local/bin/certbot-auto renew 
# ... Upgrading certbot-auto 0.8.1 to 0.18.2... blah blah blah ...

instead of what normally runs from root's crontab:

5 7 * * * /usr/local/bin/certbot-auto renew --quiet --no-self-upgrade

After that, letsencrypt renwals ran normally once again.

Get real path from URI, Android KitKat new storage access framework

We need to do the following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Android 4.4 (KitKat) and on all other earlier versions as well.

Uri selectedImgFileUri = data.getData();

if (selectedImgFileUri == null ) {

    // The user has not selected any photo
}

try {

   InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
   mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
}
catch (Throwable tr) {

    // Show message to try again
}

Sorted collection in Java

Use sort() method to sort the list as below:

List list = new ArrayList();

//add elements to the list

Comparator comparator = new SomeComparator();

Collections.sort(list, comparator);

For reference see the link: http://tutorials.jenkov.com/java-collections/sorting.html

"could not find stored procedure"

Sometimes this can also happen when you have a stored procedure being called with parameters. For example, if you type something like:

set @runProc = 'dbo.StoredProcedure'
 exec @runProc

This will work, However:

set @runProc = 'dbo.StoredProcedure ''foods'''
exec @runProc

This will throw the error "could not find stored procedure dbo.StoredProcedure 'foods'", however this can easily be overcome with parantheses like so:

set @runProc = 'exec dbo.StoredProcedure ''foods'''
exec (@runProc)

Can't create handler inside thread that has not called Looper.prepare()

UPDATE - 2016

The best alternative is to use RxAndroid (specific bindings for RxJava) for the P in MVP to take charge fo data.

Start by returning Observable from your existing method.

private Observable<PojoObject> getObservableItems() {
    return Observable.create(subscriber -> {

        for (PojoObject pojoObject: pojoObjects) {
            subscriber.onNext(pojoObject);
        }
        subscriber.onCompleted();
    });
}

Use this Observable like this -

getObservableItems().
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Observer<PojoObject> () {
    @Override
    public void onCompleted() {
        // Print Toast on completion
    }

    @Override
    public void onError(Throwable e) {}

    @Override
    public void onNext(PojoObject pojoObject) {
        // Show Progress
    }
});
}

----------------------------------------------------------------------------------------------------------------------------------

I know I am a little late but here goes. Android basically works on two thread types namely UI thread and background thread. According to android documentation -

Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)  
View.post(Runnable)  
View.postDelayed(Runnable, long)

Now there are various methods to solve this problem.

I will explain it by code sample:

runOnUiThread

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                //Do your UI operations like dialog opening or Toast here
            }
        });
    }
}.start();

LOOPER

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}

AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

public void onClick(View v) {
    new CustomTask().execute((Void[])null);
}


private class CustomTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... param) {
        //Do some work
        return null;
    }

    protected void onPostExecute(Void param) {
        //Print Toast or open dialog
    }
}

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Message msg = new Message();


new Thread()
{
    public void run()
    {
        msg.arg1=1;
        handler.sendMessage(msg);
    }
}.start();



Handler handler = new Handler(new Handler.Callback() {

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.arg1==1)
        {
            //Print Toast or open dialog        
        }
        return false;
    }
});

trigger body click with jQuery

I've used the following code a few times and it works sweet:

$("body").click(function(e){ 
    // Check what has been clicked:
    var target = $(e.target); 
    if(target.is("#target")){
    // The target was clicked
    // Do something...
  }
});

How do I start PowerShell from Windows Explorer?

It's even easier in Windows 8.1 and Server 2012 R2.

Do this once: Right-click on the task bar, choose Properties. In the Navigation tab, turn on [✓] Replace Command Prompt with Windows PowerShell in the menu when I right-click the lower-left corner or press Windows key+X.

Then whenever you want a PowerShell prompt, hit Win+X, I. (Or Win+X, A for an Admin PowerShell prompt)

What is the difference between "INNER JOIN" and "OUTER JOIN"?

The General Idea

Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN, RIGHT OUTER JOIN and LEFT OUTER JOIN.

These two table form a basis for the representation of the JOINs below:

Basis

CROSS JOIN

CrossJoin

SELECT *
  FROM citizen
 CROSS JOIN postalcode

The result will be the Cartesian products of all combinations. No JOIN condition required:

CrossJoinResult

INNER JOIN

INNER JOIN is the same as simply: JOIN

InnerJoin

SELECT *
  FROM citizen    c
  JOIN postalcode p ON c.postal = p.postal

The result will be combinations that satisfies the required JOIN condition:

InnerJoinResult

LEFT OUTER JOIN

LEFT OUTER JOIN is the same as LEFT JOIN

LeftJoin

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal

The result will be everything from citizen even if there are no matches in postalcode. Again a JOIN condition is required:

LeftJoinResult

Data for playing

All examples have been run on an Oracle 18c. They're available at dbfiddle.uk which is also where screenshots of tables came from.

CREATE TABLE citizen (id      NUMBER,
                      name    VARCHAR2(20),
                      postal  NUMBER,  -- <-- could do with a redesign to postalcode.id instead.
                      leader  NUMBER);

CREATE TABLE postalcode (id      NUMBER,
                         postal  NUMBER,
                         city    VARCHAR2(20),
                         area    VARCHAR2(20));

INSERT INTO citizen (id, name, postal, leader)
              SELECT 1, 'Smith', 2200,  null FROM DUAL
        UNION SELECT 2, 'Green', 31006, 1    FROM DUAL
        UNION SELECT 3, 'Jensen', 623,  1    FROM DUAL;

INSERT INTO postalcode (id, postal, city, area)
                 SELECT 1, 2200,     'BigCity',         'Geancy'  FROM DUAL
           UNION SELECT 2, 31006,    'SmallTown',       'Snizkim' FROM DUAL
           UNION SELECT 3, 31006,    'Settlement',      'Moon'    FROM DUAL  -- <-- Uuh-uhh.
           UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space'   FROM DUAL;

Blurry boundaries when playing with JOIN and WHERE

CROSS JOIN

CROSS JOIN resulting in rows as The General Idea/INNER JOIN:

SELECT *
  FROM citizen          c
  CROSS JOIN postalcode p
 WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows

Using CROSS JOIN to get the result of a LEFT OUTER JOIN requires tricks like adding in a NULL row. It's omitted.

INNER JOIN

INNER JOIN becomes a cartesian products. It's the same as The General Idea/CROSS JOIN:

SELECT *
  FROM citizen    c
  JOIN postalcode p ON 1 = 1  -- < -- The ON condition makes it a CROSS JOIN

This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.

Using INNER JOIN to get the result of a LEFT OUTER JOIN also requires tricks. It's omitted.

LEFT OUTER JOIN

LEFT JOIN results in rows as The General Idea/CROSS JOIN:

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN

LEFT JOIN results in rows as The General Idea/INNER JOIN:

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal
 WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode

The troubles with the Venn diagram

An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.

Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.

Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.

The set A represents the set on the left (the citizen table) and the set B is the set on the right (the postalcode table) in below discussion.

CROSS JOIN

Every element in both sets are matched with every element in the other set, meaning we need A amount of every B elements and B amount of every A elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION fits at all.

The rows are distinct. The UNION is 7 rows in total. But they're incompatible for a common SQL results set. And this is not how a CROSS JOIN works at all:

CrossJoinUnion1

Trying to represent it like this:

CrossJoinUnion2Crossing

..but now it just looks like an INTERSECTION, which it's certainly not. Furthermore there's no element in the INTERSECTION that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:

CrossJoinUnionUnion3

For reference one searchable result for CROSS JOINs can be seen at Tutorialgateway. The INTERSECTION, just like this one, is empty.

INNER JOIN

The value of an element depends on the JOIN condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x is only true for one row. Once a row in table A (citizen) matches multiple rows in table B (postalcode) under the JOIN condition, the result has the same problems as the CROSS JOIN: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN condition determines the placement of an element in the diagram. Looking only at the values of the JOIN condition with the rest of the row just along for the ride:

InnerJoinIntersection - Filled

This representation falls completely apart when using an INNER JOIN with a ON 1 = 1 condition making it into a CROSS JOIN.

With a self-JOIN, the rows are in fact idential elements in both tables, but representing the tables as both A and B isn't very suitable. For example a common self-JOIN condition that makes an element in A to be matching a different element in B is ON A.parent = B.child, making the match from A to B on seperate elements. From the examples that would be a SQL like this:

SELECT *
  FROM citizen c1
  JOIN citizen c2 ON c1.id = c2.leader

SelfJoinResult

Meaning Smith is the leader of both Green and Jensen.

OUTER JOIN

Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN can be though of as to match the empty set. But in set theory the union of any set C and an empty set, is always just C. The empty set adds nothing. The representation of this LEFT OUTER JOIN is usually just showing all of A to illustrate that rows in A are selected regardless of whether there is a match or not from B. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A:

LeftJoinIntersection - Filled

WHERE clause - making sense

Finding all rows from a CROSS JOIN with Smith and postalcode on the Moon:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
   AND p.area = 'Moon';

Where - result

Now the Venn diagram isn't used to reflect the JOIN. It's used only for the WHERE clause:

Where

..and that makes sense.

When INTERSECT and UNION makes sense

INTERSECT

As explained an INNER JOIN is not really an INTERSECT. However INTERSECTs can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL will result in the same row as the one above WHERE, and the Venn diagram will also be the same:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
INTERSECT
SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';

UNION

An OUTER JOIN is not a UNION. However UNION work under the same conditions as INTERSECT, resulting in a return of all results combining both SELECTs:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
UNION
SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';

which is equivalent to:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
   OR p.area = 'Moon';

..and gives the result:

Union - Result

Also here a Venn diagram makes sense:

UNION

When it doesn't apply

An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:

SELECT *
  FROM citizen
 WHERE name = 'Smith'
SELECT *
  FROM postalcode
 WHERE area = 'Moon';

..trying to combine the results with UNION gives a

ORA-01790: expression must have same datatype as corresponding expression

For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT.

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Refused to execute script, strict MIME type checking is enabled?

Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs

_x000D_
_x000D_
<div id="wrapper"></div>_x000D_
<base href="/" />
_x000D_
_x000D_
_x000D_

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

Redirecting to a new page after successful login

You need to set the location header as follows:

header('Location: http://www.example.com/');

Replacing http://www.example.com of course with the url of your landing page.

Add this where you have finished logging the user in.

Note: When redirecting the user will be immediately redirected so you're message probably won't display.

Additionally, you need to move your PHP code to the top of the file for this solution to work.

On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.

Python Pandas Counting the Occurrences of a Specific value

You can create subset of data with your condition and then use shape or len:

print df
  col1 education
0    a       9th
1    b       9th
2    c       8th

print df.education == '9th'
0     True
1     True
2    False
Name: education, dtype: bool

print df[df.education == '9th']
  col1 education
0    a       9th
1    b       9th

print df[df.education == '9th'].shape[0]
2
print len(df[df['education'] == '9th'])
2

Performance is interesting, the fastest solution is compare numpy array and sum:

graph

Code:

import perfplot, string
np.random.seed(123)


def shape(df):
    return df[df.education == 'a'].shape[0]

def len_df(df):
    return len(df[df['education'] == 'a'])

def query_count(df):
    return df.query('education == "a"').education.count()

def sum_mask(df):
    return (df.education == 'a').sum()

def sum_mask_numpy(df):
    return (df.education.values == 'a').sum()

def make_df(n):
    L = list(string.ascii_letters)
    df = pd.DataFrame(np.random.choice(L, size=n), columns=['education'])
    return df

perfplot.show(
    setup=make_df,
    kernels=[shape, len_df, query_count, sum_mask, sum_mask_numpy],
    n_range=[2**k for k in range(2, 25)],
    logx=True,
    logy=True,
    equality_check=False, 
    xlabel='len(df)')

Storing Form Data as a Session Variable

That's perfectly fine and will work. But to use sessions you have to put session_start(); on the first line of the php code. So basically

<?php
session_start();

//rest of stuff

?>

Android 8: Cleartext HTTP traffic not permitted

According to Network security configuration -

Starting with Android 9 (API level 28), cleartext support is disabled by default.

Also have a look at - https://koz.io/android-m-and-the-war-on-cleartext-traffic/

Codelabs explanation - https://codelabs.developers.google.com/codelabs/android-network-security-config/index.html

Option 1 -

First try hitting the URL with "https://" instead of "http://"

Option 2 -

Create file res/xml/network_security_config.xml -

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
    </domain-config>
</network-security-config>

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>

Option 3 -

android:usesCleartextTraffic Doc

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

Also as @david.s' answer pointed out android:targetSandboxVersion can be a problem too -

According to Manifest Docs -

android:targetSandboxVersion

The target sandbox for this app to use. The higher the sandbox version number, the higher the level of security. Its default value is 1; you can also set it to 2. Setting this attribute to 2 switches the app to a different SELinux sandbox. The following restrictions apply to a level 2 sandbox:

  • The default value of usesCleartextTraffic in the Network Security Config is false.
  • Uid sharing is not permitted.

So Option 4 -

If you have android:targetSandboxVersion in <manifest> then reduce it to 1

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

How can I delete an item from an array in VB.NET?

As Heinzi said, an array has a fixed size. In order to 'remove an item' or 'resize' it, you'll have to create a new array with the desired size and copy the items you need as appropriate.

Here's code to remove an item from an array:

<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        Return outArr
    End If
End Function

You can use it as such:

Module Module1

    Sub Main()
        Dim arr = New String() {"abc", "mno", "xyz"}
        arr.RemoveAt(1)
    End Sub
End Module

The code above removes the second element ("mno") [which has an index of 1] from the array.

You need to be developing in .NET 3.5 or higher in order to use the extension method. If you're using .NET 2.0 or 3.0, you can call the method as such

arr = RemoveAt(arr, 1)

I hope this is what you need.

Update

After running tests based on ToolMakerSteve's comment it appears the initial code does not modify the array you want to update because of the ByVal used in the function's declaration. However, writing code like arr = arr.RemoveAt(1) or arr = RemoveAt(arr, 1) does modify the array because it reassigns the modified array to the original.

Find below the updated method (subroutine) for removing an element from an array.

<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef arr As T(), ByVal index As Integer)
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        arr = outArr
    End If
End Sub

Usage of the method is similar to the original, except there is no return value this time so trying to assign an array from the return value will not work because nothing is returned.

Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)  ' Output: {"abc", "mno"} (works on .NET 3.5 and higher)
RemoveAt(arr, 1) ' Output: {"abc", "mno"} (works on all versions of .NET fx)
arr = arr.RemoveAt(1)  'will not work; no return value
arr = RemoveAt(arr, 1) 'will not work; no return value

Note:

  1. I use a temporary array for the process because it makes my intentions clear and that is exactly what VB.NET does behind the scenes when you do Redim Preserve. If you would like to modify the array in-place using Redim Preserve, see ToolmakerSteve's answer.

  2. The RemoveAt methods written here are extension methods. In order for them to work, you will have to paste them in a Module. Extension methods will not work in VB.NET if they are placed in a Class.

  3. Important If you will be modifying your array with lots of 'removes', it is highly recommended to use a different data structure such as List(Of T) as suggested by other answerers to this question.

Neither BindingResult nor plain target object for bean name available as request attribute

In the controller, you need to add the login object as an attribute of the model:

model.addAttribute("login", new Login());

Like this:

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String displayLogin(Model model) { 
    model.addAttribute("login", new Login()); 
    return "login"; 
}

How to insert a data table into SQL Server database table?

I am giving a very simple code, which i used in my solution (I have the same problem statement as yours)

    SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
    sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) 
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();

I have given a predefined table-name as "abcd" (you must take care that a table by this name doesn't exist in your database). Please vote my answer if it works for you!!!! :)

How do you set a default value for a MySQL Datetime column?

Use the following code

DELIMITER $$

    CREATE TRIGGER bu_table1_each BEFORE UPDATE ON table1 FOR EACH ROW
    BEGIN
      SET new.datefield = NOW();
    END $$

    DELIMITER ;

python: SyntaxError: EOL while scanning string literal

All code below was tested with Python 3.8.3


Simplest -- just use triple quotes.
Either single:

long_string = '''some
very 
long
string
............'''

or double:

long_string = """some
very 
long
string
............"""

Note: triple quoted strings retain indentation, it means that

long_string = """some
    very 
    long
string
............"""

and

long_string = """some
    very 
long
string
............"""

or even just

long_string = """
some
very 
long
string
............"""

are not the same.
There is a textwrap.dedent function in standard library to deal with this, though working with it is out of question's scope.


You can, as well, use \n inside a string, residing on single line:

long_string = "some \nvery \nlong \nstring \n............"

Also, if you don't need any linefeeds (i.e. newlines) in your string, you can use \ inside regular string:

long_string = "some \
very \
long \
string \
............"

Check if xdebug is working

Just to extend KsaRs answer and provide a possibility to check xdebug from command line:

php -r "echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';"

The default XML namespace of the project must be the MSBuild XML namespace

I was getting the same messages while I was running just msbuild from powershell.

dotnet msbuild "./project.csproj" worked for me.

bootstrap 3 tabs not working properly

My problem was with extra </div> tag inside the first tab.

Setting up Vim for Python

Put the following in your .vimrc

autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
autocmd BufRead *.py set nocindent
autocmd BufWritePre *.py normal m`:%s/\s\+$//e ``
filetype plugin indent on

See also the detailed instructions

I personally use JetBrain's PyCharm with the IdeaVIM plugin when doing anything complex, for simple editing the additions to .vimrc seem sufficient.

Hive: Filtering Data between Specified Dates when Date is a String

No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.

For Example:

select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10; 

Simple linked list in C++

head is defined inside the main as follows.

struct Node *head = new Node;

But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.

Make the declaration of the head as global and do not pass it to functions.

The functions should be as follows.

void initNode(int n){
    head->x = n;
    head->next = NULL;
}

void addNode(int n){
    struct Node *NewNode = new Node;
    NewNode-> x = n;
    NewNode->next = head;
    head = NewNode;
}

"Least Astonishment" and the Mutable Default Argument

Every other answer explains why this is actually a nice and desired behavior, or why you shouldn't be needing this anyway. Mine is for those stubborn ones who want to exercise their right to bend the language to their will, not the other way around.

We will "fix" this behavior with a decorator that will copy the default value instead of reusing the same instance for each positional argument left at its default value.

import inspect
from copy import copy

def sanify(function):
    def wrapper(*a, **kw):
        # store the default values
        defaults = inspect.getargspec(function).defaults # for python2
        # construct a new argument list
        new_args = []
        for i, arg in enumerate(defaults):
            # allow passing positional arguments
            if i in range(len(a)):
                new_args.append(a[i])
            else:
                # copy the value
                new_args.append(copy(arg))
        return function(*new_args, **kw)
    return wrapper

Now let's redefine our function using this decorator:

@sanify
def foo(a=[]):
    a.append(5)
    return a

foo() # '[5]'
foo() # '[5]' -- as desired

This is particularly neat for functions that take multiple arguments. Compare:

# the 'correct' approach
def bar(a=None, b=None, c=None):
    if a is None:
        a = []
    if b is None:
        b = []
    if c is None:
        c = []
    # finally do the actual work

with

# the nasty decorator hack
@sanify
def bar(a=[], b=[], c=[]):
    # wow, works right out of the box!

It's important to note that the above solution breaks if you try to use keyword args, like so:

foo(a=[4])

The decorator could be adjusted to allow for that, but we leave this as an exercise for the reader ;)

Command not found after npm install in zsh

For Mac users:

Alongside the following: nvm, iterm2, zsh

I found using the .bashrc rather than .profile or .bash_profile caused far less issues.

Simply by adding the latter to my .zshrc file:

source $HOME/.bashrc

How to check not in array element

I prefer this

if(in_array($id,$user_access_arr) == false)

respective

if (in_array(search_value, array) == false) 
// value is not in array 

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.

g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

Why is the gets function so dangerous that it should not be used?

I read recently, in a USENET post to comp.lang.c, that gets() is getting removed from the Standard. WOOHOO

You'll be happy to know that the committee just voted (unanimously, as it turns out) to remove gets() from the draft as well.

How to read a PEM RSA private key from .NET

Check http://msdn.microsoft.com/en-us/library/dd203099.aspx

under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;


public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
    try{ 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 
    } 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
    try{ 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 
    } 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
    else 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 
} 

How to fix 'Notice: Undefined index:' in PHP form action

Please try this

error_reporting = E_ALL & ~E_NOTICE

in php.ini

Is there a way to link someone to a YouTube Video in HD 1080p quality?

No, this is not working. And it's not just for you, in case you spent the last hour trying to find an answer for having your embeded videos open in HD.

Question: Oh, but how do you know this is not working anymore and there is no other alternative to make embeded videos open in a different quality?

Answer: Just went to Google's official documentation regarding Youtube's player parameters and there is not a single parameter that allows you to change its quality.

Also, hd=1 doesn't work either. More info here.

Apparently Youtube analyses the width and height of the user's window (or iframe) and automatically sets the quality based on this.

UPDATE:

As of 10 of April of 2018 it still doesn't work (see my comment on the accepted answer for more details).

What I can see from comments is that it MAY work sometimes, but some others it doesn't. The accepted answer states that "it measures the network speed and the screen and player sizes". So, by that, we can understand that I CANNOT force HD as YouTube will still do whatever it wants in case of low network speed/screen resolution. From my perspective everyone saying it works just have false positives on their hands and on the occasion they tested it worked for some random reason not related to the vq parameter. If it was a valid parameter, Google would document it somewhere, and vq isn't documented anywhere.

What is the use of a private static variable in Java?

Is declaring a variable as private static varName; any different from declaring a variable private varName;?

Yes, both are different. And the first one is called class variable because it holds single value for that class whereas the other one is called instance variable because it can hold different value for different instances(Objects). The first one is created only once in jvm and other one is created once per instance i.e if you have 10 instances then you will have 10 different private varName; in jvm.

Does declaring the variable as static give it other special properties?

Yes, static variables gets some different properties than normal instance variables. I've mentioned few already and let's see some here: class variables (instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName. And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects. Class variables can be used in static methods.

What is the use of a private static variable in Java?

Logically, private static variable is no different from public static variable rather the first one gives you more control. IMO, you can literally replace public static variable by private static variable with help of public static getter and setter methods.

One widely used area of private static variable is in implementation of simple Singleton pattern where you will have only single instance of that class in whole world. Here static identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).

public class Singleton {
    private static Singleton singletonInstance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return Singleton.singletonInstance;
    }
}

Listen to changes within a DIV and act accordingly

You can opt to create your own custom events so you'll still have a clear separation of logic.

Bind to a custom event:

$('#laneconfigdisplay').bind('contentchanged', function() {
  // do something after the div content has changed
  alert('woo');
});

In your function that updates the div:

// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

How to change port for jenkins window service when 8080 is being used

1 ) Open the jenkins.xml file
2 ) Search for the "--httpPort=8080" Text and replace the port number 8080 with your custom port number (like 7070 , 9090 )
3 ) Go to your services running your machine & find out the Jenkins service and click on restart.

enter image description here

How get permission for camera in android.(Specifically Marshmallow)

I try to add following code:

private static final int MY_CAMERA_REQUEST_CODE = 100;

@RequiresApi(api = Build.VERSION_CODES.M)

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
    }

On onCreate Function and this following code:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_CAMERA_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

And this worked for me :)

C# Iterate through Class properties

I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

    Type type = typeof(Record);
    FieldInfo[] properties = type.GetFields();
    foreach (FieldInfo property in properties) {
       Debug.LogError(property.Name);
    }

Can I install/update WordPress plugins without providing FTP access?

The best way to install plugin using SSH is WPCLI.

Note that, SSH access is mandatory to use WP CLI commands. Before using it check whether the WP CLI is installed at your hosting server or machine.

How to check : wp --version [ It will show the wp cli version installed ]

If not installed, how to install it : Before installing WP-CLI, please make sure the environment meets the minimum requirements:

UNIX-like environment (OS X, Linux, FreeBSD, Cygwin); limited support in Windows environment. PHP 5.4 or later WordPress 3.7 or later. Versions older than the latest WordPress release may have degraded functionality

If above points satisfied, please follow the steps : Reference URL : WPCLI

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
[ download the wpcli phar ]

php wp-cli.phar --info [ check whether the phar file is working ]

chmod +x wp-cli.phar [ change permission ]
sudo mv wp-cli.phar /usr/local/bin/wp [ move to global folder ]
wp --info [ to check the installation ]

Now WP CLI is ready to install.

Now you can install any plugin that is available in WordPress.org by using the following commands :

wp install plugin plugin-slug
wp delete plugin plugin-slug
wp deactivate plugin plugin-slug

NOTE : wp cli can install only those plugin which is available in wordpress.org

How do format a phone number as a String in Java?

U can format any string containing non numeric characters also to your desired format use my util class to format

usage is very simple

public static void main(String[] args){
    String num = "ab12345*&67890";

    System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}

output: (123)-456-7890

u can specify any foramt such as XXX-XXX-XXXX and length of the phone number , if input length is greater than specified length then string will be trimmed.

Get my class from here: https://github.com/gajeralalji/PhoneNumberUtil/blob/master/PhoneNumberUtil.java

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.