Programs & Examples On #Url

A URL (Uniform Resource Locator), is a universal identifier on the web. A URL is a reference to a web resource at a specific location, and provides a means for retrieving that resource.

Manipulate a url string by adding GET parameters

Here's a shorter version of the accepted answer:

$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . 'category=action';

Edit: as discussed in the accepted answer, this is flawed in that it doesn't check to see if category already exists. A better solution would be to treat the $_GET for what it is - an array - and use functions like in_array().

Curl Command to Repeat URL Request

You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):

curl http://www.myurl.com/?[1-20]

If you have other query strings in your URL, assign the sequence to a throwaway variable:

curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]

Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html

How to get domain root url in Laravel 4?

use directly where you want controller or web.php

Request::getHost();

Convert blob URL to normal URL

A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.

A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.

Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.

It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).

Here's an example:

_x000D_
_x000D_
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var xhr = new XMLHttpRequest;_x000D_
xhr.responseType = 'blob';_x000D_
_x000D_
xhr.onload = function() {_x000D_
   var recoveredBlob = xhr.response;_x000D_
_x000D_
   var reader = new FileReader;_x000D_
_x000D_
   reader.onload = function() {_x000D_
     var blobAsDataUrl = reader.result;_x000D_
     window.location = blobAsDataUrl;_x000D_
   };_x000D_
_x000D_
   reader.readAsDataURL(recoveredBlob);_x000D_
};_x000D_
_x000D_
xhr.open('GET', blobUrl);_x000D_
xhr.send();
_x000D_
_x000D_
_x000D_

data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.

Redirect to specified URL on PHP script completion?

<?php

// do something here

header("Location: http://example.com/thankyou.php");
?>

React-router urls don't work when refreshing or writing manually

I'm not using server side rendering yet but I hit the same problem as the OP where Link seemed to work fine most of the time but failed when I had a parameter. I'll document my solution here to see if it helps anyone.

My main jsx contains this:

<Route onEnter={requireLogin} path="detail/:id" component={ModelDetail} />

This works fine for the first matching link but when the :id changes in <Link> expressions nested on that model's detail page, the url changes in the browser bar but the content of the page did not initially change to reflect the linked model.

The trouble was that I had used the props.params.id to set the model in componentDidMount. The component is just mounted once so this means that the first model is the one that sticks on the page and the subsequent Links change the props but leave the page looking unchanged.

Setting the model in the component state in both componentDidMount and in componentWillReceiveProps (where it is based on the next props) solves the problem and the page content changes to reflect the desired model.

How can I check if a URL exists via PHP?

to check if url is online or offline ---

function get_http_response_code($theURL) {
    $headers = @get_headers($theURL);
    return substr($headers[0], 9, 3);
}

What is the difference between URI, URL and URN?

Below I sum up Prateek Joshi's awesome explanation.

The theory:

  • URI (uniform resource identifier) identifies a resource (text document, image file, etc)
  • URL (uniform resource locator) is a subset of the URIs that include a network location
  • URN (uniform resource name) is a subset of URIs that include a name within a given space, but no location

That is:

enter image description here

And for an example:

enter image description here

Also, if you haven't already, I suggest reading Roger Pate's answer.

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

How to construct a relative path in Java from two absolute paths (or URLs)?

When using java.net.URI.relativize you should be aware of Java bug: JDK-6226081 (URI should be able to relativize paths with partial roots)

At the moment, the relativize() method of URI will only relativize URIs when one is a prefix of the other.

Which essentially means java.net.URI.relativize will not create ".."'s for you.

Change URL parameters

I just wrote a simple module to deal with reading and updating the current url query params.

Example usage:

import UrlParams from './UrlParams'

UrlParams.remove('foo') //removes all occurences of foo=?
UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
UrlParams.get('foo') //returns bar
UrlParams.get('foo', true) //returns [bar, bar2]

Here is my code named UrlParams.(js/ts):

class UrlParams {

    /**
     * Get params from current url
     * 
     * @returns URLSearchParams
     */
    static getParams(){
        let url = new URL(window.location.href)
        return new URLSearchParams(url.search.slice(1))
    }

    /**
     * Update current url with params
     * 
     * @param params URLSearchParams
     */
    static update(params){
        if(`${params}`){
            window.history.replaceState({}, '', `${location.pathname}?${params}`)
        } else {
            window.history.replaceState({}, '', `${location.pathname}`)
        }
    }

    /**
     * Remove key from url query
     * 
     * @param param string
     */
    static remove(param){
        let params = this.getParams()
        if(params.has(param)){
            params.delete(param)
            this.update(params)
        }
    }

    /**
     * Add key value pair to current url
     * 
     * @param key string
     * @param value string
     */
    static add(key, value){
        let params = this.getParams()
        params.append(key, value)
        this.update(params)
    }

    /**
     * Get value or values of key
     * 
     * @param param string
     * @param all string | string[]
     */
    static get(param, all=false){
        let params = this.getParams()
        if(all){
            return params.getAll(param)
        }
        return params.get(param)
    }

    /**
     * Set value of query param
     * 
     * @param key string
     * @param value string
     */
    static set(key, value){
        let params = this.getParams()
        params.set(key, value)
        this.update(params)
    }

}
export default UrlParams
export { UrlParams }

How do I make an http request using cookies on Android?

I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.

So if there is no default (have you checked if CookieHandler.getDefault() really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.

edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault() to receive the callbacks. Forgot to mention that.

Simplest way to read json from a URL in java

The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

Using PHP Replace SPACES in URLS with %20

$result = preg_replace('/ /', '%20', 'your string here');

you may also consider using

$result = urlencode($yourstring)

to escape other special characters as well

How do I decode a URL parameter using C#?

Try:

var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);

Get file name from URL

Instead of reinventing the wheel, how about using Apache commons-io:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");

        System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
        System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
        System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
    }

}

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

How to obtain the last path segment of a URI

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

Get query string parameters url values with jQuery / Javascript (querystring)

JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use

$.url().param('search');

This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.

Or you can use js-url instead. Its quite similar to the one below.

So you can access the query param like $.url('?search')

Ways to insert javascript into URL?

If the link has javascript:, then it will run javascript, otherwise, I agree with everyone else here, there's no way to do it.

SO is smart enough to filter this out!

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

Submit HTML form on self page

If you are submitting a form using php be sure to use:

action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

for security.

Characters allowed in a URL

I tested it by requesting my website (apache) with all available chars on my german keyboard as URL parameter:

http://example.com/?^1234567890ß´qwertzuiopü+asdfghjklöä#<yxcvbnm,.-°!"§$%&/()=? `QWERTZUIOPÜ*ASDFGHJKLÖÄ\'>YXCVBNM;:_²³{[]}\|µ@€~

These were not encoded:

^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-!/()=?`*;:_{}[]\|~

Not encoded after urlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_

Not encoded after rawurlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~

Note: Before PHP 5.3.0 rawurlencode() encoded ~ because of RFC 1738. But this was replaced by RFC 3986 so its safe to use, now. But I do not understand why for example {} are encoded through rawurlencode() because they are not mentioned in RFC 3986.

An additional test I made was regarding auto-linking in mail texts. I tested Mozilla Thunderbird, aol.com, outlook.com, gmail.com, gmx.de and yahoo.de and they fully linked URLs containing these chars:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~+#,%&=*;:@

Of course the ? was linked, too, but only if it was used once.

Some people would now suggest to use only the rawurlencode() chars, but did you ever hear that someone had problems to open these websites?

Asterisk
http://wayback.archive.org/web/*/http://google.com

Colon
https://en.wikipedia.org/wiki/Wikipedia:About

Plus
https://plus.google.com/+google

At sign, Colon, Comma and Exclamation mark
https://www.google.com/maps/place/USA/@36.2218457,...

Because of that these chars should be usable unencoded without problems. Of course you should not use &; because of encoding sequences like &amp;. The same reason is valid for % as it used to encode chars in general. And = as it assigns a value to a parameter name.

Finally I would say its ok to use these unencoded:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~!+,*:@

But if you expect randomly generated URLs you should not use .!, because those mark the end of a sentence and some mail apps will not auto-link the last char of the url. Example:

Visit http://example.com/foo=bar! !

Get domain name from given url

I made a small treatment after the URI object creation

 if (url.startsWith("http:/")) {
        if (!url.contains("http://")) {
            url = url.replaceAll("http:/", "http://");
        }
    } else {
        url = "http://" + url;
    }
    URI uri = new URI(url);
    String domain = uri.getHost();
    return domain.startsWith("www.") ? domain.substring(4) : domain;

Java - How to find the redirected url of a url?

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

How to read GET data from a URL using JavaScript?

Here's one solution. Of course, this function doesn't need to load into a "window.params" option -- that can be customized.

window.params = function(){
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&');
    for(var i in param_array){
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }
    return params;
}();

Example API call on http://www.mints.com/myurl.html?name=something&goal=true:

if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();

How can I get a specific parameter from location.search?

The following uses regular expressions and searches only on the query string portion of the URL.

Most importantly, this method supports normal and array parameters as in http://localhost/?fiz=zip&foo[]=!!=&bar=7890#hashhashhash

function getQueryParam(param) {
    var result =  window.location.search.match(
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")
    );

    return result ? result[3] : false;
}

console.log(getQueryParam("fiz"));
console.log(getQueryParam("foo"));
console.log(getQueryParam("bar"));
console.log(getQueryParam("zxcv"));

Output:

zip
!!=
7890
false

Javascript isnull

I'm using this function

function isNull() {
    for (var i = 0; i < arguments.length; i++) {
        if (
            typeof arguments[i] !== 'undefined'
            && arguments[i] !== undefined
            && arguments[i] != null
            && arguments[i] != NaN
            && arguments[i] 
        ) return arguments[i];
      }
}

test

console.log(isNull(null, null, undefined, 'Target'));

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

What is the meaning of # in URL and how can I use that?

It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.

Please see this page for more details.

RegEx to match stuff between parentheses

You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'

By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

\(([^\)]+)\)

which will match any grouping of parens that do not, themselves, contain parens.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Compiling answers given by @adurdin and @User

Add followings to your info.plist & change localhost.com with your corresponding domain name, you can add multiple domains as well:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <false/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>
</plist>

You info.plist must looks like this:

enter image description here

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Preferred Java way to ping an HTTP URL for availability

Instead of using URLConnection use HttpURLConnection by calling openConnection() on your URL object.

Then use getResponseCode() will give you the HTTP response once you've read from the connection.

here is code:

    HttpURLConnection connection = null;
    try {
        URL u = new URL("http://www.google.com/");
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();
        System.out.println("" + code);
        // You can determine on HTTP return code received. 200 is success.
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

Also check similar question How to check if a URL exists or returns 404 with Java?

Hope this helps.

How do I modify the URL without reloading the page?

You can use this beautiful and simple function to so so anywhere on your application.

function changeurl(url, title) {
    var new_url = '/' + url;
    window.history.pushState('data', title, new_url);
    
}

You can not only edit URL but you can update title along with it.

Quite helpful everyone.

Facebook login "given URL not allowed by application configuration"

You can set up a developer application and set the url to localhost.com:port Make sure to map localhost.com to localhost on your hosts file

Works for me

Passing arrays as url parameter

Easiest way would be to use the serialize function.

It serializes any variable for storage or transfer. You can read about it in the php manual - serialize

The variable can be restored by using unserialize

So in the passing to the URL you use:

$url = urlencode(serialize($array))

and to restore the variable you use

$var = unserialize(urldecode($_GET['array']))

Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.

Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.

Extract parameter value from url using regular expressions

I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b

    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    }

The above function will return an array consisting of url variables.

For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,

function getUrlParams() { 
    var vars = {};
    var parts = window.location.href.split('/' );
    return parts;
}

You can even combine them both to be able to use with a single call in a page or in javascript.

slashes in url variables

You need to escape those but don't just replace it by %2F manually. You can use URLEncoder for this.

Eg URLEncoder.encode(url, "UTF-8")

Then you can say

yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")

Escaping ampersand in URL

You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.

data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos&param2="+encodeURIComponent(someValue)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

java.net.URL read stream to byte[]

There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
  int n;

  while ( (n = is.read(byteChunk)) > 0 ) {
    baos.write(byteChunk, 0, n);
  }
}
catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
  e.printStackTrace ();
  // Perform any other exception handling that's appropriate.
}
finally {
  if (is != null) { is.close(); }
}

You'll then have the image data in baos, from which you can get a byte array by calling baos.toByteArray().

This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.

Beautiful way to remove GET-variables with PHP?

You can use the server variables for this, for example $_SERVER['REQUEST_URI'], or even better: $_SERVER['PHP_SELF'].

InputStream from a URL

Try:

final InputStream is = new URL("http://wwww.somewebsite.com/a.txt").openStream();

Spaces in URLs?

They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20).

In fact, the RFC even states that spaces are delimiters and should be ignored:

In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.

and

For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.

Curiously, the use of + as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

How to get base URL in Web API controller?

In the action method of the request to the url "http://localhost:85458/api/ctrl/"

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

this will get you http://localhost:85458

Getting URL parameter in java and extract a specific text from that URL

this will work for all sort of youtube url :
if url could be

youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that

Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any

if (m.matches()) {
    url = m.group(1);        
}
System.out.println(url);

this will extract video id from your url

further reference

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

REST API Best practices: Where to put parameters?

One "dimension" of this topic has been left out yet it's very important: there are times when the "best practices" have to come into terms with the plaform we are implementing or augmenting with REST capabilities.

Practical example:

Many web applications nowadays implement the MVC (Model, View, Controller) architecture. They assume a certain standard path is provided, even more so when those web applications come with an "Enable SEO URLs" option.

Just to mention a fairly famous web application: an OpenCart e-commerce shop. When the admin enables the "SEO URLs" it expects said URLs to come in a quite standard MVC format like:

http://www.domain.tld/special-offers/list-all?limit=25

Where

  • special-offers is the MVC controller that shall process the URL (showing the special-offers page)

  • list-all is the controller's action or function name to call. (*)

  • limit=25 is an option, stating that 25 items will be shown per page.

(*) list-all is a fictious function name I used for clarity. In reality, OpenCart and most MVC frameworks have a default, implied (and usually omitted in the URL) index function that gets called when the user wants a default action to be performed. So the real world URL would be:

http://www.domain.tld/special-offers?limit=25

With a now fairly standard application or frameworkd structure similar to the above, you'll often get a web server that is optimized for it, that rewrites URLs for it (the true "non SEOed URL" would be: http://www.domain.tld/index.php?route=special-offers/list-all&limit=25).

Therefore you, as developer, are faced into dealing with the existing infrastructure and adapt your "best practices", unless you are the system admin, know exactly how to tweak an Apache / NGinx rewrite configuration (the latter can be nasty!) and so on.

So, your REST API would often be much better following the referring web application's standards, both for consistency with it and ease / speed (and thus budget saving).

To get back to the practical example above, a consistent REST API would be something with URLs like:

http://www.domain.tld/api/special-offers-list?from=15&limit=25

or (non SEO URLs)

http://www.domain.tld/index.php?route=api/special-offers-list?from=15&limit=25

with a mix of "paths formed" arguments and "query formed" arguments.

What is apache's maximum url length?

  • Internet Explorer: 2,083 characters, with no more than 2,048 characters in the path portion of the URL
  • Firefox: 65,536 characters show up, but longer URLs do still work even up past 100,000
  • Safari: > 80,000 characters
  • Opera: > 190,000 characters
  • IIS: 16,384 characters, but is configurable
  • Apache: 4,000 characters

From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/

Absolute vs relative URLs

In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.

Using the GET parameter of a URL in JavaScript

I made this variation of gnarf's solution, so the call and the result is similar to PHP:

function S_GET(id){
    var a = new RegExp(id+"=([^&#=]*)");
    return decodeURIComponent(a.exec(window.location.search)[1]);
}

But as being called in a function slows the process, its better to use as global:

window['var_name'] = decodeURIComponent( /var_in_get=([^&#=]*)/.exec(window.location.search)[1] );

UPDATE

As I'm still learning JS, I created a better answer in a more JS behaviour:

Url = {
    get get(){
        var vars= {};
        if(window.location.search.length!==0)
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                key=decodeURIComponent(key);
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
            });
        return vars;
    }
};

This allows to be called just using Url.get.

Example The url ?param1=param1Value&param2=param2Value can be called like:

Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"

here is a snipet:

_x000D_
_x000D_
// URL GET params_x000D_
url = "?a=2&a=3&b=2&a=4";_x000D_
_x000D_
Url = {_x000D_
    get get(){_x000D_
        var vars= {};_x000D_
        if(url.length!==0)_x000D_
            url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){_x000D_
                key=decodeURIComponent(key);_x000D_
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}_x000D_
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}_x000D_
            });_x000D_
        return vars;_x000D_
    }_x000D_
};_x000D_
_x000D_
document.querySelector('log').innerHTML = JSON.stringify(Url.get);
_x000D_
<log></log>
_x000D_
_x000D_
_x000D_

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

Kotlin & clean, so you don't have to refactor before code review:

private fun addQueryParameters(url: String?): String? {
        val uri = URI(url)

        val queryParams = StringBuilder(uri.query.orEmpty())
        if (queryParams.isNotEmpty())
            queryParams.append('&')

        queryParams.append(URLEncoder.encode("$QUERY_PARAM=$param", Xml.Encoding.UTF_8.name))
        return URI(uri.scheme, uri.authority, uri.path, queryParams.toString(), uri.fragment).toString()
    }

Check if url contains string with JQuery

window.location is an object, not a string so you need to use window.location.href to get the actual string url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}

What are the safe characters for making URLs?

Looking at RFC3986 - Uniform Resource Identifier (URI): Generic Syntax, your question revolves around the path component of a URI.

    foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

Citing section 3.3, valid characters for a URI segment are of type pchar:

pchar = unreserved / pct-encoded / sub-delims / ":" / "@"

Which breaks down to:

ALPHA / DIGIT / "-" / "." / "_" / "~"

pct-encoded

"!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

":" / "@"

Or in other words: You may use any (non-control-) character from the ASCII table, except /, ?, #, [ and ].

This understanding is backed by RFC1738 - Uniform Resource Locators (URL).

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails

This sounds a reasonable approach to me, but I don't think you'll be able to get it to open mobile itunes as a second resort. I think you'll have to pick one or the other - either redirect to your app or to itunes.

i.e. if you redirect to myprotocol://, and the app isn't on the phone, you won't get a second chance to redirect to itunes.

You could perhaps first redirect to an (iphone optimised) landing page and give the user the option to click through to your app, or to itunes to get the app if they don't have it? But, you'll be relying on the user to do the right thing there. (Edit: though you could set a cookie so that is a first-time thing only?)

How to encode URL parameters?

Just try encodeURI() and encodeURIComponent() yourself...

_x000D_
_x000D_
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
_x000D_
_x000D_

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...

You should not be using encodeURIComponent() or encodeURI(). You should use fixedEncodeURIComponent() and fixedEncodeURI(), according to the MDN Documentation.

Regarding encodeURI()...

If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

Regarding encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

So, what is the difference? fixedEncodeURI() and fixedEncodeURIComponent() convert the same set of values, but fixedEncodeURIComponent() also converts this set: +@?=:*#;,$&. This set is used in GET parameters (&, +, etc.), anchor tags (#), wildcard tags (*), email/username parts (@), etc..

For example -- If you use encodeURI(), [email protected]/?email=me@home will not properly send the second @ to the server, except for your browser handling the compatibility (as Chrome naturally does often).

Is there any way to specify a suggested filename when using data: URI?

HTML only: use the download attribute:

_x000D_
_x000D_
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
_x000D_
_x000D_
_x000D_


Javascript only: you can save any data URI with this code:

_x000D_
_x000D_
function saveAs(uri, filename) {_x000D_
  var link = document.createElement('a');_x000D_
  if (typeof link.download === 'string') {_x000D_
    link.href = uri;_x000D_
    link.download = filename;_x000D_
_x000D_
    //Firefox requires the link to be in the body_x000D_
    document.body.appendChild(link);_x000D_
    _x000D_
    //simulate click_x000D_
    link.click();_x000D_
_x000D_
    //remove the link when done_x000D_
    document.body.removeChild(link);_x000D_
  } else {_x000D_
    window.open(uri);_x000D_
  }_x000D_
}_x000D_
_x000D_
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'_x000D_
saveAs(file, 'logo.gif');
_x000D_
_x000D_
_x000D_

Chrome, Firefox, and Edge 13+ will use the specified filename.

IE11, Edge 12, and Safari 9 (which don't support the download attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …

How to get the anchor from the URL using jQuery?

If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:

var url = "www.example.com/task1/1.3.html#a_1"  
var anchor = url.match(/#(.*)/)[1] 

Check if a JavaScript string is a URL

this working with me

function isURL(str) {
  var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
  var pattern = new RegExp(regex); 
return pattern.test(str);
}

How to make URL/Phone-clickable UILabel?

Swift 4.0 possible solution using UIButton

     phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05))
     phoneButton.setTitle("333-333-3333", for: .normal )
     phoneButton.setTitleColor(UIColor(red: 0 / 255, green: 0 / 255, blue: 238 / 255, alpha: 1.0), for: .normal)
     phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside )

     @objc func callPhone(){

         UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil)


    }

Allow Access-Control-Allow-Origin header using HTML5 fetch API

You need to set cors header on server side where you are requesting data from. For example if your backend server is in Ruby on rails, use following code before sending back response. Same headers should be set for any backend server.

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the other encode method in URLEncoder:

URLEncoder.encode(String, String)

The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8). For example:

System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);

How to add url parameter to the current url?

There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to:

topic.php?id=14&like=like

PHP check if url parameter exists

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

How do I send a POST request as a JSON?

for python 3.4.2 I found the following will work:

import urllib.request
import json      

body = {'ids': [12, 14, 50]}  
myurl = "http://www.testmycode.com"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

CSS background image URL failing to load

You are using a local path. Is that really what you want? If it is, you need to use the file:/// prefix:

file:///H:/media/css/static/img/sprites/buttons-v3-10.png

obviously, this will work only on your local computer.

Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://, https://) pages has been widely disabled due to security reasons.

Form Google Maps URL that searches for a specific places near specific coordinates

Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.

https://maps.google.com/?parameter=value



q=

Used to specify the search query in Google maps search.
eg :

https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679

near=

Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.

z=

Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

ll=

Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

sll=

Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

t=

Sets the kind of map shown. Can be set to:

m – normal  map
k – satellite
h – hybrid
p – terrain

saddr=

Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

daddr=

Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

via=

Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

doflg=

Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

msa=

Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Access a URL and read Data with R

In the simplest case, just do

X <- read.csv(url("http://some.where.net/data/foo.csv"))

plus which ever options read.csv() may need.

Edit in Sep 2020 or 9 years later:

For a few years now R also supports directly passing the URL to read.csv:

X <- read.csv("http://some.where.net/data/foo.csv")

End of 2020 edit. Original post continutes.

Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:

R> library(tseries)
Loading required package: quadprog
Loading required package: zoo

    ‘tseries’ version: 0.10-24

    ‘tseries’ is a package for time series analysis and computational finance.

    See ‘library(help="tseries")’ for details.

R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv?    ## manual linebreak here
  s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb

             Open   High    Low  Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]

This is all exceedingly well documented in the manual pages for help(connection) and help(url). Also see the manul on 'Data Import/Export' that came with R.

Removing the fragment identifier from AngularJS urls (# symbol)

Guess this is reallllly late for this. But adding the below config to the app.module imports does the job:

RouterModule.forRoot(routes, { useHash: false })

How do I get the YouTube video ID from a URL?

This definitely requires regex:

Copy into Ruby IRB:

var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
url.match(VID_REGEX)[1]

See for all test cases: https://gist.github.com/blairanderson/b264a15a8faaac9c6318

Javascript-Setting background image of a DIV via a function and function parameter

From what I know, the correct syntax is:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}

So basically, getElementById(tabName).backgroundImage and split the string like:

"cssInHere('and" + javascriptOutHere + "/cssAgain')";

How to download image from url

It is not necessary to use System.Drawing to find the image format in a URI. System.Drawing is not available for .NET Core unless you download the System.Drawing.Common NuGet package and therefore I don't see any good cross-platform answers to this question.

Also, my example does not use System.Net.WebClient since Microsoft explicitly discourage the use of System.Net.WebClient.

We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.

Download an image from a URL and write it to a file (cross platform)*

*Without old System.Net.WebClient and System.Drawing.

This method will asynchronously download an image (or any file as long as the URI has a file extension) using the System.Net.Http.HttpClient and then write it to a file, using the same file extension as the image had in the URI.

Getting the file extension

First part of getting the file extension is removing all the unnecessary parts from the URI.
We use Uri.GetLeftPart() with UriPartial.Path to get everything from the Scheme up to the Path.
In other words, https://www.example.com/image.png?query&with.dots becomes https://www.example.com/image.png.

After that, we use Path.GetExtension() to get only the extension (in my previous example, .png).

var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);

Downloading the image

From here it should be straight forward. Download the image with HttpClient.GetByteArrayAsync, create the path, ensure the directory exists and then write the bytes to the path with File.WriteAllBytesAsync() (or File.WriteAllBytes if you are on .NET Framework)

private async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri)
{
    using var httpClient = new HttpClient();

    // Get the file extension
    var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
    var fileExtension = Path.GetExtension(uriWithoutQuery);

    // Create file path and ensure directory exists
    var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}");
    Directory.CreateDirectory(directoryPath);

    // Download the image and write to the file
    var imageBytes = await _httpClient.GetByteArrayAsync(uri);
    await File.WriteAllBytesAsync(path, imageBytes);
}

Note that you need the following using directives.

using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;

Example usage

var folder = "images";
var fileName = "test";
var url = "https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";

await DownloadImageAsync(folder, fileName, new Uri(url));

Notes

  • It's bad practice to create a new HttpClient for every method call. It is supposed to be reused throughout the application. I wrote a short example of an ImageDownloader(50 lines) with more documentation that correctly reuses the HttpClient and properly disposes of it that you can find here.

How to get URL parameter using jQuery or plain JavaScript?

Best solution here.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

Getting absolute URLs using ASP.NET Core

For ASP.NET Core 1.0 Onwards

/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
    /// <summary>
    /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
    /// route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="actionName">The name of the action method.</param>
    /// <param name="controllerName">The name of the controller.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName,
        string controllerName,
        object routeValues = null)
    {
        return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
    /// virtual (relative) path to an application absolute path.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="contentPath">The content path.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteContent(
        this IUrlHelper url,
        string contentPath)
    {
        HttpRequest request = url.ActionContext.HttpContext.Request;
        return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified route by using the route name and route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="routeName">Name of the route.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteRouteUrl(
        this IUrlHelper url,
        string routeName,
        object routeValues = null)
    {
        return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }
}

Bonus Tip

You can't directly register an IUrlHelper in the DI container. Resolving an instance of IUrlHelper requires you to use the IUrlHelperFactory and IActionContextAccessor. However, you can do the following as a shortcut:

services
    .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
    .AddScoped<IUrlHelper>(x => x
        .GetRequiredService<IUrlHelperFactory>()
        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

ASP.NET Core Backlog

UPDATE: This won't make ASP.NET Core 5

There are indications that you will be able to use LinkGenerator to create absolute URL's without the need to provide a HttpContext (This was the biggest downside of LinkGenerator and why IUrlHelper although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".

Trying to Validate URL Using JavaScript

Demo : http://jsbin.com/uzimeb/1/edit

function checkURL(value) {
    var urlregex = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$");
    if (urlregex.test(value)) {
        return (true);
    }
    return (false);
}

Redirecting to a relative URL in JavaScript

If you use location.hostname you will get your domain.com part. Then location.pathname will give you /path/folder. I would split location.pathname by / and reassemble the URL. But unless you need the querystring, you can just redirect to .. to go a directory above.

Getting parts of a URL (Regex)

I know you're claiming language-agnostic on this, but can you tell us what you're using just so we know what regex capabilities you have?

If you have the capabilities for non-capturing matches, you can modify hometoast's expression so that subexpressions that you aren't interested in capturing are set up like this:

(?:SOMESTUFF)

You'd still have to copy and paste (and slightly modify) the Regex into multiple places, but this makes sense--you're not just checking to see if the subexpression exists, but rather if it exists as part of a URL. Using the non-capturing modifier for subexpressions can give you what you need and nothing more, which, if I'm reading you correctly, is what you want.

Just as a small, small note, hometoast's expression doesn't need to put brackets around the 's' for 'https', since he only has one character in there. Quantifiers quantify the one character (or character class or subexpression) directly preceding them. So:

https?

would match 'http' or 'https' just fine.

Fixed page header overlaps in-page anchors

CSS trick will be a workaround. A proper solution which will work in all scenario can be implemented using jQuery.

Refer to https://codepen.io/pikeshmn/pen/mMxEdZ

Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight And offset the scroll to this value.

var jump=function(e){  

e.preventDefault();                        //prevent "hard" jump
  var target = $(this).attr("href");       //get the target

      //perform animated scrolling
      $('html,body').animate(
        {
          scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5  //get top-position of target-element and set it as scroll target
        },1000,function()                  //scrolldelay: 1 seconds
        {
          location.hash = target;          //attach the hash (#jumptarget) to the pageurl
        });
      }

  $(document).ready(function()
  {
    $('a[href*="#"]').bind("click", jump); //get all hrefs
    return false;
  });

P.S:

  • It includes a nice 5 pixels difference between header and target
  • Scroll effect is not hard, rather smooth; Smooth Scrolling

How do I parse a URL into hostname and path in javascript?

a simple hack with the first answer

var getLocation = function(href=window.location.href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname

How to get the size of a file in MB (Megabytes)?

     String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
     File file = new File(FILE_NAME);

    if((file.length()) <= (1048576)) {      
        System.out.println("file size is less than 1 mb");
        }else {
            System.out.println("file size is More  than 1 mb");             
        }

Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb

How to get the value from the GET parameters?

Here is what I do:

var uriParams = getSearchParameters();
alert(uriParams.c);


// background functions:

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

A potentially dangerous Request.Path value was detected from the client (*)

Try to set web project's server propery as Local IIS if it is IIS Express. Be sure if project url is right and create virual directory.

Encode URL in JavaScript?

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

Pass a local file in to URL in Java

You can also use

[AnyClass].class.getResource(filePath)

Facebook page automatic "like" URL (for QR Code)

The answers above seem partly outdated.

The URL builder on https://developers.facebook.com/docs/plugins/like-button/ worked nicely for me.

You can configure, preview and the get the code/URL in different flavors: HTML5, XFBML, IFRAME, URL

Is a URL allowed to contain a space?

Urls should not have spaces in them. If you need to address one that does, use its encoded value of %20

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

What is syntax for selector in CSS for next element?

You can use the sibling selector ~:

h1.hc-reform ~ p{
     clear:both;
}

This selects all the p elements that come after .hc-reform, not just the first one.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.

PHP 7 simpleXML

For Ubuntu 14.04 with

PHP 7.0.13-1+deb.sury.org~trusty+1 (cli) ( NTS )

sudo apt-get install php-xml

worked for me.

Remote origin already exists on 'git push' to a new repository

The previous solutions seem to ignore origin, and they only suggest to use another name. When you just want to use git push origin, keep reading.

The problem appears because a wrong order of Git configuration is followed. You might have already added a 'git origin' to your .git configuration.

You can change the remote origin in your Git configuration with the following line:

git remote set-url origin [email protected]:username/projectname.git

This command sets a new URL for the Git repository you want to push to. Important is to fill in your own username and projectname

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.

library(ggplot2)
library(ggrepel)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_classic()

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

I've ported Grant Burton's PHP code to an ASP.Net static method callable against the HttpRequestBase. It will optionally skip through any private IP ranges.

public static class ClientIP
{
    // based on http://www.grantburton.com/2008/11/30/fix-for-incorrect-ip-addresses-in-wordpress-comments/
    public static string ClientIPFromRequest(this HttpRequestBase request, bool skipPrivate)
    {
        foreach (var item in s_HeaderItems)
        {
            var ipString = request.Headers[item.Key];

        if (String.IsNullOrEmpty(ipString))
            continue;

        if (item.Split)
        {
            foreach (var ip in ipString.Split(','))
                if (ValidIP(ip, skipPrivate))
                    return ip;
        }
        else
        {
            if (ValidIP(ipString, skipPrivate))
                return ipString;
        }
    }

    return request.UserHostAddress;
}

private static bool ValidIP(string ip, bool skipPrivate)
{
    IPAddress ipAddr;

    ip = ip == null ? String.Empty : ip.Trim();

    if (0 == ip.Length
        || false == IPAddress.TryParse(ip, out ipAddr)
        || (ipAddr.AddressFamily != AddressFamily.InterNetwork
            && ipAddr.AddressFamily != AddressFamily.InterNetworkV6))
        return false;

    if (skipPrivate && ipAddr.AddressFamily == AddressFamily.InterNetwork)
    {
        var addr = IpRange.AddrToUInt64(ipAddr);
        foreach (var range in s_PrivateRanges)
        {
            if (range.Encompasses(addr))
                return false;
        }
    }

    return true;
}

/// <summary>
/// Provides a simple class that understands how to parse and
/// compare IP addresses (IPV4) ranges.
/// </summary>
private sealed class IpRange
{
    private readonly UInt64 _start;
    private readonly UInt64 _end;

    public IpRange(string startStr, string endStr)
    {
        _start = ParseToUInt64(startStr);
        _end = ParseToUInt64(endStr);
    }

    public static UInt64 AddrToUInt64(IPAddress ip)
    {
        var ipBytes = ip.GetAddressBytes();
        UInt64 value = 0;

        foreach (var abyte in ipBytes)
        {
            value <<= 8;    // shift
            value += abyte;
        }

        return value;
    }

    public static UInt64 ParseToUInt64(string ipStr)
    {
        var ip = IPAddress.Parse(ipStr);
        return AddrToUInt64(ip);
    }

    public bool Encompasses(UInt64 addrValue)
    {
        return _start <= addrValue && addrValue <= _end;
    }

    public bool Encompasses(IPAddress addr)
    {
        var value = AddrToUInt64(addr);
        return Encompasses(value);
    }
};

private static readonly IpRange[] s_PrivateRanges =
    new IpRange[] { 
            new IpRange("0.0.0.0","2.255.255.255"),
            new IpRange("10.0.0.0","10.255.255.255"),
            new IpRange("127.0.0.0","127.255.255.255"),
            new IpRange("169.254.0.0","169.254.255.255"),
            new IpRange("172.16.0.0","172.31.255.255"),
            new IpRange("192.0.2.0","192.0.2.255"),
            new IpRange("192.168.0.0","192.168.255.255"),
            new IpRange("255.255.255.0","255.255.255.255")
    };


/// <summary>
/// Describes a header item (key) and if it is expected to be 
/// a comma-delimited string
/// </summary>
private sealed class HeaderItem
{
    public readonly string Key;
    public readonly bool Split;

    public HeaderItem(string key, bool split)
    {
        Key = key;
        Split = split;
    }
}

// order is in trust/use order top to bottom
private static readonly HeaderItem[] s_HeaderItems =
    new HeaderItem[] { 
            new HeaderItem("HTTP_CLIENT_IP",false),
            new HeaderItem("HTTP_X_FORWARDED_FOR",true),
            new HeaderItem("HTTP_X_FORWARDED",false),
            new HeaderItem("HTTP_X_CLUSTER_CLIENT_IP",false),
            new HeaderItem("HTTP_FORWARDED_FOR",false),
            new HeaderItem("HTTP_FORWARDED",false),
            new HeaderItem("HTTP_VIA",false),
            new HeaderItem("REMOTE_ADDR",false)
    };
}

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

Adobe Acrobat Pro make all pages the same dimension

The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.

Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

Just drag a cell (as you did for TableViewController) and add in to it just by releasing the cell on TableViewController. Click on the cell and.Go to its attributes inspector and set its identifier as "Cell".Hope it works.


Don't forget you want Identifier on the Attributes Inspector.

(NOT the "Restoration ID" on the "Identity Inspector" !)

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

How to get current route

import { Router, NavigationEnd } from "@angular/router";

constructor(private router: Router) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
});

How to rename HTML "browse" button of an input type=file?

  1. Wrap the <input type="file"> with a <label> tag;
  2. Add a tag (with the text that you need) inside the label, like a <span> or <a>;
  3. Make this tag look like a button;
  4. Make input[type="file"] invisible via display: none.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Here's one approach which automates creating labels above each column of a listbox (on a worksheet).

It will work (though not super-pretty!) as long as there's no horizontal scrollbar on your listbox.

Sub Tester()
Dim i As Long

With Me.lbTest
    .Clear
    .ColumnCount = 5
    'must do this next step!
    .ColumnWidths = "70;60;100;60;60"
    .ListStyle = fmListStylePlain
    Debug.Print .ColumnWidths
    For i = 0 To 10
        .AddItem
        .List(i, 0) = "blah" & i
        .List(i, 1) = "blah"
        .List(i, 2) = "blah"
        .List(i, 3) = "blah"
        .List(i, 4) = "blah"
    Next i

End With

LabelHeaders Me.lbTest, Array("Header1", "Header2", _
                     "Header3", "Header4", "Header5")

End Sub

Sub LabelHeaders(lb, arrHeaders)

    Const LBL_HT As Long = 15
    Dim T, L, shp As Shape, cw As String, arr
    Dim i As Long, w

    'delete any previous headers for this listbox
    For i = lb.Parent.Shapes.Count To 1 Step -1
        If lb.Parent.Shapes(i).Name Like lb.Name & "_*" Then
            lb.Parent.Shapes(i).Delete
        End If
    Next i

    'get an array of column widths
    cw = lb.ColumnWidths
    If Len(cw) = 0 Then Exit Sub
    cw = Replace(cw, " pt", "")
    arr = Split(cw, ";")

    'start points for labels
    T = lb.Top - LBL_HT
    L = lb.Left

    For i = LBound(arr) To UBound(arr)
        w = CLng(arr(i))
        If i = UBound(arr) And (L + w) < lb.Width Then w = lb.Width - L
        Set shp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, _
                                         L, T, w, LBL_HT)
        With shp
            .Name = lb.Name & "_" & i
            'do some formatting
            .Line.ForeColor.RGB = vbBlack
            .Line.Weight = 1
            .Fill.ForeColor.RGB = RGB(220, 220, 220)
            .TextFrame2.TextRange.Characters.Text = arrHeaders(i)
            .TextFrame2.TextRange.Font.Size = 9
            .TextFrame2.TextRange.Font.Fill.ForeColor.RGB = vbBlack
        End With
        L = L + w
    Next i
End Sub

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

Best place to insert the Google Analytics code

Google used to recommend putting it just before the </body> tag, because the original method they provided for loading ga.js was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head> tag.

<head> will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.

As a matter of personal preference, I like to include it in the <head>, but its really a matter of preference.

Understanding slice notation

Index:
      ------------>
  0   1   2   3   4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
  0  -4  -3  -2  -1
      <------------

Slice:
    <---------------|
|--------------->
:   1   2   3   4   :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
:  -4  -3  -2  -1   :
|--------------->
    <---------------|

I hope this will help you to model the list in Python.

Reference: http://wiki.python.org/moin/MovingToPythonFromOtherLanguages

Blank HTML SELECT without blank item in dropdown list

You can try this snippet

$("#your-id")[0].selectedIndex = -1

It worked for me.

Android ListView Divider

The android docs warn about things dissappearing due to round-off error... Perhaps try dp instead of px, and perhaps also try > 1 first to see if it is the round-off problem.

see http://developer.android.com/guide/practices/screens_support.html#testing

for the section "Images with 1 pixel height/width"

Are iframes considered 'bad practice'?

The original frameset model (Frameset and Frame-elements) were very bad from a usability standpoint. IFrame vas a later invention which didn't have as many problems as the original frameset model, but it does have its drawback.

If you allow the user to navigate inside the IFrame, then links and bookmarks will not work as expected (because you bookmark the URL of the outer page, but not the URL of the iframe).

Principal Component Analysis (PCA) in Python

I posted my answer even though another answer has already been accepted; the accepted answer relies on a deprecated function; additionally, this deprecated function is based on Singular Value Decomposition (SVD), which (although perfectly valid) is the much more memory- and processor-intensive of the two general techniques for calculating PCA. This is particularly relevant here because of the size of the data array in the OP. Using covariance-based PCA, the array used in the computation flow is just 144 x 144, rather than 26424 x 144 (the dimensions of the original data array).

Here's a simple working implementation of PCA using the linalg module from SciPy. Because this implementation first calculates the covariance matrix, and then performs all subsequent calculations on this array, it uses far less memory than SVD-based PCA.

(the linalg module in NumPy can also be used with no change in the code below aside from the import statement, which would be from numpy import linalg as LA.)

The two key steps in this PCA implementation are:

  • calculating the covariance matrix; and

  • taking the eivenvectors & eigenvalues of this cov matrix

In the function below, the parameter dims_rescaled_data refers to the desired number of dimensions in the rescaled data matrix; this parameter has a default value of just two dimensions, but the code below isn't limited to two but it could be any value less than the column number of the original data array.


def PCA(data, dims_rescaled_data=2):
    """
    returns: data transformed in 2 dims/columns + regenerated original data
    pass in: data as 2D NumPy array
    """
    import numpy as NP
    from scipy import linalg as LA
    m, n = data.shape
    # mean center the data
    data -= data.mean(axis=0)
    # calculate the covariance matrix
    R = NP.cov(data, rowvar=False)
    # calculate eigenvectors & eigenvalues of the covariance matrix
    # use 'eigh' rather than 'eig' since R is symmetric, 
    # the performance gain is substantial
    evals, evecs = LA.eigh(R)
    # sort eigenvalue in decreasing order
    idx = NP.argsort(evals)[::-1]
    evecs = evecs[:,idx]
    # sort eigenvectors according to same index
    evals = evals[idx]
    # select the first n eigenvectors (n is desired dimension
    # of rescaled data array, or dims_rescaled_data)
    evecs = evecs[:, :dims_rescaled_data]
    # carry out the transformation on the data using eigenvectors
    # and return the re-scaled data, eigenvalues, and eigenvectors
    return NP.dot(evecs.T, data.T).T, evals, evecs

def test_PCA(data, dims_rescaled_data=2):
    '''
    test by attempting to recover original data array from
    the eigenvectors of its covariance matrix & comparing that
    'recovered' array with the original data
    '''
    _ , _ , eigenvectors = PCA(data, dim_rescaled_data=2)
    data_recovered = NP.dot(eigenvectors, m).T
    data_recovered += data_recovered.mean(axis=0)
    assert NP.allclose(data, data_recovered)


def plot_pca(data):
    from matplotlib import pyplot as MPL
    clr1 =  '#2026B2'
    fig = MPL.figure()
    ax1 = fig.add_subplot(111)
    data_resc, data_orig = PCA(data)
    ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)
    MPL.show()

>>> # iris, probably the most widely used reference data set in ML
>>> df = "~/iris.csv"
>>> data = NP.loadtxt(df, delimiter=',')
>>> # remove class labels
>>> data = data[:,:-1]
>>> plot_pca(data)

The plot below is a visual representation of this PCA function on the iris data. As you can see, a 2D transformation cleanly separates class I from class II and class III (but not class II from class III, which in fact requires another dimension).

enter image description here

How to handle screen orientation change when progress dialog and background thread active?

I've tried EVERYTHING. Spent days experimenting. I didn't want to block the activity from rotating. My scenario was:

  1. A progress dialog showing dynamic information to the user. E.g.: "Connecting to server...", "Downloading data...", etc.
  2. A thread doing the heavy stuff and updating the dialog
  3. Updating the UI with the results at the end.

The problem was, when rotating the screen, every solution on the book failed. Even with the AsyncTask class, which is the correct Android way of dealing with this situations. When rotating the screen, the current Context that the starting thread is working with, is gone, and that messes up with the dialog that is showing. The problem was always the Dialog, no matter how many tricks I added to the code (passing new contexts to running threads, retaining thread states through rotations, etc...). The code complexity at the end was always huge and there was always something that could go wrong.

The only solution that worked for me was the Activity/Dialog trick. It's simple and genius and it's all rotation proof:

  1. Instead of creating a Dialog and ask to show it, create an Activity that has been set in the manifest with android:theme="@android:style/Theme.Dialog". So, it just looks like a dialog.

  2. Replace showDialog(DIALOG_ID) with startActivityForResult(yourActivityDialog, yourCode);

  3. Use onActivityResult in the calling Activity to get the results from the executing thread (even the errors) and update the UI.

  4. On your 'ActivityDialog', use threads or AsyncTask to execute long tasks and onRetainNonConfigurationInstance to save "dialog" state when rotating the screen.

This is fast and works fine. I still use dialogs for other tasks and the AsyncTask for something that doesn't require a constant dialog on screen. But with this scenario, I always go for the Activity/Dialog pattern.

And, I didn't try it, but it's even possible to block that Activity/Dialog from rotating, when the thread is running, speeding things up, while allowing the calling Activity to rotate.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

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

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Where is localhost folder located in Mac or Mac OS X?

There are actually two place where where mac os x serves website by default:

/Library/WebServer/Documents --> http://localhost

~/Sites --> http://localhost/~user/

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

phpmailer - The following SMTP Error: Data not accepted

Try to set the port on 26, this has fixed my problem with the message "data not accepted".

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

What is “assert” in JavaScript?

Previous answers can be improved in terms of performances and compatibility.

Check once if the Error object exists, if not declare it :

if (typeof Error === "undefined") {
    Error = function(message) {
        this.message = message;
    };
    Error.prototype.message = "";
}

Then, each assertion will check the condition, and always throw an Error object

function assert(condition, message) {
    if (!condition) throw new Error(message || "Assertion failed");
}

Keep in mind that the console will not display the real error line number, but the line of the assert function, which is not useful for debugging.

In C#, how to check if a TCP port is available?

You're on the wrong end of the Intertube. It is the server that can have only one particular port open. Some code:

  IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
  try {
    TcpListener tcpListener = new TcpListener(ipAddress, 666);
    tcpListener.Start();
  }
  catch (SocketException ex) {
    MessageBox.Show(ex.Message, "kaboom");
  }

Fails with:

Only one usage of each socket address (protocol/network address/port) is normally permitted.

How to emulate GPS location in the Android Emulator?

For the new emulator:

http://developer.android.com/tools/devices/emulator.html#extended

Basically, click on the three dots button in the emulator controls (to the right of the emulator) and it will open up a menu which will allow you to control the emulator including location

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

How to show full height background image?

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

How to use the read command in Bash?

Do you need the pipe?

echo -ne "$MENU"
read NUMBER

Git push rejected "non-fast-forward"

try this command

$ git push -f -u origin <name of branch>

i.e $ git push -f -u origin master

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

intellij incorrectly saying no beans of type found for autowired repository

As long as your tests are passing you are good, hit alt + enter by taking the cursor over the error and inside the submenu of the first item you will find Disable Inspection select that

Conda activate not working?

If your console does not show (base) after running conda activate base, then try running:

conda init

Then running conda activate <your_env> should show the name of (<your_env>) at the beginning of the shell prompt.

This worked for me on Windows. My PATH environment variable was set properly so conda activate base did not raise any error but quietly failed.

What's the difference between xsd:include and xsd:import?

Direct quote from MSDN: <xsd:import> Element, Remarks section

The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.

MySQL Insert into multiple tables? (Database normalization?)

For PDO You may do this

$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')"; 
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";

$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);

BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

Is there a Visual Basic 6 decompiler?

I have used VB Decompiler Lite (http://www.vb-decompiler.org/) in the past, and although it does not give you the original source code, it does give you a lot of information such as method names, some variable strings, etc. With more knowledge (or with the full version) it might be possible to get even more than this.

Cannot make Project Lombok work on Eclipse

This is for setup of lombok on Spring Tool Suite. Here is what I did on spring tool suite (sts-4.4.0.RELEASE) and lombok-1.18.10.jar (current latest version available in mavenrepository).

  1. If having maven project, ensure lombok dependency added to it. Else you need manually add the jar to your project classpath.

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> <scope>provided</scope> </dependency>

  2. Clean build the maven application. This will download lombok jar in your .m2 location by default from maven repository. The path would be org\projectlombok\lombok\1.18.10\

  3. Now open command prompt and navigate to the lombok path and execute command java -jar lombok-1.18.10.jar

    C:\xxx\xxx\org\projectlombok\lombok\1.18.10>java -jar lombok-1.18.10.jar

  4. Opens up lombok dialog box. If see message Can't find IDE Click Specify location... Provide the path to your STS root location

    My case it is C:\apps\sts-4.4.0.RELEASE\SpringToolSuite.exe

    Install/Update

  5. Install successful Click Quit Installer

  6. Now in explorer navigate to your STS root path. C:\apps\sts-4.4.0.RELEASE\ We see lombok.jar placed in the sts root path Now edit in notepad SpringToolSuite4.ini file We see following appended at the end

    -javaagent:C:\apps\sts-4.4.0.RELEASE\lombok.jar

  7. Start STS using SpringToolSuite4.exe Clean, rebuild your project.

Deleting all pending tasks in celery / rabbitmq

In Celery 3+:

CLI:

$ celery -A proj purge

Programatically:

>>> from proj.celery import app
>>> app.control.purge()

http://docs.celeryproject.org/en/latest/faq.html#how-do-i-purge-all-waiting-tasks

Importing Excel into a DataTable Quickly

 class DataReader
    {
        Excel.Application xlApp;
        Excel.Workbook xlBook;
        Excel.Range xlRange;
        Excel.Worksheet xlSheet;
        public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
        {
            DataTable dt = new DataTable();
            try
            {
                xlApp = new Excel.Application();
                xlBook = xlApp.Workbooks.Open(filePath);
                xlSheet = xlBook.Worksheets[sheetName];
                xlRange = xlSheet.UsedRange;
                DataRow row=null;
                for (int i = 1; i <= xlRange.Rows.Count; i++)
                {
                    if (i != 1)
                        row = dt.NewRow();
                    for (int j = 1; j <= xlRange.Columns.Count; j++)
                    {
                        if (i == 1)
                            dt.Columns.Add(xlRange.Cells[1, j].value);
                        else
                            row[j-1] = xlRange.Cells[i, j].value;
                    }
                    if(row !=null)
                        dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlBook.Close();
                xlApp.Quit();
            }
            return dt;
        }
    }

Make new column in Panda dataframe by adding values from other columns

You can solve it by adding simply: df['C'] = df['A'] + df['B']

Angular - ui-router get previous state

Here is a really elegant solution from Chris Thielen ui-router-extras: $previousState

var previous = $previousState.get(); //Gets a reference to the previous state.

previous is an object that looks like: { state: fromState, params: fromParams } where fromState is the previous state and fromParams is the previous state parameters.

Nesting await in Parallel.ForEach

You can save effort with the new AsyncEnumerator NuGet Package, which didn't exist 4 years ago when the question was originally posted. It allows you to control the degree of parallelism:

using System.Collections.Async;
...

await ids.ParallelForEachAsync(async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
},
maxDegreeOfParallelism: 10);

Disclaimer: I'm the author of the AsyncEnumerator library, which is open source and licensed under MIT, and I'm posting this message just to help the community.

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Definitely, git filter-branch is the way to go.

Sadly, this will not suffice to completely remove filename.orig from your repo, as it can be still be referenced by tags, reflog entries, remotes and so on.

I recommend removing all these references as well, and then calling the garbage collector. You can use the git forget-blob script from this website to do all this in one step.

git forget-blob filename.orig

Get class list for element with jQuery

I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:

$('<img>').hasClass("nameOfMyClass"); 

but I got a nice "this function is not available for this element".

Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.

$('img').className // it contains "class1 class2 class3"

Once you get this, just split the string as usual.

In my case this worked:

var listOfClassesOfMyElement= $('img').className.split(" ");

I am assuming this would work with other kinds of elements (besides img).

Hope it helps.

SQL Server Restore Error - Access is Denied

In my case - I had to double check the Backup path of the database from where I was restoring. I had previously restored it from a different path when I did it the first time. I fixed the Backup path to use the backup path I used the first time and it worked!

Rails DB Migration - How To Drop a Table?

Run

rake db:migrate:down VERSION=<version>

Where <version> is the version number of your migration file you want to revert.

Example:-

rake db:migrate:down VERSION=3846656238

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

This problem happens when you install the JDK by _uncompressing_ it instead of _executing_ it.

By example:

unzip jdk-6u45-linux-x64.bin  (wrong)

sh ./jdk-6u45-linux-x64.bin   (right)

In the first scenario, the runtime libraries, as rt.jar, don't get automatically uncompresessed (thus, you can find the rt.pack files, etc. instead of the .jar ones).

codeigniter, result() vs. result_array()

Returning pure array is slightly faster than returning an array of objects.

Is there a standard sign function (signum, sgn) in C/C++?

Is there a standard sign function (signum, sgn) in C/C++?

Yes, depending on definition.

C99 and later has the signbit() macro in <math.h>

int signbit(real-floating x);
The signbit macro returns a nonzero value if and only if the sign of its argument value is negative. C11 §7.12.3.6


Yet OP wants something a little different.

I want a function that returns -1 for negative numbers and +1 for positive numbers. ... a function working on floats.

#define signbit_p1_or_n1(x)  ((signbit(x) ?  -1 : 1)

Deeper:

The post is not specific in the following cases: x = 0.0, -0.0, +NaN, -NaN.

A classic signum() returns +1 on x>0, -1 on x<0 and 0 on x==0.

Many answers have already covered that, but do not address x = -0.0, +NaN, -NaN. Many are geared for an integer point-of-view that usually lacks Not-a-Numbers (NaN) and -0.0.

Typical answers function like signnum_typical() On -0.0, +NaN, -NaN, they return 0.0, 0.0, 0.0.

int signnum_typical(double x) {
  if (x > 0.0) return 1;
  if (x < 0.0) return -1;
  return 0;
}

Instead, I propose this functionality: On -0.0, +NaN, -NaN, it returns -0.0, +NaN, -NaN.

double signnum_c(double x) {
  if (x > 0.0) return 1.0;
  if (x < 0.0) return -1.0;
  return x;
}

Detect Android phone via Javascript / jQuery

Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

PHP:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js

Drop all tables command

I had this issue in Android and I wrote a method similar to it-west.

Because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I didn't want to drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method

private void dropAllUserTables(SQLiteDatabase db) {
    Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    //noinspection TryFinallyCanBeTryWithResources not available with API < 19
    try {
        List<String> tables = new ArrayList<>(cursor.getCount());

        while (cursor.moveToNext()) {
            tables.add(cursor.getString(0));
        }

        for (String table : tables) {
            if (table.startsWith("sqlite_")) {
                continue;
            }
            db.execSQL("DROP TABLE IF EXISTS " + table);
            Log.v(LOG_TAG, "Dropped table " + table);
        }
    } finally {
        cursor.close();
    }
}

String comparison using '==' vs. 'strcmp()'

Also The function can help in sorting. To be more clear about sorting. strcmp() returns less than 0 if string1 sorts before string2, greater than 0 if string2 sorts before string1 or 0 if they are the same. For example

$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string,$second_string);

The function will return greater than zero, as aaao is sorting before aabo.

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

Programmatically get the version number of a DLL

You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.

Mapping two integers to one, in a unique and deterministic way

Say you have a 32 bit integer, why not just move A into the first 16 bit half and B into the other?

def vec_pack(vec):
    return vec[0] + vec[1] * 65536;


def vec_unpack(number):
    return [number % 65536, number // 65536];

Other than this being as space efficient as possible and cheap to compute, a really cool side effect is that you can do vector math on the packed number.

a = vec_pack([2,4])
b = vec_pack([1,2])

print(vec_unpack(a+b)) # [3, 6] Vector addition
print(vec_unpack(a-b)) # [1, 2] Vector subtraction
print(vec_unpack(a*2)) # [4, 8] Scalar multiplication

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

jQuery onclick event for <li> tags

Here, to get the text of the menu that triggered the event (does not seem to have any id):

 $(document).ready(function() 
 {
    $('ul.art-vmenu li').click(function(e) 
    { 
     alert($(this).find("span.t").text());
    });
 });

If input value is blank, assign a value of "empty" with Javascript

If you're using pure JS you can simply do it like:

var input = document.getElementById('myInput');

if(input.value.length == 0)
    input.value = "Empty";

Here's a demo: http://jsfiddle.net/nYtm8/

How to convert PDF files to images

Apache PDFBox also works great for me.

Usage with the command line tool:

javar -jar pdfbox-app-2.0.19.jar PDFToImage -quality 1.0  -dpi 150 -prefix out_dir/page -format png

Autowiring fails: Not an managed Type

In my case, when using IntelliJ, I had multiple modules in the project. The main module was dependent on another module which had the maven dependencies on Spring.

The main module had Entitys and so did the second module. But when I ran the main module, only the Entitys from the second module got recognized as managed classes.

I then added Spring dependencies on the main module as well, and guess what? It recognized all the Entitys.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

If your app server is weblogic, then make sure WLProxySSL ON entry exists(and also make sure it should not be commented) in the weblogic.conf file in webserver's conf directory. then restart web server, it will work.

Make multiple-select to adjust its height to fit options without scroll bar

For jQuery you can try this. I always do the following and it works.

$(function () {
   $("#multiSelect").attr("size",$("#multiSelect option").length);
});

Difference between xcopy and robocopy

I have written lot of scripts to automate daily backups etc. Previously I used XCopy and then moved to Robocopy. Anyways Robocopy and XCopy both are frequently used in terms of file transfers in Windows. Robocopy stands for Robust File Copy. All type of huge file copying both these commands are used but Robocopy has added options which makes copying easier as well as for debugging purposes.

Having said that lets talk about features between these two.

  • Robocopy becomes handy for mirroring or synchronizing directories. It also checks the files in the destination directory against the files to be copied and doesn't waste time copying unchanged files.

  • Just like myself, if you are into automation to take daily backups etc, "Run Hours - /RH" becomes very useful without any interactions. This is supported by Robocopy. It allows you to set when copies should be done rather than the time of the command as with XCopy. You will see robocopy.exe process in task list since it will run background to monitor clock to execute when time is right to copy.

  • Robocopy supports file and directory monitoring with the "/MON" or "/MOT" commands.

  • Robocopy gives extra support for copying over the "archive" attribute on files, it supports copying over all attributes including timestamps, security, owner, and auditing information.

Hope this helps you.

ImportError: No module named dateutil.parser

If you are using Pipenv, you may need to add this to your Pipfile:

[packages]
python-dateutil = "*"

Get method arguments using Spring AOP?

if your using @Aspect an option is add this method inside your Aspect and send the JoinPoint and the name of parameter you need.

private Object getParameter(ProceedingJoinPoint joinPoint, String parameterName) {
    Object valueParameter = null;
    if (Objects.nonNull(joinPoint) && joinPoint.getSignature() instanceof MethodSignature
            && Objects.nonNull(parameterName) ) {
        MethodSignature method = (MethodSignature)joinPoint.getSignature();
        String[] parameters = method.getParameterNames();
        for (int t = 0; t< parameters.length; t++) {
            if( Objects.nonNull(parameters[t]) && parameters[t].equals(parameterName)) {
                Object[] obj = joinPoint.getArgs();
                valueParameter = obj[t];
            }
        }
    }
    return valueParameter;
}

and the call example:

Object parameterObject = getParameter(joinPoint, "nameClient");
if ( Objects.nonNull(parameterObject) ) {
    String parametro = String.valueOf(parameterObject);
}

Only need know the type of object for convert

What's the canonical way to check for type in Python?

The most Pythonic way to check the type of an object is... not to check it.

Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

android ellipsize multiline textview

In my case, there is no need to code this in Java. Everything works as expected. No need for something like android:singleLine="false".

<TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:ellipsize="end"
  android:maxLines="4"
  android:text="@string/very_long_text" />

But there seems to be a bug in the layout preview of Android Studio (v3.0): layout preview

Given Android 7.1.1 on my device this is working: device screenshot

Expanding a parent <div> to the height of its children

_x000D_
_x000D_
#childRightCol_x000D_
{_x000D_
float:right;_x000D_
}_x000D_
#childLeftCol_x000D_
{_x000D_
float:left;_x000D_
}_x000D_
#parent_x000D_
{_x000D_
    display:inline;_x000D_
}
_x000D_
_x000D_
_x000D_

How do I change the UUID of a virtual disk?

Though you have solved the problem, I just post the reason here for some others with the similar problem.

The reason is there's an space in your path(directory name VirtualBox VMs) which will separate the command. So the error appears.

Java default constructor

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

How to print the current time in a Batch-File?

If you use the command

time /T

that will print the time. (without the /T, it will try to set the time)

date /T

is similar for the date.

If cmd's Command Extensions are enabled (they are enabled by default, but in this question they appear to be disabled), then the environment variables %DATE% and %TIME% will expand to the current date and time each time they are expanded. The format used is the same as the DATE and TIME commands.

To see the other dynamic environment variables that exist when Command Extensions are enabled, run set /?.

count number of characters in nvarchar column

Use the LEN function:

Returns the number of characters of the specified string expression, excluding trailing blanks.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

How to close Android application?

Use "this.FinishAndRemoveTask();" - it closes application properly

Thymeleaf using path variables to th:href

You can use like

  1. My table is bellow like..

    <table>
       <thead>
        <tr>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user: ${staffList}">
            <td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
        </tr>
     </tbody>
    </table>
    
  2. Here is my controller ..

    @GetMapping(value = "/details-view/{userId}")
    public String details(@PathVariable String userId) { 
    
        Logger.getLogger(getClass().getName()).info("userId-->" + userId);
    
     return "user-details";
    }
    

What's the difference between git reset --mixed, --soft, and --hard?

You don't have to force yourself to remember differences between them. Think of how you actually made a commit.

  1. Make some changes.

  2. git add .

  3. git commit -m "I did Something"

Soft, Mixed and Hard is the way enabling you to give up the operations you did from 3 to 1.

  • Soft "pretended" to never see you have did git commit.
  • Mixed "pretended" to never see you have did git add .
  • Hard "pretended" to never see you have made file changes.

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

Error inflating when extending a class

I think I figured out why this wasn't working. I was only providing a constructor for the case of one parameter 'context' when I should have provided a constructor for the two parameter 'Context, AttributeSet' case. I also needed to give the constructor(s) public access. Here's my fix:

public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
        SurfaceHolder mHolder;
        Camera mCamera;

        public GhostSurfaceCameraView(Context context)
        {
            super(context);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

TSQL - Cast string to integer or return default value

My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.

CREATE FUNCTION [dbo].[udfIsInteger]
(
    -- Add the parameters for the function here
    @Value nvarchar(max)
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result int = 0

    -- Add the T-SQL statements to compute the return value here
    DECLARE @MinValue nvarchar(11) = '-2147483648'
    DECLARE @MaxValue nvarchar(10) = '2147483647'

    SET @Value = ISNULL(@Value,'')

    IF LEN(@Value)=0 OR 
      ISNUMERIC(@Value)<>1 OR
      (LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
      (LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
      GOTO FINISHED

    DECLARE @cnt int = 0
    WHILE @cnt<LEN(@Value)
    BEGIN
      SET @cnt=@cnt+1
      IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
    END
    SET @Result=1

FINISHED:
    -- Return the result of the function
    RETURN @Result

END

Generating a Random Number between 1 and 10 Java

The standard way to do this is as follows:

Provide:

  • min Minimum value
  • max Maximum value

and get in return a Integer between min and max, inclusive.

Random rand = new Random();

// nextInt as provided by Random is exclusive of the top value so you need to add 1 

int randomNum = rand.nextInt((max - min) + 1) + min;

See the relevant JavaDoc.

As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

Order data frame rows according to vector with specific order

I prefer to use ***_join in dplyr whenever I need to match data. One possible try for this

left_join(data.frame(name=target),df,by="name")

Note that the input for ***_join require tbls or data.frame

How to convert a string with Unicode encoding to a string of letters

For Java 9+, you can use the new replaceAll method of Matcher class.

private static final Pattern UNICODE_PATTERN = Pattern.compile("\\\\u([0-9A-Fa-f]{4})");

public static String unescapeUnicode(String unescaped) {
    return UNICODE_PATTERN.matcher(unescaped).replaceAll(r -> String.valueOf((char) Integer.parseInt(r.group(1), 16)));
}

public static void main(String[] args) {
    String originalMessage = "\\u0048\\u0065\\u006C\\u006C\\u006F World";
    String unescapedMessage = unescapeUnicode(originalMessage);
    System.out.println(unescapedMessage);
}

I believe the main advantage of this approach over unescapeJava by StringEscapeUtils (besides not using an extra library) is that you can convert only the unicode characters (if you wish), since the latter converts all escaped Java characters (like \n or \t). If you prefer to convert all escaped characters the library is really the best option.

How can I properly handle 404 in ASP.NET MVC?

I really like cottsaks solution and think its very clearly explained. my only addition was to alter step 2 as follows

public abstract class MyController : Controller
{

    #region Http404 handling

    protected override void HandleUnknownAction(string actionName)
    {
        //if controller is ErrorController dont 'nest' exceptions
        if(this.GetType() != typeof(ErrorController))
        this.InvokeHttp404(HttpContext);
    }

    public ActionResult InvokeHttp404(HttpContextBase httpContext)
    {
        IController errorController = ObjectFactory.GetInstance<ErrorController>();
        var errorRoute = new RouteData();
        errorRoute.Values.Add("controller", "Error");
        errorRoute.Values.Add("action", "Http404");
        errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
        errorController.Execute(new RequestContext(
             httpContext, errorRoute));

        return new EmptyResult();
    }

    #endregion
}

Basically this stops urls containing invalid actions AND controllers from triggering the exception routine twice. eg for urls such as asdfsdf/dfgdfgd

Update records in table from CTE

You don't need a CTE for this

UPDATE PEDI_InvoiceDetail
SET
    DocTotal = v.DocTotal
FROM
     PEDI_InvoiceDetail
inner join 
(
   SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
) v
   ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

What's the difference between git clone --mirror and git clone --bare

A clone copies the refs from the remote and stuffs them into a subdirectory named 'these are the refs that the remote has'.

A mirror copies the refs from the remote and puts them into its own top level - it replaces its own refs with those of the remote.

This means that when someone pulls from your mirror and stuffs the mirror's refs into thier subdirectory, they will get the same refs as were on the original. The result of fetching from an up-to-date mirror is the same as fetching directly from the initial repo.

What is the difference between id and class in CSS, and when should I use them?

  • Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.

    Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.

    Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)

    Examples of class names are: tag, comment, toolbar-button, warning-message, or email.

  • Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.

    Examples of ids are: main-content, header, footer, or left-sidebar.

A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.

Full-screen responsive background image

for Full-screen responsive background image

set css height ( height:100vh )

example :

.main-header {
    background-image: url(../img/bb-background2.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    width: 100%;
    height:100vh;  /* responsive height */
}

How to save/restore serializable object to/from file?

You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.

Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.

So, with your code, if I were using XML Serialization:

var path = @"C:\Test\myserializationtest.xml";
using(FileStream fs = new FileStream(path, FileMode.Create))
{
    XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));

    xSer.Serialize(fs, serializableObject);
}

Then, to deserialize:

using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
{
    XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));

    var myObject = _xSer.Deserialize(fs);
}

NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.

JSON - Iterate through JSONArray

for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

How do you stop tracking a remote branch in Git?

The easiest way to do this is to delete the branch remotely and then use:

git fetch --prune (aka git fetch -p)

Convert time span value to format "hh:mm Am/Pm" using C#

You can add the TimeSpan to a DateTime, for example:

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

Demo: http://ideone.com/veJ6tT

04:00 PM

Standard Date and Time Format Strings

Fetch the row which has the Max value for a column

I think this should work?

Select
T1.UserId,
(Select Top 1 T2.Value From Table T2 Where T2.UserId = T1.UserId Order By Date Desc) As 'Value'
From
Table T1
Group By
T1.UserId
Order By
T1.UserId

problem with php mail 'From' header

In order to prevent phishing, some mail servers prevent the From from being rewritten.

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

Get the generated SQL statement from a SqlCommand object?

If your database was Oracle and the sql text contains dynamic variables named like :1,:2 ,... then you can use:

string query = cmd.CommandText;
int i = 1;
foreach (OracleParameter p in cmd.Parameters)
  {
    query = query.Replace(":"+i.ToString(),((p.Value==null)?"":p.Value.ToString()));
    i++;
  }

ERROR 1064 (42000) in MySQL

Check your dump file. Looks like a stray character at the beginning. SQL isn't standard the world around, and the MySQL importer expects MySQL-friendly SQL. I'm willing to bet that your exporter did something funky.

You may have to massage the file a bit to get it to work with MySQL.

LDAP Authentication using Java

This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.

Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.

$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd

$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd

Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.

Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.

LoginLDAP.java

package test;

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class LoginLDAP {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = createParams(args);

        String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
        String principalName = params.get("username"); // [email protected]
        String domainName = params.get("domain"); // mydomain.com or empty

        if (domainName==null || "".equals(domainName)) {
            int delim = principalName.indexOf('@');
            domainName = principalName.substring(delim+1);
        }

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, url); 
        props.put(Context.SECURITY_PRINCIPAL, principalName); 
        props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
        if (url.toUpperCase().startsWith("LDAPS://")) {
            props.put(Context.SECURITY_PROTOCOL, "ssl");
            props.put(Context.SECURITY_AUTHENTICATION, "simple");
            props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");         
        }

        InitialDirContext context = new InitialDirContext(props);
        try {
            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
            if(!results.hasMore())
                throw new AuthenticationException("Principal name not found");

            SearchResult result = results.next();
            System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com

            Attribute memberOf = result.getAttributes().get("memberOf");
            if(memberOf!=null) {
                for(int idx=0; idx<memberOf.size(); idx++) {
                    System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
                    //Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
                    //System.out.println( att.get().toString() ); //  CN part of groupname
                }
            }
        } finally {
            try { context.close(); } catch(Exception ex) { }
        }       
    }

    /**
     * Create "DC=sub,DC=mydomain,DC=com" string
     * @param domainName    sub.mydomain.com
     * @return
     */
    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if(token.length()==0) continue;
            if(buf.length()>0)  buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }

    private static Map<String,String> createParams(String[] args) {
        Map<String,String> params = new HashMap<String,String>();  
        for(String str : args) {
            int delim = str.indexOf('=');
            if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
            else if (delim==0) params.put("", str.substring(1).trim());
            else params.put(str, null);
        }
        return params;
    }

}

And SSL helper class.

package test;

import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;    
import javax.net.*;
import javax.net.ssl.*;

public class DummySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;
    public DummySSLSocketFactory() {
        try {
          SSLContext ctx = SSLContext.getInstance("TLS");
          ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
          socketFactory = ctx.getSocketFactory();
        } catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
    }

      public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }

      @Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
      @Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }

      @Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
        return socketFactory.createSocket(socket, string, i, bln);
      }
      @Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i);
      }
      @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i, ia, i1);
      }
      @Override public Socket createSocket(InetAddress ia, int i) throws IOException {
        return socketFactory.createSocket(ia, i);
      }
      @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
      }
}

class DummyTrustManager implements X509TrustManager {
    @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
        // do nothing
    }
    @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
        /*System.out.println("checkServerTrusted for authType: " + str); // RSA
        for(int idx=0; idx<xcs.length; idx++) {
            X509Certificate cert = xcs[idx];
            System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
        }*/
    }
    @Override public X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
}

What's NSLocalizedString equivalent in Swift?

Localization with default language:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

How to get a path to a resource in a Java JAR file

The following path worked for me: classpath:/path/to/resource/in/jar

How do I convert a column of text URLs into active hyperlinks in Excel?

This method works for me using the hyperlink function:

=HYPERLINK("http://"&B10,B10)

Where B10 is the cell containing the text version of the URL (in this example).

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Manually install Gradle and use it in Android Studio

in first step you should go to http://www.gradle.org/downloads and then choose your Gradle version and follow download link in GitHub and then download Gradle from GitHub. after your download is completed, you should extract the downloaded file in a directory (every directory that you want). finally open extracted folder and just run gradlew.bat and wait several minutes for completing download. and after completing download files, Gradle install itself automaticly. Gradle will work correctly for next times. i resolve this problem with this way and i tested it and every things are ok, so every one can test this way, it should working well. Good Luck.

no pg_hba.conf entry for host

For those who have the similar problem trying to connect to local db and trying like
con = psycopg2.connect(database="my_db", user="my_name", password="admin"), try to pass the additional parameter, so the following saved me a day:
con = psycopg2.connect(database="my_db", user="my_name", password="admin", host="localhost")

Disable scrolling in all mobile devices

html, body {
  overflow-x: hidden;
}
body {
  position: relative;
}

The position relative is important, and i just stumbled about it. Could not make it work without it.

How do you check if a selector matches something in jQuery?

For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}

S3 limit to objects in a bucket

"You can store as many objects as you want within a bucket, and write, read, and delete objects in your bucket. Objects can be up to 5 terabytes in size."

from http://aws.amazon.com/s3/details/ (as of Mar 4th 2015)

How to check if a string "StartsWith" another string?

var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
    return true;
else
    return false;

What is Hash and Range Primary Key?

A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.

In a simple words range + hash key = composite primary key CoreComponents of Dynamodb enter image description here

A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.

So both have a different purpose and together help to do complex query. In the above example hashkey1 can have multiple n-range. Another example of range and hashkey is game, userA(hashkey) can play Ngame(range)

enter image description here

The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.

A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.

enter image description here

https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

Don't worry. Just uninstall jdk as well as jdk updates Before re installing jdk ,delete the oracle folder inside programData hidden folder in C:\ Then reinstall. Set the following,

JAVA_HOME
CLASSPATH
PATH
JRE_HOME ( is optional)

SSRS Field Expression to change the background color of the Cell

The problem with IIF(Fields!column.Value = "Approved", "Green") is that you are missing the third parameter. The correct syntax is IIF( [some boolean expression], [result if boolean expression is true], [result if boolean is false])

Try this

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Here is a list of expression examples Expression Examples in Reporting Services

IIF in SSRS report

Call javascript from MVC controller action

If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt) So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:

void webBrowser1_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
    if(search != null)
    {
        search.SetAttribute("value", "Superman");
        foreach(HtmlElement ele in search.Parent.Children)
        {
            if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
            {
                ele.InvokeMember("click");
                break;
            }
        }
    }
}

So probably nowadays, that would not be the easiest solution.

The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.

Some related questions on this topic or possible duplicates:

Embedding JavaScript engine into .NET

Load a DOM and Execute javascript, server side, with .Net

Hope this helps.

How do you specify the Java compiler version in a pom.xml file?

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>(whatever version is current)</version>
        <configuration>
          <!-- or whatever version you use -->
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

See the config page for the maven compiler plugin:

http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

Oh, and: don't use Java 1.3.x, current versions are Java 1.7.x or 1.8.x

Set QLineEdit to accept only numbers

If you're using QT Creator 5.6 you can do that like this:

#include <QIntValidator>

ui->myLineEditName->setValidator( new QIntValidator);

I recomend you put that line after ui->setupUi(this);

I hope this helps.

Kill detached screen session

You can just go to the place where the screen session is housed and run:

 screen -ls

which results in

 There is a screen on:
         26727.pts-0.devxxx      (Attached)
 1 Socket in /tmp/uscreens/S-xxx. <------ this is where the session is.

And just remove it:

  1. cd /tmp/uscreens/S-xxx
  2. ls
  3. 26727.pts-0.devxxx
  4. rm 26727.pts-0.devxxx
  5. ls

The uscreens directory will not have the 26727.pts-0.devxxx file in it anymore. Now to make sure just type this:

screen -ls

and you should get:

No Sockets found in /tmp/uscreens/S-xxx.

What does -> mean in C++?

a->b means (*a).b.

If a is a pointer, a->b is the member b of which a points to.

a can also be a pointer like object (like a vector<bool>'s stub) override the operators.

(if you don't know what a pointer is, you have another question)

Java: How to stop thread?

We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().

public class Task1 implements Runnable {
    public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                       ................
                       ................
                       ................
                       ................
           }
    }
}

in main we will do like this:

Thread t1 = new Thread(new Task1());
t1.start();
t1.interrupt();

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

How can I disable a button in a jQuery dialog from a function?

you can simply add id to the button, it is not in the document, but it works.

$().dialog(buttons:[{id:'your button id'....}]);

then in your function just use the

$('#your button id') 

to disable it.

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How do I get HTTP Request body content in Laravel?

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

From the docs:

$this->call($method, $uri, $parameters, $files, $server, $content);

Python convert decimal to hex

In order to put the number in the correct order i modified your code to have a variable (s) for the output. This allows you to put the characters in the correct order.

s=""
def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        x =(n%16)
        if (x < 10):
            s=str(x)+s, 
        if (x == 10):
            s="A"+s,
        if (x == 11):
            s="B"+s,
        if (x == 12):
            s="C"+s,
        if (x == 13):
            s="D"+s,
        if (x == 14):
            s="E"+s,
        if (x == 15):
            s="F"+s,
        ChangeHex( n / 16 )        

NOTE: This was done in python 3.7.4 so it may not work for you.

Removing App ID from Developer Connection

As @AlexanderN pointed out, you can now delete App IDs.

  1. In your Member Center go to the Certificates, Identifiers & Profiles section.
  2. Go to Identifiers folder.
  3. Select the App ID you want to delete and click Settings
  4. Scroll down and click Delete.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

SELECT * 
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

How to render html with AngularJS templates

So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:

<html>
  <body ng-app="yourApp">
    <div class="span12">
      <div ng-view=""></div>
    </div>
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Then yourView.html could just be:

<div>
  <h1>{{ stuff.h1 }}</h1>
  <p>{{ stuff.content }}</p>
</div>

scripts.js could have your controller with data $scope'd to it.

angular.module('yourApp')
    .controller('YourCtrl', function ($scope) {
      $scope.stuff = {
        'h1':'Title',
        'content':"A paragraph..."
      };
    });

Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)

angular.module('yourApp', [])
.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/yourView.html',
      controller: 'YourCtrl'
    });
});

I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

ToolBar's name can easily be changed using

android:label="My Activity"

in your Manifest File. I just going through Manifest & found

android:label 

Helps to change according to the specific activity, Hope you'll give it a try

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

How to sort an array of objects by multiple fields?

This is a complete cheat but I think that it adds value to this question because it's basically a canned library function that you can use out-of-the box.

If your code has access to lodash or a lodash compatible library like underscore then you can use the _.sortBy method. The snippet below is copied directly from the lodash documentation.

The commented results in the examples looks like they return arrays of arrays but that's just showing the order and not the actual results which are an array of objects.

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, [function(o) { return o.user; }]);
 // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]

_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]

sendUserActionEvent() is null

It is an error on all Samsung devices, the solution is: put this line in your activity declaration in Manifest.

android:configChanges="orientation|screenSize"

also when you start the activity you should do this:

Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.setType(Settings.ACTION_SYNC_SETTINGS);
CurrentActivity.this.startActivity(intent);
finish();

I used this to make an activity as fullscreen mode, but this question does not need the fullscreen code, but in all cases might someone need it you can refer to this question for the rest of the code:

How to make VideoView full screen

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

Get length of array?

Try CountA:

Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount

Share data between html pages

why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.

To store values for a session:

sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

or more permanently:

localStorage.getItem('label')
localStorage.setItem('label', 'value')

So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

In my Case: I have put the correct path for Android and java but still getting the error.

The problem was that I have added the Android platform using sudo command.sudo ionic cordova platform android.

To solve my problem: First I have removed the platform android by running command

sudo ionic cordova platform rm android

then add the android platform again with out sudoionic cordova platform add android but i get the error of permissions.

To resolve the error run command

sudo chmod -R 777 {Path-of-your-project}

in my case sudo chmod -R 777 ~/codebase/IonicProject Then run command

ionic cordova platform add android

or

ionic cordova run android

python, sort descending dataframe with pandas

For pandas 0.17 and above, use this :

test = df.sort_values('one', ascending=False)

Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.

Length of array in function argument

length of an array(type int) with sizeof: sizeof(array)/sizeof(int)

How to print the full NumPy array, without truncation?

You can use the array2string function - docs.

a = numpy.arange(10000).reshape(250,40)
print(numpy.array2string(a, threshold=numpy.nan, max_line_width=numpy.nan))
# [Big output]

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

Select Tomcat server in Targeted Runtime

Project->Properties->Targeted Runtimes (Select your Tomcat Server)

Visual Studio loading symbols

You can try the following answer to Visual Studio debugging/loading very slow:

  1. Go to Tools -> Options -> Debugging -> General

  2. CHECK the checkmark next to "Enable Just My Code".

  3. Go to Tools -> Options -> Debugging -> Symbols

  4. Click on the "..." button and create/select a new folder somewhere on your local computer to store cached symbols. I named mine "Symbol caching" and put it in Documents -> Visual Studio 2012.

  5. Click on "Load all symbols" and wait for the symbols to be downloaded from Microsoft's servers, which may take a while. Note that Load all symbols button is only available while debugging.

  6. UNCHECK the checkmark next to "Microsoft Symbol Servers" to prevent Visual Studio from remotely querying the Microsoft servers.

  7. Click "OK".

Also try to delete all the breakpoints(Debug>Delete all the breakpoints),

See Also: Visual Studio 2015 RC1 Hangs in Debug mode while loading symbols

how to open .mat file without using MATLAB?

A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.

git returns http error 407 from proxy after CONNECT

This config works in my setup:

[http]
    proxy = <your proxy>
[https] proxy = <your proxy>
[http]
    sslVerify = false
[https]
    sslVerify = false   
[credential]
    helper = wincred 

How to insert an item into an array at a specific index (JavaScript)?

I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you, it's called splice...

Let's see what's splice()...

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

OK, imagine we have this array below:

const arr = [1, 2, 3, 4, 5];

We can remove 3 like this:

arr.splice(arr.indexOf(3), 1);

It will return 3, but if we check the arr now, we have:

[1, 2, 4, 5]

So far, so good, but how we can add a new element to array using splice? Let's put back 3 in the arr...

arr.splice(2, 0, 3);

Let's see what we have done...

We use splice again, but this time for the second argument, we pass 0, means we want to delete no item, but at the same time, we add third argument which is 3 that will be added at second index...

You should be aware, that we can delete and add at the same time, for example now we can do:

arr.splice(2, 2, 3);

Which will delete 2 items at index 2, then add 3 at index 2 and result will be:

[1, 2, 3, 5];

This is showing how each item in splice work:

array.splice(start, deleteCount, item1, item2, item3 ...)

How do I do pagination in ASP.NET MVC?

I think the easiest way to create pagination in ASP.NET MVC application is using PagedList library.

There is a complete example in following github repository. Hope it would help.

public class ProductController : Controller
{
    public object Index(int? page)
    {
        var list = ItemDB.GetListOfItems();

        var pageNumber = page ?? 1; 
        var onePageOfItem = list.ToPagedList(pageNumber, 25); // will only contain 25 items max because of the pageSize

        ViewBag.onePageOfItem = onePageOfProducts;
        return View();
    }
}

Demo Link: http://ajaxpagination.azurewebsites.net/

Source Code: https://github.com/ungleng/SimpleAjaxPagedListAndSearchMVC5

How to load image files with webpack file-loader

This is my working example of our simple Vue component.

<template functional>
    <div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>

How to connect to Oracle 11g database remotely

First. It is necessary add static IP address for Computer A AND B. For example in my case Computer A (172.20.14.13) and B (172.20.14.78).

Second. In Computer A with Net Manager add for Listener new address (172.20.14.13) or manually add new record in listener.ora

# listener.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = E:\app\user\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app\user\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
  )

ADR_BASE_LISTENER = E:\app\user

Third. With Net Manager create Service Naming with IP address computer B (172.20.14.78) or manually add new record in tnsnames.ora

# tnsnames.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.

ALINADB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

LISTENER_ALINADB =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))


LOCAL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

ORCL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.78)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

Fourth. In computer B (172.20.14.78) install win64_11gR2_client (For example it is for me in Windows 10 Pro 64 bit )

Five. Create with Net Configuration Assistant listener (localhost) or manually add record in listener.ora

# listener.ora Network Configuration File: F:\app\alinasoft\product\11.2.0\client_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = TCP)(HOST = myserver)(PORT = 1521))
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
        )
      )

    ADR_BASE_LISTENER = F:\app\alinasoft

Six. With Net Manager create Service Naming with IP address computer A (172.20.14.13) or manually add new record in tnsnames.ora.

SERVER-DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

Seven (Computer A - (172.20.14.13)) for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image) Oracle_home\bin\oracle.exe - Oracle Database executable Oracle_home\bin\tnslsnr.exe - Oracle Listener

Eight Allow connections for port 1158 (Computer A - (172.20.14.13)) for Oracle Enterprise Manager (https://172.20.14.13:1158/em/console/logon/logon)

Ninth Allow connections for port 1521 ( in and out) (Computer A - (172.20.14.17))

Tenth In computer B 172.20.14.78 sqlplus /NOLOG CONNECT system/oracle@//172.20.14.13:1521/alinadb

If uses Toad, in my case is enter image description here

HTML Table different number of columns in different rows

On the realisation that you're unfamiliar with colspan, I presumed you're also unfamiliar with rowspan, so I thought I'd throw that in for free.

One important point to note, when using rowspan: the following tr elements must contain fewer td elements, because of the cells using rowspan in the previous row (or previous rows).

_x000D_
_x000D_
table {_x000D_
  border: 1px solid #000;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th colspan="2">Column one and two</th>_x000D_
      <th>Column three</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td rowspan="2" colspan="2">A large cell</td>_x000D_
      <td>a smaller cell</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <!-- note that this row only has _one_ td, since the preceding row_x000D_
                     takes up some of this row -->_x000D_
      <td>Another small cell</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Sort tuples based on second parameter

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1])

or, slightly faster,

my_list.sort(key=operator.itemgetter(1))

(As with any module, you'll need to import operator to be able to use it.)

Retrieve the maximum length of a VARCHAR column in SQL Server

Use the built-in functions for length and max on the description column:

SELECT MAX(LEN(DESC)) FROM table_name;

Note that if your table is very large, there can be performance issues.

How to get the instance id from within an ec2 instance?

Just Type:

ec2metadata --instance-id

How to open a new tab in GNOME Terminal from command line?

#!/bin/sh

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID

This will auto determine the corresponding terminal and opens the tab accordingly.

Convert .pfx to .cer

I wanted to add a method which I think was simplest of all.

  1. Simply right click the pfx file, click "Install" follow the wizard, and add it to a store (I added to the Personal store).

  2. In start menu type certmgr.msc and go to CertManager program.

  3. Find your pfx certificate (tabs at top are the various stores), click the export button and follow the wizard (there is an option to export as .CER)

Essentially it does the same thing as Andrew's answer, but it avoids using Windows Management Console (goes straight to the import/export).

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

The chart seem to be async so you will probably need to provide a callback when the animation has finished or else the canvas will be empty.

var options = {
    bezierCurve : false,
    onAnimationComplete: done  /// calls function done() {} at end
};

delete a column with awk or sed

This might work for you (GNU sed):

sed -i -r 's/\S+//3' file

If you want to delete the white space before the 3rd field:

sed -i -r 's/(\s+)?\S+//3' file

Jquery $.ajax fails in IE on cross domain calls

I had a similar problem in IE9 where some CORS calls were aborting, while others weren't. My app is also dependent on a promise interface, so the XDomainRequest suggestions above weren't EXACTLY what I needed, so I added a deferred into my service.get workaround for IE9. Hopefully it can be useful to someone else running across this problem. :

    get: function (url) {
        if ('XDomainRequest' in window && window.XDomainRequest !== null) {
            var deferred = $.Deferred();
            var xdr      = new XDomainRequest();

            xdr.open("get", url);

            xdr.onload = function() {
              json = xdr.responseText;
              parsed_json = $.parseJSON(json);
              deferred.resolve(parsed_json);
            }

            xdr.send();
            return deferred;
        } else {
            return $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                crossDomain: true
            });
        }
    }

Sort objects in ArrayList by date?

Pass the ArrayList In argument.

    private static void order(ArrayList<Object> list) {

    Collections.sort(list, new Comparator() {

        public int compare(Object o2, Object o1) {

            String x1 =  o1.Date;
            String x2 =  o2.Date;

                return  x1.compareTo(x2);

        }
    });
}

How to set a Default Route (To an Area) in MVC

This one interested me, and I finally had a chance to look into it. Other folks apparently haven't understood that this is an issue with finding the view, not an issue with the routing itself - and that's probably because your question title indicates that it's about routing.

In any case, because this is a View-related issue, the only way to get what you want is to override the default view engine. Normally, when you do this, it's for the simple purpose of switching your view engine (i.e. to Spark, NHaml, etc.). In this case, it's not the View-creation logic we need to override, but the FindPartialView and FindView methods in the VirtualPathProviderViewEngine class.

You can thank your lucky stars that these methods are in fact virtual, because everything else in the VirtualPathProviderViewEngine is not even accessible - it's private, and that makes it very annoying to override the find logic because you have to basically rewrite half of the code that's already been written if you want it to play nice with the location cache and the location formats. After some digging in Reflector I finally managed to come up with a working solution.

What I've done here is to first create an abstract AreaAwareViewEngine that derives directly from VirtualPathProviderViewEngine instead of WebFormViewEngine. I did this so that if you want to create Spark views instead (or whatever), you can still use this class as the base type.

The code below is pretty long-winded, so to give you a quick summary of what it actually does: It lets you put a {2} into the location format, which corresponds to the area name, the same way {1} corresponds to the controller name. That's it! That's what we had to write all this code for:

BaseAreaAwareViewEngine.cs

public abstract class BaseAreaAwareViewEngine : VirtualPathProviderViewEngine
{
    private static readonly string[] EmptyLocations = { };

    public override ViewEngineResult FindView(
        ControllerContext controllerContext, string viewName,
        string masterName, bool useCache)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }
        if (string.IsNullOrEmpty(viewName))
        {
            throw new ArgumentNullException(viewName,
                "Value cannot be null or empty.");
        }

        string area = getArea(controllerContext);
        return FindAreaView(controllerContext, area, viewName,
            masterName, useCache);
    }

    public override ViewEngineResult FindPartialView(
        ControllerContext controllerContext, string partialViewName,
        bool useCache)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }
        if (string.IsNullOrEmpty(partialViewName))
        {
            throw new ArgumentNullException(partialViewName,
                "Value cannot be null or empty.");
        }

        string area = getArea(controllerContext);
        return FindAreaPartialView(controllerContext, area,
            partialViewName, useCache);
    }

    protected virtual ViewEngineResult FindAreaView(
        ControllerContext controllerContext, string areaName, string viewName,
        string masterName, bool useCache)
    {
        string controllerName =
            controllerContext.RouteData.GetRequiredString("controller");
        string[] searchedViewPaths;
        string viewPath = GetPath(controllerContext, ViewLocationFormats,
            "ViewLocationFormats", viewName, controllerName, areaName, "View",
            useCache, out searchedViewPaths);
        string[] searchedMasterPaths;
        string masterPath = GetPath(controllerContext, MasterLocationFormats,
            "MasterLocationFormats", masterName, controllerName, areaName,
            "Master", useCache, out searchedMasterPaths);
        if (!string.IsNullOrEmpty(viewPath) &&
            (!string.IsNullOrEmpty(masterPath) || 
              string.IsNullOrEmpty(masterName)))
        {
            return new ViewEngineResult(CreateView(controllerContext, viewPath,
                masterPath), this);
        }
        return new ViewEngineResult(
            searchedViewPaths.Union<string>(searchedMasterPaths));
    }

    protected virtual ViewEngineResult FindAreaPartialView(
        ControllerContext controllerContext, string areaName,
        string viewName, bool useCache)
    {
        string controllerName =
            controllerContext.RouteData.GetRequiredString("controller");
        string[] searchedViewPaths;
        string partialViewPath = GetPath(controllerContext,
            ViewLocationFormats, "PartialViewLocationFormats", viewName,
            controllerName, areaName, "Partial", useCache,
            out searchedViewPaths);
        if (!string.IsNullOrEmpty(partialViewPath))
        {
            return new ViewEngineResult(CreatePartialView(controllerContext,
                partialViewPath), this);
        }
        return new ViewEngineResult(searchedViewPaths);
    }

    protected string CreateCacheKey(string prefix, string name,
        string controller, string area)
    {
        return string.Format(CultureInfo.InvariantCulture,
            ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:",
            base.GetType().AssemblyQualifiedName,
            prefix, name, controller, area);
    }

    protected string GetPath(ControllerContext controllerContext,
        string[] locations, string locationsPropertyName, string name,
        string controllerName, string areaName, string cacheKeyPrefix,
        bool useCache, out string[] searchedLocations)
    {
        searchedLocations = EmptyLocations;
        if (string.IsNullOrEmpty(name))
        {
            return string.Empty;
        }
        if ((locations == null) || (locations.Length == 0))
        {
            throw new InvalidOperationException(string.Format("The property " +
                "'{0}' cannot be null or empty.", locationsPropertyName));
        }
        bool isSpecificPath = IsSpecificPath(name);
        string key = CreateCacheKey(cacheKeyPrefix, name,
            isSpecificPath ? string.Empty : controllerName,
            isSpecificPath ? string.Empty : areaName);
        if (useCache)
        {
            string viewLocation = ViewLocationCache.GetViewLocation(
                controllerContext.HttpContext, key);
            if (viewLocation != null)
            {
                return viewLocation;
            }
        }
        if (!isSpecificPath)
        {
            return GetPathFromGeneralName(controllerContext, locations, name,
                controllerName, areaName, key, ref searchedLocations);
        }
        return GetPathFromSpecificName(controllerContext, name, key,
            ref searchedLocations);
    }

    protected string GetPathFromGeneralName(ControllerContext controllerContext,
        string[] locations, string name, string controllerName,
        string areaName, string cacheKey, ref string[] searchedLocations)
    {
        string virtualPath = string.Empty;
        searchedLocations = new string[locations.Length];
        for (int i = 0; i < locations.Length; i++)
        {
            if (string.IsNullOrEmpty(areaName) && locations[i].Contains("{2}"))
            {
                continue;
            }
            string testPath = string.Format(CultureInfo.InvariantCulture,
                locations[i], name, controllerName, areaName);
            if (FileExists(controllerContext, testPath))
            {
                searchedLocations = EmptyLocations;
                virtualPath = testPath;
                ViewLocationCache.InsertViewLocation(
                    controllerContext.HttpContext, cacheKey, virtualPath);
                return virtualPath;
            }
            searchedLocations[i] = testPath;
        }
        return virtualPath;
    }

    protected string GetPathFromSpecificName(
        ControllerContext controllerContext, string name, string cacheKey,
        ref string[] searchedLocations)
    {
        string virtualPath = name;
        if (!FileExists(controllerContext, name))
        {
            virtualPath = string.Empty;
            searchedLocations = new string[] { name };
        }
        ViewLocationCache.InsertViewLocation(controllerContext.HttpContext,
            cacheKey, virtualPath);
        return virtualPath;
    }


    protected string getArea(ControllerContext controllerContext)
    {
        // First try to get area from a RouteValue override, like one specified in the Defaults arg to a Route.
        object areaO;
        controllerContext.RouteData.Values.TryGetValue("area", out areaO);

        // If not specified, try to get it from the Controller's namespace
        if (areaO != null)
            return (string)areaO;

        string namespa = controllerContext.Controller.GetType().Namespace;
        int areaStart = namespa.IndexOf("Areas.");
        if (areaStart == -1)
            return null;

        areaStart += 6;
        int areaEnd = namespa.IndexOf('.', areaStart + 1);
        string area = namespa.Substring(areaStart, areaEnd - areaStart);
        return area;
    }

    protected static bool IsSpecificPath(string name)
    {
        char ch = name[0];
        if (ch != '~')
        {
            return (ch == '/');
        }
        return true;
    }
}

Now as stated, this isn't a concrete engine, so you have to create that as well. This part, fortunately, is much easier, all we need to do is set the default formats and actually create the views:

AreaAwareViewEngine.cs

public class AreaAwareViewEngine : BaseAreaAwareViewEngine
{
    public AreaAwareViewEngine()
    {
        MasterLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.master",
            "~/Areas/{2}/Views/{1}/{0}.cshtml",
            "~/Areas/{2}/Views/Shared/{0}.master",
            "~/Areas/{2}/Views/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.master",
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.master"
            "~/Views/Shared/{0}.cshtml"
        };
        ViewLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.aspx",
            "~/Areas/{2}/Views/{1}/{0}.ascx",
            "~/Areas/{2}/Views/{1}/{0}.cshtml",
            "~/Areas/{2}/Views/Shared/{0}.aspx",
            "~/Areas/{2}/Views/Shared/{0}.ascx",
            "~/Areas/{2}/Views/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.aspx",
            "~/Views/{1}/{0}.ascx",
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.aspx"
            "~/Views/Shared/{0}.ascx"
            "~/Views/Shared/{0}.cshtml"
        };
        PartialViewLocationFormats = ViewLocationFormats;
    }

    protected override IView CreatePartialView(
        ControllerContext controllerContext, string partialPath)
    {
        if (partialPath.EndsWith(".cshtml"))
            return new System.Web.Mvc.RazorView(controllerContext, partialPath, null, false, null);
        else
            return new WebFormView(controllerContext, partialPath);
    }

    protected override IView CreateView(ControllerContext controllerContext,
        string viewPath, string masterPath)
    {
        if (viewPath.EndsWith(".cshtml"))
            return new RazorView(controllerContext, viewPath, masterPath, false, null);
        else
            return new WebFormView(controllerContext, viewPath, masterPath);
    }
}

Note that we've added few entries to the standard ViewLocationFormats. These are the new {2} entries, where the {2} will be mapped to the area we put in the RouteData. I've left the MasterLocationFormats alone, but obviously you can change that if you want.

Now modify your global.asax to register this view engine:

Global.asax.cs

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new AreaAwareViewEngine());
}

...and register the default route:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Area",
        "",
        new { area = "AreaZ", controller = "Default", action = "ActionY" }
    );
    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = "" }
    );
}

Now Create the AreaController we just referenced:

DefaultController.cs (in ~/Controllers/)

public class DefaultController : Controller
{
    public ActionResult ActionY()
    {
        return View("TestView");
    }
}

Obviously we need the directory structure and view to go with it - we'll keep this super simple:

TestView.aspx (in ~/Areas/AreaZ/Views/Default/ or ~/Areas/AreaZ/Views/Shared/)

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<h2>TestView</h2>
This is a test view in AreaZ.

And that's it. Finally, we're done.

For the most part, you should be able to just take the BaseAreaAwareViewEngine and AreaAwareViewEngine and drop it into any MVC project, so even though it took a lot of code to get this done, you only have to write it once. After that, it's just a matter of editing a few lines in global.asax.cs and creating your site structure.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

For Java 7 you can simply omit the Class.forName() statement as it is not really required.

For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see

Manipulating an Access database from Java without ODBC

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

How to fully delete a git repository created with init?

If you really want to remove all of the repository, leaving only the working directory then it should be as simple as this.

rm -rf .git

The usual provisos about rm -rf apply. Make sure you have an up to date backup and are absolutely sure that you're in the right place before running the command. etc., etc.

Clearing Magento Log Data

Further hint: If you don't need those information you can change the Table Type to "Blackhole" (instead of InnoDB). This means, nothing will be stored in the future and the insert statements are still working fine.

You can also disable the logs by setting all events to disabled:

https://gist.github.com/tegansnyder/189f1c3ce897b4ab494d

How to retrieve checkboxes values in jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

How to change the ROOT application?

You can do this in a slightly hack-y way by:

  1. Stop Tomcat
  2. Move ROOT.war aside and rm -rf webapps/ROOT
  3. Copy the webapp you want to webapps/ROOT.war
  4. Start Tomcat

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

add a as follows:

<a href="http://foo.com" onclick="return false;">....</a>

or return false; from click handler for #clickable like:

  $("#clickable").click(function() {
        var url = $("#clickable a").attr("href");
        window.location = url;
        return false;
   });

clear form values after submission ajax

$('#formid).reset();

or

document.getElementById('formid').reset();

How do you round UP a number in Python?

For those who doesn't want to use import.

For a given list or any number:

x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]

You must first evaluate if the number is equal to its integer, which always rounds down. If the result is True, you return the number, if is not, return the integer(number) + 1.

w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]

Math logic:

  • If the number has decimal part: round_up - round_down == 1, always.
  • If the number doens't have decimal part: round_up - round_down == 0.

So:

  • round_up == x + round_down

With:

  • x == 1 if number != round_down
  • x == 0 if number == round_down

You are cutting the number in 2 parts, the integer and decimal. If decimal isn't 0, you add 1.

PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment.

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

Can regular expressions be used to match nested patterns?

YES

...assuming that there is some maximum number of nestings you'd be happy to stop at.

Let me explain.


@torsten-marek is right that a regular expression cannot check for nested patterns like this, BUT it is possible to define a nested regex pattern which will allow you to capture nested structures like this up to some maximum depth. I created one to capture EBNF-style comments (try it out here), like:

(* This is a comment (* this is nested inside (* another level! *) hey *) yo *)

The regex (for single-depth comments) is the following:

m{1} = \(+\*+(?:[^*(]|(?:\*+[^)*])|(?:\(+[^*(]))*\*+\)+

This could easily be adapted for your purposes by replacing the \(+\*+ and \*+\)+ with { and } and replacing everything in between with a simple [^{}]:

p{1} = \{(?:[^{}])*\}

(Here's the link to try that out.)

To nest, just allow this pattern within the block itself:

p{2} = \{(?:(?:p{1})|(?:[^{}]))*\}
  ...or...
p{2} = \{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\}

To find triple-nested blocks, use:

p{3} = \{(?:(?:p{2})|(?:[^{}]))*\}
  ...or...
p{3} = \{(?:(?:\{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\})|(?:[^{}]))*\}

A clear pattern has emerged. To find comments nested to a depth of N, simply use the regex:

p{N} = \{(?:(?:p{N-1})|(?:[^{}]))*\}

  where N > 1 and
  p{1} = \{(?:[^{}])*\}

A script could be written to recursively generate these regexes, but that's beyond the scope of what I need this for. (This is left as an exercise for the reader. )

AngularJS custom filter function

Additionally, if you want to use the filter in your controller the same way you do it here:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

You could do something like:

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

convert htaccess to nginx

Online tools to translate Apache .htaccess to Nginx rewrite tools include:

Note that these tools will convert to equivalent rewrite expressions using if statements, but they should be converted to try_files. See:

Reading Data From Database and storing in Array List object

try this

import java.sql.ResultSet;
import java.util.ArrayList;

import com.rcb.dbconnection.DbConnection;
import com.rcb.model.Docter;


public class DocterService {



public ArrayList<Docter> getAllDocters() {
    ArrayList<Docter> docters = new ArrayList<Docter>();

    try {
        String sql = "SELECT tbl_docters";

        ResultSet rs = db.getData(sql);
        while (rs.next()) {
            Docter docter = new Docter();

            docter.setD_id(rs.getInt("d_id"));
            docter.setD_FName(rs.getString("d_fname"));
            docter.setD_LName(rs.getString("d_lname"));

            docters.add(docter);

        }

    } catch (Exception e) {
        System.out.println("getAllDocters()");
        e.printStackTrace();
    }

    return (docters);
}

public static void main(String args[]) {
    DocterService ds = new DocterService();
    ArrayList<Docter> doctersList = ds.getAllDocters();
    String s[] = null;
    for (int i = 0; i < doctersList.size(); i++) {

        System.out.println(doctersList.get(i).getD_id());
        System.out.println(doctersList.get(i).getD_FName());
    }

  }
}

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.

Ignore case in Python strings

The recommended idiom to sort lists of values using expensive-to-compute keys is to the so-called "decorated pattern". It consists simply in building a list of (key, value) tuples from the original list, and sort that list. Then it is trivial to eliminate the keys and get the list of sorted values:

>>> original_list = ['a', 'b', 'A', 'B']
>>> decorated = [(s.lower(), s) for s in original_list]
>>> decorated.sort()
>>> sorted_list = [s[1] for s in decorated]
>>> sorted_list
['A', 'a', 'B', 'b']

Or if you like one-liners:

>>> sorted_list = [s[1] for s in sorted((s.lower(), s) for s in original_list)]
>>> sorted_list
['A', 'a', 'B', 'b']

If you really worry about the cost of calling lower(), you can just store tuples of (lowered string, original string) everywhere. Tuples are the cheapest kind of containers in Python, they are also hashable so they can be used as dictionary keys, set members, etc.

any tool for java object to object mapping?

There is one more Java mapping engine/framework Nomin: http://nomin.sourceforge.net.

CORS with POSTMAN

As @Musa comments it, it seems that the reason is that:

Postman doesn't care about SOP, it's a dev tool not a browser

By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).

Check here if you want to learn more about Cross-Origin and why it's working for extensions.

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

Differences between MySQL and SQL Server

I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / "with" statements. It's a pretty annoying difference.

'Incorrect SET Options' Error When Building Database Project

I found the solution for this problem:

  1. Go to the Server Properties.
  2. Select the Connections tab.
  3. Check if the ansi_padding option is unchecked.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Passing two command parameters using a WPF binding

In the converter of the chosen solution, you should add values.Clone() otherwise the parameters in the command end null

public class YourConverter : IMultiValueConverter
{
    public object Convert(object[] values, ...)
    {
        return values.Clone();
    }

    ...
}