Programs & Examples On #Internet connection

Anything related to the hardware, software tools and techniques needed to establish and manage an Internet connection.

Check if Internet Connection Exists with jQuery?

The best option for your specific case might be:

Right before your close </body> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

This is probably the easiest way given that your issue is centered around jQuery.

If you wanted a more robust solution you could try:

var online = navigator.onLine;

Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.

Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.

I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.

What does it mean to be "online"?

There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.

To determine if a host is reachable from your network, you could do this:

function hostReachable() {

  // Handle IE and more capable browsers
  var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );

  // Open new request as a HEAD to the root hostname with a random param to bust the cache
  xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );

  // Issue request and handle response
  try {
    xhr.send();
    return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
  } catch (error) {
    return false;
  }

}

You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579

Details on local implementation

Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.

Detect if Android device has Internet connection

You can do this with very simple class.

class CheckInternet {
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    }
}

Now you can check this from any class.

if (CheckInternet().isNetworkAvailable(this)) {
  //connected with internet
}else{
  //Not connected with internet
}

What is the best way to check for Internet connectivity using .NET?

private bool ping()
{
    System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
    System.Net.NetworkInformation.PingReply reply = pingSender.Send(address);
    if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
    {                
        return true;
    }
    else
    {                
        return false;
    }
}

Detect the Internet connection is offline?

The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.

Here is my code:

 var xhr = new XMLHttpRequest();
 //index.php is in my web
 xhr.open('HEAD', 'index.php', true);
 xhr.send();

 xhr.addEventListener("readystatechange", processRequest, false);

 function processRequest(e) {
     if (xhr.readyState == 4) {
         //If you use a cache storage manager (service worker), it is likely that the
         //index.php file will be available even without internet, so do the following validation
         if (xhr.status >= 200 && xhr.status < 304) {
             console.log('On line!');
         } else {
             console.log('Offline :(');
         }
     }
}

How to check currently internet connection is available or not in android

  public  boolean isInternetConnection()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            //we are connected to a network
            return  true;
        }
        else {
            return false;
        }
    }

Easiest way to detect Internet connection on iOS?

Sorry for replying too late but I hope this answer can help somebody in future.

Following is a small native C code snippet that can check internet connectivity without any extra class.

Add the following headers:

#include<unistd.h>
#include<netdb.h>

Code:

-(BOOL)isNetworkAvailable
{
    char *hostname;
    struct hostent *hostinfo;
    hostname = "google.com";
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL){
        NSLog(@"-> no connection!\n");
        return NO;
    }
    else{
        NSLog(@"-> connection established!\n");
        return YES;
    }
}

Swift 3

func isConnectedToInternet() -> Bool {
    let hostname = "google.com"
    //let hostinfo = gethostbyname(hostname)
    let hostinfo = gethostbyname2(hostname, AF_INET6)//AF_INET6
    if hostinfo != nil {
        return true // internet available
      }
     return false // no internet
    }

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...

How do I sleep for a millisecond in Perl?

system "sleep 0.1";

does the trick.

What is the difference between 'java', 'javaw', and 'javaws'?

java: Java application executor which is associated with a console to display output/errors

javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.

javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.

All are part of JRE and use the same JVM.

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

What is the mouse down selector in CSS?

I think you mean the active state

 button:active{
  //some styling
 }

These are all the possible pseudo states a link can have in CSS:

a:link {color:#FF0000;}    /* unvisited link, same as regular 'a' */
a:hover {color:#FF00FF;}   /* mouse over link */
a:focus {color:#0000FF;}   /* link has focus */
a:active {color:#0000FF;}  /* selected link */
a:visited {color:#00FF00;} /* visited link */

See also: http://www.w3.org/TR/selectors/#the-user-action-pseudo-classes-hover-act

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

Android, landscape only orientation?

One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available! So android:screenOrientation="landscape" will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:

android:screenOrientation="sensorLandscape"

How to connect to a MySQL Data Source in Visual Studio

  1. Download MySQL Connector .NET (6.9.4 on this date) from here and install it CUSTOM!
  2. Remove the ASP.NET WEB providers option or the installer will write in machine.config!
  3. Download MySQL for Visual Studio from here and install it CUSTOM. Be sure to check the integration options. You need this step because after Connector .NET 6.7 the installer will no longer integrate the connector with Visual Studio. This installer can take longer then expected. This is it.

You can install it from alternate download here which should have integrated with VS correctly but it did not and I got a strange error and after the reinstall it is ok.

How to Fill an array from user input C#?

C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

using Microsoft.VisualBasic;

You can do the following:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

Import CSV to mysql table

Here's a simple PHP command line script that will do what you need:

<?php

$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'database';

$db = mysql_connect($host, $user, $pass);
mysql_query("use $database", $db);

/********************************************************************************/
// Parameters: filename.csv table_name

$argv = $_SERVER[argv];

if($argv[1]) { $file = $argv[1]; }
else {
    echo "Please provide a file name\n"; exit; 
}
if($argv[2]) { $table = $argv[2]; }
else {
    $table = pathinfo($file);
    $table = $table['filename'];
}

/********************************************************************************/
// Get the first row to create the column headings

$fp = fopen($file, 'r');
$frow = fgetcsv($fp);

foreach($frow as $column) {
    if($columns) $columns .= ', ';
    $columns .= "`$column` varchar(250)";
}

$create = "create table if not exists $table ($columns);";
mysql_query($create, $db);

/********************************************************************************/
// Import the data into the newly created table.

$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
mysql_query($q, $db);

?>

It will create a table based on the first row and import the remaining rows into it. Here is the command line syntax:

php csv_import.php csv_file.csv table_name

java.io.IOException: Server returned HTTP response code: 500

Change the content-type to "application/x-www-form-urlencoded", i solved the problem.

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Difference between F5, Ctrl + F5 and click on refresh button?

F5 is a standard page reload.

and

Ctrl + F5 refreshes the page by clearing the cached content of the page.

Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

ModuleNotFoundError: No module named 'sklearn'

Cause

Conda and pip install scikit-learn under ~/anaconda3/envs/$ENV/lib/python3.7/site-packages, however Jupyter notebook looks for the package under ~/anaconda3/lib/python3.7/site-packages.

Therefore, even when the environment is specified to conda, it does not work.

conda install -n $ENV scikit-learn # Does not work

Solution

pip 3 install the package under ~/anaconda3/lib/python3.7/site-packages.

Verify

After pip3, in a Jupyter notebook.

import sklearn
sklearn.__file__

~/anaconda3/lib/python3.7/site-packages/sklearn/init.py'

jQuery select change show/hide div event

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value Also change the values... as per your parameters

React - How to get parameter value from query string?

React Router v3

With React Router v3, you can get query-string from this.props.location.search (?qs1=naisarg&qs2=parmar). For example, with let params = queryString.parse(this.props.location.search), would give { qs1 : 'naisarg', qs2 : 'parmar'}

React Router v4

With React Router v4, the this.props.location.query does not exist anymore. You need to use this.props.location.search instead and parse the query parameters either by yourself or using an existing package such as query-string.

Example

Here is a minimal example using React Router v4 and the query-string library.

import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
    
class ActivateAccount extends Component{
    someFunction(){
        let params = queryString.parse(this.props.location.search)
        ...
    }
    ...
}
export default withRouter(ActivateAccount);

Rational

The React Router's team rational for removing the query property is:

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

[...]

The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.

You can find the full discussion on GitHub.

How can I make directory writable?

To make the parent directory as well as all other sub-directories writable, just add -R

chmod -R a+w <directory>

Can HTML checkboxes be set to readonly?

No, but you might be able to use javascript events to achieve something similar

No process is on the other end of the pipe (SQL Server 2012)

Had this error too, the cause was simple, but not obvious: incorrect password. Not sure why I didn't get just "Login failed" from freshly installed SQL 2016 server.

SQL Server - Return value after INSERT

Entity Framework performs something similar to gbn's answer:

DECLARE @generated_keys table([Id] uniqueidentifier)

INSERT INTO Customers(FirstName)
OUTPUT inserted.CustomerID INTO @generated_keys
VALUES('bob');

SELECT t.[CustomerID]
FROM @generated_keys AS g 
   JOIN dbo.Customers AS t 
   ON g.Id = t.CustomerID
WHERE @@ROWCOUNT > 0

The output results are stored in a temporary table variable, and then selected back to the client. Have to be aware of the gotcha:

inserts can generate more than one row, so the variable can hold more than one row, so you can be returned more than one ID

I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).

But that's what EF does.

SQL Server 2008 or newer only. If it's 2005 then you're out of luck.

CSS Float: Floating an image to the left of the text

I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)

.post-container {
 margin: 20px 20px 0 0;
 border:5px solid #333;
}
.post-thumb img {
 float: left;
}
.post-content {
 overflow:hidden;
}

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

Custom events in jQuery?

It is an old post, but I will try to update it with a new information.

To use custom events you need to bind it to some DOM element and to trigger it. So you need to use

.on() method takes an event type and an event handling function as arguments. Optionally, it can also receive event-related data as its second argument, pushing the event handling function to the third argument. Any data that is passed will be available to the event handling function in the data property of the event object. The event handling function always receives the event object as its first argument.

and

.trigger() method takes an event type as its argument. Optionally, it can also take an array of values. These values will be passed to the event handling function as arguments after the event object.

The code looks like this:

$(document).on("getMsg", {
    msg: "Hello to everyone",
    time: new Date()
}, function(e, param) {
    console.log( e.data.msg );
    console.log( e.data.time );
    console.log( param );
});

$( document ).trigger("getMsg", [ "Hello guys"] );

Nice explanation can be found here and here. Why exactly this can be useful? I found how to use it in this excellent explanation from twitter engineer.

P.S. In plain javascript you can do this with new CustomEvent, but beware of IE and Safari problems.

How to check if field is null or empty in MySQL?

Alternatively you can also use CASE for the same:

SELECT CASE WHEN field1 IS NULL OR field1 = '' 
       THEN 'empty' 
       ELSE field1 END AS field1
FROM tablename.

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Please try this

 useEffect(() => {
        (async () => {
          const products = await api.index()
          setFilteredProducts(products)
          setProducts(products)
        })()
      }, [])

show validation error messages on submit in angularjs

A complete solution to the validate form with angularjs.

HTML is as follows.

<div ng-app="areaApp" ng-controller="addCtrler">
        <form class="form-horizontal" name="fareainfo">
            <div class="form-group">
                  <label for="input-areaname" class="col-sm-2 control-label">Area Name : </label>
                  <div class="col-sm-4">
                      <input type="text" class="form-control" name="name" id="input-areaname" ng-model="Area.Name" placeholder="" required>
                      <span class="text-danger" ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"> Field is required</span>
                  </div>
            </div>
             <div class="col-sm-12">
                  <button type="button" class="btn btn-primary pull-right" ng-click="submitAreaInfo()">Submit</button>
             </div>
        </form>
    </div>

AngularJS App and Controller is as follows

var areaApp = angular.module('areaApp', []); 
areaApp.controller('addCtrler', function ($scope) {
    $scope.submitAreaInfo = function () {  
       if ($scope.fareainfo.$valid) {
         //after Form is Valid
       } else {
          $scope.fareainfo.$setSubmitted();
       }
    };
});

Important Code Segments

  1. ng-app="areaApp" ng-controller="addCtrler"
    Defines the angular app and controller

  2. ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"
    Above condition ensure that whenever a user first sees the form there's no any validation error on the screen and after a user does changes to the form it ensure that validation message show on the screen. .name. is the name attribute of the input element.

  3. $scope.fareainfo.$valid
    Above code, segment check whether the form is valid whenever a user submits the form.

  4. $scope.fareainfo.$setSubmitted();
    Above code, segment ensures that all validation messages are displayed on the screen whenever a user submits the form without doing anything.

Update Eclipse with Android development tools v. 23

After trying the approaches in other answers without success, I just installed a new bundle from http://developer.android.com/sdk/installing/index.html?pkg=adt and that worked fine.

Do the following:

  1. As you don't want to re-download all the platforms again, copy the existing one from /OLD_ANDROID_SDK_PATH/sdk/platforms to /NEW_ANDROID_SDK_PATH/sdk/platforms.
  2. When opening the new Eclipse from the recent downloaded bundle, make sure you reuse the previous 'workspace' folder. That will ensure that all your previous settings will be remembered.
  3. After opening the new Eclipse on the previous workspace, please check if the used Android SDK is pointing to the new one (Eclipse preferences -> Android). It might be pointing to the old one, as you've reused the previews workspace settings.

With these steps, you should't have to reconfigure everything, and you won't need to spend time troubleshooting this BUG on this upgrade from Google Developers.

Good luck! ;-)

Why is nginx responding to any domain name?

Little comment to answer:

if you have several virtual hosts on several IPs in several config files in sites-available/, than "default" domain for IP will be taken from first file by alphabetic order.

And as Pavel said, there is "default_server" argument for "listen" directive http://nginx.org/en/docs/http/ngx_http_core_module.html#listen

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

How can I get href links from HTML using Python?

My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!

import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
  curpos = test.find("href")
  if curpos >= 0:
    testlen = len(test)
    test = test[curpos:testlen]
    curpos = test.find('"')
    testlen = len(test)
    test = test[curpos+1:testlen]
    curpos = test.find('"')
    needle = test[0:curpos]
    if needle.startswith("http" or "www"):
        needlestack.append(needle)
  else:
    sane = 1
for item in needlestack:
  print item

How to check if a value exists in an object using JavaScript

You can use Object.values():

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

and then use the indexOf() method:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

For example:

Object.values(obj).indexOf("test`") >= 0

A more verbose example is below:

_x000D_
_x000D_
var obj = {_x000D_
  "a": "test1",_x000D_
  "b": "test2"_x000D_
}_x000D_
_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1")); // 0_x000D_
console.log(Object.values(obj).indexOf("test2")); // 1_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1") >= 0); // true_x000D_
console.log(Object.values(obj).indexOf("test2") >= 0); // true _x000D_
_x000D_
console.log(Object.values(obj).indexOf("test10")); // -1_x000D_
console.log(Object.values(obj).indexOf("test10") >= 0); // false
_x000D_
_x000D_
_x000D_

Apache 13 permission denied in user's home directory

im using CentOS 5.5 and for me it was SElinux messing with it, i forgot to check that out. you can temporary disable it by doing as root

echo 0 > /selinux/enforce

hope it help someone

possible EventEmitter memory leak detected

As pointed out by others, increasing the limit is not the best answer. I was facing the same issue, but in my code I was nowhere using any event listener. When I closely looked into the code, I was creating a lot of promises at times. Each promise had some code of scraping the provided URL (using some third-party library). If you are doing something like that, then it may be the cause.

Refer this thread on how to prevent that: What is the best way to limit concurrency when using ES6's Promise.all()?

What is the total amount of public IPv4 addresses?

https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing

For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.

In case of IPv6

The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

inclusive of RESERVED IP

 Reserved address blocks
 Range  Description Reference

 0.0.0.0/8  Current network (only valid as source address)  RFC 6890
 10.0.0.0/8 Private network RFC 1918
 100.64.0.0/10  Shared Address Space    RFC 6598
 127.0.0.0/8    Loopback    RFC 6890
 169.254.0.0/16 Link-local  RFC 3927
 172.16.0.0/12  Private network RFC 1918
 192.0.0.0/24   IETF Protocol Assignments   RFC 6890
 192.0.2.0/24   TEST-NET-1, documentation and examples  RFC 5737
 192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
 192.168.0.0/16 Private network RFC 1918
 198.18.0.0/15  Network benchmark tests RFC 2544
 198.51.100.0/24    TEST-NET-2, documentation and examples  RFC 5737
 203.0.113.0/24 TEST-NET-3, documentation and examples  RFC 5737
 224.0.0.0/4    IP multicast (former Class D network)   RFC 5771
 240.0.0.0/4    Reserved (former Class E network)   RFC 1700
 255.255.255.255    Broadcast   RFC 919

wiki has full details and this has details of IPv6.

How to set a selected option of a dropdown list control using angular JS

I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.

If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:

JS:

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];

HTML:

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

This would leave the "b" item to be selected.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

Add the following dependency. The scope should be compile then it will work.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>compile</scope> 
</dependency>

Log.INFO vs. Log.DEBUG

Debug: fine-grained statements concerning program state, typically used for debugging;

Info: informational statements concerning program state, representing program events or behavior tracking;

Warn: statements that describe potentially harmful events or states in the program;

Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;

Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.

Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Inline SVG in CSS

I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.

A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).

Then, just replace %,<,>,",', with the %xxcodes:

@function svg-inline($string){
  $result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  $result: str-replace($result, '%', '%25');
  $result: str-replace($result, '"', '%22');
  $result: str-replace($result, "'", '%27');
  $result: str-replace($result, ' ', '%20');
  $result: str-replace($result, '<', '%3C');
  $result: str-replace($result, '>', '%3E');
  @return "data:image/svg+xml;utf8," + $result;
}

$mySVG: svg-inline("<svg>...</svg>");

html {
  height: 100vh;
  background: url($mySVG) 50% no-repeat;
}

There is also a image-inline helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.

Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/

How to pass event as argument to an inline event handler in JavaScript?

You don't need to pass this, there already is the event object passed by default automatically, which contains event.target which has the object it's coming from. You can lighten your syntax:

This:

<p onclick="doSomething()">

Will work with this:

function doSomething(){
  console.log(event);
  console.log(event.target);
}

You don't need to instantiate the event object, it's already there. Try it out. And event.target will contain the entire object calling it, which you were referencing as "this" before.

Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:

document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));

Then doSomething() will see event and event.target as per usual!

No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.

How permission can be checked at runtime without throwing SecurityException?

You can also use this:

private boolean doesUserHavePermission()
{
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.

I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

Meaning of delta or epsilon argument of assertEquals for double values

The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.

Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.

If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation

Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));

Or

Assert.assertEquals(0, Double.compareTo(expected, result));

Which can take these nuances into account.

I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.

Read and write a text file in typescript

believe there should be a way in accessing file system.

Include node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed:

import fs from 'fs';
fs.readFileSync('foo.txt','utf8');

You can use other functions in fs as well : https://nodejs.org/api/fs.html

More

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

Error 405 (Method Not Allowed) Laravel 5

When use method delete in form then must have to set route delete

Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");

How to determine if string contains specific substring within the first X characters

Adding on from the answer below i have created this method:

    public static bool ContainsInvalidStrings(IList<string> invalidStrings,string stringToCheck)
    {

        foreach (string invalidString in invalidStrings)
        {
            var index = stringToCheck.IndexOf(invalidString, StringComparison.InvariantCultureIgnoreCase);
            if (index != -1)
            {
                return true;
            }
        }
        return false;
    }

it can be used like this:

            var unsupportedTypes = new List<string>()
        {
            "POINT Empty",
            "MULTIPOINT",
            "MULTILINESTRING",
            "MULTIPOLYGON",
            "GEOMETRYCOLLECTION",
            "CIRCULARSTRING",
            "COMPOUNDCURVE",
            "CURVEPOLYGON",
            "MULTICURVE",
            "TRIANGLE",
            "TIN",
            "POLYHEDRALSURFACE"
        };


            bool hasInvalidValues =   ContainsInvalidStrings(unsupportedTypes,possibleWKT);

you can check for multiple invalid values this way.

Rounding a variable to two decimal places C#

Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.

double pay = 200 + bonus;
double pay = Math.Round(pay);
// Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even
double pay = Math.Round(pay, 2, MidpointRounding.ToEven);
// Rounds up to nearest number
double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero);

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Implementing INotifyPropertyChanged - does a better way exist?

I realize this question already has a gazillion answers, but none of them felt quite right for me. My issue is I don't want any performance hits and am willing to put up with a little verbosity for that reason alone. I also don't care too much for auto properties either, which led me to the following solution:

public abstract class AbstractObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual bool SetValue<TKind>(ref TKind Source, TKind NewValue, params string[] Notify)
    {
        //Set value if the new value is different from the old
        if (!Source.Equals(NewValue))
        {
            Source = NewValue;

            //Notify all applicable properties
            foreach (var i in Notify)
                OnPropertyChanged(i);

            return true;
        }

        return false;
    }

    public AbstractObject()
    {
    }
}

In other words, the above solution is convenient if you don't mind doing this:

public class SomeObject : AbstractObject
{
    public string AnotherProperty
    {
        get
        {
            return someProperty ? "Car" : "Plane";
        }
    }

    bool someProperty = false;
    public bool SomeProperty
    {
        get
        {
            return someProperty;
        }
        set
        {
            SetValue(ref someProperty, value, "SomeProperty", "AnotherProperty");
        }
    }

    public SomeObject() : base()
    {
    }
}

Pros

  • No reflection
  • Only notifies if old value != new value
  • Notify multiple properties at once

Cons

  • No auto properties (you can add support for both, though!)
  • Some verbosity
  • Boxing (small performance hit?)

Alas, it is still better than doing this,

set
{
    if (!someProperty.Equals(value))
    {
        someProperty = value;
        OnPropertyChanged("SomeProperty");
        OnPropertyChanged("AnotherProperty");
    }
}

For every single property, which becomes a nightmare with the additional verbosity ;-(

Note, I do not claim this solution is better performance-wise compared to the others, just that it is a viable solution for those who don't like the other solutions presented.

How to convert byte array to string and vice versa?

Your byte array must have some encoding. The encoding cannot be ASCII if you've got negative values. Once you figure that out, you can convert a set of bytes to a String using:

byte[] bytes = {...}
String str = new String(bytes, StandardCharsets.UTF_8); // for UTF-8 encoding

There are a bunch of encodings you can use, look at the supported encodings in the Oracle javadocs.

Using NOT operator in IF conditions

It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething()) seems fine. However, if you have

if(!doSomething()) {
    ...
}
else {
    // do something else
}

I'd probably reverse that logic to remove the ! operator and make the if clause slightly more clear.

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

urlencoded Forward slash is breaking URL

In Apache, AllowEncodedSlashes On would prevent the request from being immediately rejected with a 404.

Just another idea on how to fix this.

MVC 3 file upload and model binding

Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(x => x.Id)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then in your controller action:

[HttpPost]
public ActionResult Uploadfile(int id, HttpPostedFileBase file)
{
    Containers containers = Repository.GetContainers(id);
    ...
}

On the other hand if you wanted to allow the user to modify this model then you will need to include the proper input fields for each field of your model that you want to be sent to the server:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(x => x.Prop1)
    @Html.TextBoxFor(x => x.Prop2)
    @Html.TextBoxFor(x => x.Prop3)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then you will have the default model binder reconstruct this model from the request:

[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
    ...
}

Using Eloquent ORM in Laravel to perform search of database using LIKE

Use double quotes instead of single quote eg :

where('customer.name', 'LIKE', "%$findcustomer%")

Below is my code:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}

Convert a list of objects to an array of one of the object's properties

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

Convert String To date in PHP

Simple exploding should do the trick:

$monthNamesToInt = array('Jan'=>1,'Feb'=>2, 'Mar'=>3 /*, [...]*/ );
$datetime = '05/Feb/2010:14:00:01';
list($date,$hour,$minute,$second) = explode(':',$datetime);
list($day,$month,$year) = explode('/',$date);

$unixtime = mktime((int)$hour, (int)$minute, (int)$second, $monthNamesToInt[$month], (int)$day, (int)$year);

Where to place JavaScript in an HTML file?

The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.

Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".

How to capture the "virtual keyboard show/hide" event in Android?

You can also check for first DecorView's child bottom padding. It will be set to non-zero value when keyboard is shown.

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    View view = getRootView();
    if (view != null && (view = ((ViewGroup) view).getChildAt(0)) != null) {
        setKeyboardVisible(view.getPaddingBottom() > 0);
    }
    super.onLayout(changed, left, top, right, bottom);
}

How to install Flask on Windows?

I have windows 10 and pythonv3.5. @uku answer is correct. however, problem I was facing is that where are python scripts which are to be added in environment variable. So I found out that we need to add

C:\Users\\AppData\Local\Programs\Python\Python35\Scripts

above location as environment variable. If it still doesnot work search for python in C Drive then find out script locations.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Why does python use 'else' after for and while loops?

Since the technical part has been pretty much answered, my comment is just in relation with the confusion that produce this recycled keyword.

Being Python a very eloquent programming language, the misuse of a keyword is more notorious. The else keyword perfectly describes part of the flow of a decision tree, "if you can't do this, (else) do that". It's implied in our own language.

Instead, using this keyword with while and for statements creates confusion. The reason, our career as programmers has taught us that the else statement resides within a decision tree; its logical scope, a wrapper that conditionally return a path to follow. Meanwhile, loop statements have a figurative explicit goal to reach something. The goal is met after continuous iterations of a process.

if / else indicate a path to follow. Loops follow a path until the "goal" is completed.

The issue is that else is a word that clearly define the last option in a condition. The semantics of the word are both shared by Python and Human Language. But the else word in Human Language is never used to indicate the actions someone or something will take after something is completed. It will be used if, in the process of completing it, an issue rises (more like a break statement).

At the end, the keyword will remain in Python. It's clear it was mistake, clearer when every programmer tries to come up with a story to understand its usage like some mnemonic device. I'd have loved if they have chosen instead the keyword then. I believe that this keyword fits perfectly in that iterative flow, the payoff after the loop.

It resembles that situation that some child has after following every step in assembling a toy: And THEN what Dad?

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

adb uninstall <package_name>

can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:

  1. In Android Studio, click the drop down list to the left of Run button, and select Edit configurations...
  2. Click on app under Android Application, and in General Tab, find the heading 'Before Launch'
  3. Click the + button, select Run external tool, click the + button in the popup window.
  4. Give some name (Eg adb uninstall) and description, and type adb in Program: and uninstall <your-package-name> in Parameters:. Make sure that the new item is selected when you click Ok in the popup window.

Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).

Contains method for a slice

The sort package provides the building blocks if your slice is sorted or you are willing to sort it.

input := []string{"bird", "apple", "ocean", "fork", "anchor"}
sort.Strings(input)

fmt.Println(contains(input, "apple")) // true
fmt.Println(contains(input, "grow"))  // false

...

func contains(s []string, searchterm string) bool {
    i := sort.SearchStrings(s, searchterm)
    return i < len(s) && s[i] == searchterm
}

SearchString promises to return the index to insert x if x is not present (it could be len(a)), so a check of that reveals whether the string is contained the sorted slice.

startsWith() and endsWith() functions in PHP

I would do it like this

     function startWith($haystack,$needle){
              if(substr($haystack,0, strlen($needle))===$needle)
              return true;
        }

  function endWith($haystack,$needle){
              if(substr($haystack, -strlen($needle))===$needle)
              return true;
        }

How to use MySQL dump from a remote machine

This is how you would restore a backup after you successfully backup your .sql file

mysql -u [username] [databasename]

And choose your sql file with this command:

source MY-BACKED-UP-DATABASE-FILE.sql

Setting format and value in input type="date"

Easier than the above is

var today = new Date().toISOString().substring(0,10); # "2013-12-31"

HTML-encoding lost when attribute read from input field

Based on angular's sanitize... (es6 module syntax)

// ref: https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
const NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;

const decodeElem = document.createElement('pre');


/**
 * Decodes html encoded text, so that the actual string may
 * be used.
 * @param value
 * @returns {string} decoded text
 */
export function decode(value) {
  if (!value) return '';
  decodeElem.innerHTML = value.replace(/</g, '&lt;');
  return decodeElem.textContent;
}


/**
 * Encodes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} encoded text
 */
export function encode(value) {
  if (value === null || value === undefined) return '';
  return String(value).
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, value => {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, value => {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

export default {encode,decode};

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

How to get row data by clicking a button in a row in an ASP.NET gridview

<ItemTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="MyButtonClick" />
</ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e)
{
     //Get the button that raised the event
Button btn = (Button)sender;

    //Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

How do you upload a file to a document library in sharepoint?

As an alternative to the webservices, you can use the put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).

For a reference application that explains the use of Frontpage RPC, see the SharePad project on CodePlex.

MySQL Cannot Add Foreign Key Constraint

Confirm that the character encoding and collation for the two tables is the same.

In my own case, one of the tables was using utf8 and the other was using latin1.

I had another case where the encoding was the same but the collation different. One utf8_general_ci the other utf8_unicode_ci

You can run this command to set the encoding and collation for a table.

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I hope this helps someone.

How can I create a dynamically sized array of structs?

If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

Some example code would be:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);

Angles between two n-dimensional vectors in Python

The other possibility is using just numpy and it gives you the interior angle

import numpy as np

p0 = [3.5, 6.7]
p1 = [7.9, 8.4]
p2 = [10.8, 4.8]

''' 
compute angle (in degrees) for p0p1p2 corner
Inputs:
    p0,p1,p2 - points in the form of [x,y]
'''

v0 = np.array(p0) - np.array(p1)
v1 = np.array(p2) - np.array(p1)

angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))
print np.degrees(angle)

and here is the output:

In [2]: p0, p1, p2 = [3.5, 6.7], [7.9, 8.4], [10.8, 4.8]

In [3]: v0 = np.array(p0) - np.array(p1)

In [4]: v1 = np.array(p2) - np.array(p1)

In [5]: v0
Out[5]: array([-4.4, -1.7])

In [6]: v1
Out[6]: array([ 2.9, -3.6])

In [7]: angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))

In [8]: angle
Out[8]: 1.8802197318858924

In [9]: np.degrees(angle)
Out[9]: 107.72865519428085

Is this a good way to clone an object in ES6?

If the methods you used isn't working well with objects involving data types like Date, try this

Import _

import * as _ from 'lodash';

Deep clone object

myObjCopy = _.cloneDeep(myObj);

A table name as a variable

Declare  @tablename varchar(50) 
set @tablename = 'Your table Name' 
EXEC('select * from ' + @tablename)

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Offering another potential solution to this error.

If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.

e.g.

https://example.com/api/etc

and not

https://123.4.5.6/api/etc

In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE.

scikit-learn random state in splitting dataset

random_state is None by default which means every time when you run your program you will get different output because of splitting between train and test varies within.

random_state = any int value means every time when you run your program you will get tehe same output because of splitting between train and test does not varies within.

Form/JavaScript not working on IE 11 with error DOM7011

I got the same console warning, when an ajax request was firing, so my form was also not working properly.

I disabled caching on the server's ajax call with the following response headers:

Cache-Control: no-cache, no-store, must-revalidate
Expires: -1
Pragma: no-cache

After this, the form was working. Refer to the server language (c#, php, java etc) you are using on how to add these response headers.

How do you exit from a void function in C++?

void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

pd.set_option('display.max_columns', None)  

id (second argument) can fully show the columns.

Extracting .jar file with command line

From the docs:

To extract the files from a jar file, use x, as in:

C:\Java> jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

The folder where jar is probably isn't C:\Java for you, on my Windows partition it's:

C:\Program Files (x86)\Java\jdk[some_version_here]\bin

Unless the location of jar is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.

EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html

Windows ignores JAVA_HOME: how to set JDK as default?

After struggling with this issue for some time and researching about it, I finally managed to solve it following these steps:

1) install jdk version 12
2) Create new variable in systems variable
3) Name it as JAVA_HOME and give jdk installation path
4) add this variable in path and move it to top.
5) go to C:\Program Files (86)\Common Files\Oracle\Java\javapath and replace java.exe and javaw.exe with the corresponding files with the same names from the pathtojavajdk/bin folder

Finally, I checked the default version of java in cmd with "java -version" and it worked!

PowerShell Connect to FTP server and get files

Based on Why does FtpWebRequest download files from the root directory? Can this cause a 553 error?, I wrote a PowerShell script that enabled to download a file from a FTP-Server via explicit FTP over TLS:

# Config
$Username = "USERNAME"
$Password = "PASSWORD"
$LocalFile = "C:\PATH_TO_DIR\FILNAME.EXT"
#e.g. "C:\temp\somefile.txt"
$RemoteFile = "ftp://PATH_TO_REMOTE_FILE"
#e.g. "ftp://ftp.server.com/home/some/path/somefile.txt"

try{ 
    # Create a FTPWebRequest
    $FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
    $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
    $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $FTPRequest.UseBinary = $true
    $FTPRequest.KeepAlive = $false
    $FTPRequest.EnableSsl  = $true
    # Send the ftp request
    $FTPResponse = $FTPRequest.GetResponse()
    # Get a download stream from the server response
    $ResponseStream = $FTPResponse.GetResponseStream()
    # Create the target file on the local system and the download buffer
    $LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
    [byte[]]$ReadBuffer = New-Object byte[] 1024
    # Loop through the download

    do {
        $ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
        $LocalFileFile.Write($ReadBuffer,0,$ReadLength)
    }
    while ($ReadLength -ne 0)
}catch [Exception]
{
    $Request = $_.Exception
    Write-host "Exception caught: $Request"
}

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

What is the use of ObservableCollection in .net?

it is a collection which is used to notify mostly UI to change in the collection , it supports automatic notification.

Mainly used in WPF ,

Where say suppose you have UI with a list box and add button and when you click on he button an object of type suppose person will be added to the obseravablecollection and you bind this collection to the ItemSource of Listbox , so as soon as you added a new item in the collection , Listbox will update itself and add one more item in it.

Disable Enable Trigger SQL server for a table

As Mark mentioned, the previous statement should be ended in semi-colon. So you can use:

; DISABLE TRIGGER dbo.tr_name ON dbo.table_name

Using 'sudo apt-get install build-essentials'

The package is called build-essential without the plural "s". So

sudo apt-get install build-essential

should do what you want.

How to horizontally align ul to center of div?

ul {
width: 90%; 
    list-style-type:none;
    margin:auto;
    padding:0;
    position:relative;
    left:5%;
}

How to show multiline text in a table cell

You want to use the CSS white-space:pre applied to the appropriate <td>. To do this to all table cells, for example:

td { white-space:pre }

Alternatively, if you can change your markup, you can use a <pre> tag around your content. By default web browsers use their user-agent stylesheet to apply the same white-space:pre rule to this element.

The PRE element tells visual user agents that the enclosed text is "preformatted". When handling preformatted text, visual user agents:

  • May leave white space intact.
  • May render text with a fixed-pitch font.
  • May disable automatic word wrap.
  • Must not disable bidirectional processing.

Check if string is neither empty nor space in shell script

To check if a string is empty or contains only whitespace you could use:

shopt -s extglob  # more powerful pattern matching

if [ -n "${str##+([[:space:]])}" ]; then
    echo '$str is not null or space'
fi

See Shell Parameter Expansion and Pattern Matching in the Bash Manual.

When to use pthread_exit() and when to use pthread_join() in Linux?

You don't need any calls to pthread_exit(3) in your particular code.

In general, the main thread should not call pthread_exit, but should often call pthread_join(3) to wait for some other thread to finish.

In your PrintHello function, you don't need to call pthread_exit because it is implicit after returning from it.

So your code should rather be:

void *PrintHello(void *threadid)  {
  long tid = (long)threadid;
  printf("Hello World! It's me, thread #%ld!\n", tid);
  return threadid;
}

int main (int argc, char *argv[]) {
   pthread_t threads[NUM_THREADS];
   int rc;
   intptr_t t;
   // create all the threads
   for(t=0; t<NUM_THREADS; t++){
     printf("In main: creating thread %ld\n", (long) t);
     rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
     if (rc) { fprintf(stderr, "failed to create thread #%ld - %s\n",
                                (long)t, strerror(rc));
               exit(EXIT_FAILURE);
             };
   }
   pthread_yield(); // useful to give other threads more chance to run
   // join all the threads
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: joining thread #%ld\n", (long) t);
      rc = pthread_join(&threads[t], NULL);
      if (rc) { fprintf(stderr, "failed to join thread #%ld - %s\n",
                                (long)t, strerror(rc));
               exit(EXIT_FAILURE);
      }
   }
}

Generating random whole numbers in JavaScript in a specific range?

function getRandomInt(lower, upper)
{
    //to create an even sample distribution
    return Math.floor(lower + (Math.random() * (upper - lower + 1)));

    //to produce an uneven sample distribution
    //return Math.round(lower + (Math.random() * (upper - lower)));

    //to exclude the max value from the possible values
    //return Math.floor(lower + (Math.random() * (upper - lower)));
}

To test this function, and variations of this function, save the below HTML/JavaScript to a file and open with a browser. The code will produce a graph showing the distribution of one million function calls. The code will also record the edge cases, so if the the function produces a value greater than the max, or less than the min, you.will.know.about.it.

<html>
    <head>
        <script type="text/javascript">
        function getRandomInt(lower, upper)
        {
            //to create an even sample distribution
            return Math.floor(lower + (Math.random() * (upper - lower + 1)));

            //to produce an uneven sample distribution
            //return Math.round(lower + (Math.random() * (upper - lower)));

            //to exclude the max value from the possible values
            //return Math.floor(lower + (Math.random() * (upper - lower)));
        }

        var min = -5;
        var max = 5;

        var array = new Array();

        for(var i = 0; i <= (max - min) + 2; i++) {
          array.push(0);
        }

        for(var i = 0; i < 1000000; i++) {
            var random = getRandomInt(min, max);
            array[random - min + 1]++;
        }

        var maxSample = 0;
        for(var i = 0; i < max - min; i++) {
            maxSample = Math.max(maxSample, array[i]);
        }

        //create a bar graph to show the sample distribution
        var maxHeight = 500;
        for(var i = 0; i <= (max - min) + 2; i++) {
            var sampleHeight = (array[i]/maxSample) * maxHeight;

            document.write('<span style="display:inline-block;color:'+(sampleHeight == 0 ? 'black' : 'white')+';background-color:black;height:'+sampleHeight+'px">&nbsp;[' + (i + min - 1) + ']:&nbsp;'+array[i]+'</span>&nbsp;&nbsp;');
        }
        document.write('<hr/>');
        </script>
    </head>
    <body>

    </body>
</html>

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

How do I connect to this localhost from another computer on the same network?

Provided both machines are in the same workgroup, open cmd.exe on the machine you want to connect to, type ipconfig and note the IP at the IPv4 Address line.

Then, on the machine you want to connect with, use http:// + the IP of the target machine.

That should do it.

Padding or margin value in pixels as integer using jQuery

This simple function will do it:

$.fn.pixels = function(property) {
    return parseInt(this.css(property).slice(0,-2));
};

Usage:

var padding = $('#myId').pixels('paddingTop');

Convert a dta file to csv without Stata software

In Python, one can use statsmodels.iolib.foreign.genfromdta to read Stata datasets. In addition, there is also a wrapper of the aforementioned function which can be used to read a Stata file directly from the web: statsmodels.datasets.webuse.

Nevertheless, both of the above rely on the use of the pandas.io.stata.StataReader.data, which is now a legacy function and has been deprecated. As such, the new pandas.read_stata function should now always be used instead.

According to the source file of stata.py, as of version 0.23.0, the following are supported:

Stata data file versions:

  • 104
  • 105
  • 108
  • 111
  • 113
  • 114
  • 115
  • 117
  • 118

Valid encodings:

  • ascii
  • us-ascii
  • latin-1
  • latin_1
  • iso-8859-1
  • iso8859-1
  • 8859
  • cp819
  • latin
  • latin1
  • L1

As others have noted, the pandas.to_csv function can then be used to save the file into disk. A related function numpy.savetxt can also save the data as a text file.


EDIT:

The following details come from help dtaversion in Stata 15.1:

        Stata version     .dta file format
        ----------------------------------------
               1               102
            2, 3               103
               4               104
               5               105
               6               108
               7            110 and 111
            8, 9            112 and 113
          10, 11               114
              12               115
              13               117
              14 and 15        118 (# of variables <= 32,767)
              15               119 (# of variables > 32,767, Stata/MP only)
        ----------------------------------------
        file formats 103, 106, 107, 109, and 116
        were never used in any official release.

Bootstrap : TypeError: $(...).modal is not a function

Use this. It will work. I have used bootstrap 3.3.5 and jquery 1.11.3

_x000D_
_x000D_
$('document').ready(function() {_x000D_
  $('#btnTest').click(function() {_x000D_
    $('#dummyModal').modal('show');_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  padding-top: 40px;_x000D_
  padding-bottom: 40px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width,initial-scale=1">_x000D_
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
  <title>Modal Test</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="container">_x000D_
    <button id="btnTest" class="btn btn-default">Show Modal</button>_x000D_
    <div id="dummyModal" role="dialog" class="modal fade">_x000D_
      <div class="modal-dialog">_x000D_
        <div class="modal-content">_x000D_
          <div class="modal-header">_x000D_
            <button type="button" data-dismiss="modal" class="close">&times;</button>_x000D_
            <h4 class="modal-title">Error</h4>_x000D_
          </div>_x000D_
          <div class="modal-body">_x000D_
            <p>Quick Brown Fox Jumps Over The Lazy Dog</p>_x000D_
          </div>_x000D_
          <div class="modal-footer">_x000D_
            <button type="button" data-dismiss="modal" class="btn btn-default">Close</button>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
  <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Numpy: Creating a complex array from 2 real ones?

This is what your are looking for:

from numpy import array

a=array([1,2,3])
b=array([4,5,6])

a + 1j*b

->array([ 1.+4.j,  2.+5.j,  3.+6.j])

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

java.math.BigInteger cannot be cast to java.lang.Long

Your error might be in this line:

List<Long> result = query.list();

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();

Make child div stretch across width of page

With current browsers (this question is dating a bit now), you can use the much simpler vw (viewport width) unit:

#help_panel {
  margin-left: calc(50% - 50vw);
  width: 100vw;
}

(usage data: http://caniuse.com/#feat=viewport-units)

From my tests, this should not break your flow while being easy to use.

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

jQuery - Increase the value of a counter when a button is clicked

You are trying to set "++" on a jQuery element!

YOu could declare a js variable

var counter = 0;

and in jQuery code do:

$("#counter").html(counter++);

How to remove all .svn directories from my application directories

There are already many answers provided for deleting the .svn-directory. But I want to add, that you can avoid these directories from the beginning, if you do an export instead of a checkout:

svn export <url>

how to remove json object key and value.?

function omit(obj, key) {
    const {[key]:ignore, ...rest} = obj;
    return rest;
}

You can use ES6 spread operators like this. And to remove your key simply call

const newJson = omit(myjsonobj, "otherIndustry");

Its always better if you maintain pure function when you deal with type=object in javascript.

SOAP Action WSDL

If its a SOAP 1.1 service then you will also need to include a SOAPAction HTTP header field:

http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528

get one item from an array of name,value JSON

You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...

var hash = {};
hash['k1'] = 'abc';
...

Then you can retrieve using bracket or dot notation:

alert(hash['k1']); // alerts 'abc'
alert(hash.k1); // also alerts 'abc'

For arrays, check the underscore.js library in general and the detect method in particular. Using detect you could do something like...

_.detect(arr, function(x) { return x.name == 'k1' });

Or more generally

MyCollection = function() {
  this.arr = [];
}

MyCollection.prototype.getByName = function(name) {
  return _.detect(this.arr, function(x) { return x.name == name });
}

MyCollection.prototype.push = function(item) {
  this.arr.push(item);
}

etc...

Directory-tree listing in Python

I wrote a long version, with all the options I might need: http://sam.nipl.net/code/python/find.py

I guess it will fit here too:

#!/usr/bin/env python

import os
import sys

def ls(dir, hidden=False, relative=True):
    nodes = []
    for nm in os.listdir(dir):
        if not hidden and nm.startswith('.'):
            continue
        if not relative:
            nm = os.path.join(dir, nm)
        nodes.append(nm)
    nodes.sort()
    return nodes

def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
    root = os.path.join(root, '')  # add slash if not there
    for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
        if relative:
            parent = parent[len(root):]
        if dirs and parent:
            yield os.path.join(parent, '')
        if not hidden:
            lfiles   = [nm for nm in lfiles if not nm.startswith('.')]
            ldirs[:] = [nm for nm in ldirs  if not nm.startswith('.')]  # in place
        if files:
            lfiles.sort()
            for nm in lfiles:
                nm = os.path.join(parent, nm)
                yield nm

def test(root):
    print "* directory listing, with hidden files:"
    print ls(root, hidden=True)
    print
    print "* recursive listing, with dirs, but no hidden files:"
    for f in find(root, dirs=True):
        print f
    print

if __name__ == "__main__":
    test(*sys.argv[1:])

Google Maps API v3 adding an InfoWindow to each marker

for Earth plugin APIs, create the balloon outside your loop and pass your counter to the function to get unique contents for each placemark!

function createBalloon(placemark, i, event) {
            var p = placemark;
            var j = i;
            google.earth.addEventListener(p, 'click', function (event) {
                    // prevent the default balloon from popping up
                    event.preventDefault();
                    var balloon = ge.createHtmlStringBalloon('');
                    balloon.setFeature(event.getTarget());

                    balloon.setContentString('iframePath#' + j);

                    ge.setBalloon(balloon);
            });
        }

How to get json key and value in javascript?

var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

How do I create and read a value from cookie?

Here are functions you can use for creating and retrieving cookies.

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Make cross-domain ajax JSONP request with jQuery

Try

alert(xml.Data[0].City)

Case sensitivly!

Lombok is not generating getter and setter

Download Lombok Jar, let’s maven do the download on our behalf :

 <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
    </dependency>

Now... mvn clean install command on the newly created project to get this jar downloaded in local repository. Goto the jar location, execute the command prompt, run the command : java -jar lombok-1.16.18.jar

enter image description here

click on the “Specify Location” button and locate the eclipse.exe path LIKE : enter image description here

finally install this by clicking the “Install/Update”

Convert XML String to Object

You can generate class as described above, or write them manually:

[XmlRoot("msg")]
public class Message
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("action")]
    public string Action { get; set; }
}

Then you can use ExtendedXmlSerializer to serialize and deserialize.

Instalation You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Serialization:

var serializer = new ConfigurationContainer().Create();
var obj = new Message();
var xml = serializer.Serialize(obj);

Deserialization

var obj2 = serializer.Deserialize<Message>(xml);

This serializer support:

  • Deserialization xml from standard XMLSerializer
  • Serialization class, struct, generic class, primitive type, generic list and dictionary, array, enum
  • Serialization class with property interface
  • Serialization circular reference and reference Id
  • Deserialization of old version of xml
  • Property encryption
  • Custom serializer
  • Support XmlElementAttribute and XmlRootAttribute
  • POCO - all configurations (migrations, custom serializer...) are outside the class

ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.

Interface naming in Java

As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:

class Number implements Comparable{...}  
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}

Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.

Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?

I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.

Is there a way to run Bash scripts on Windows?

Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).

Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.

Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.

How does a Breadth-First Search work when looking for Shortest Path?

As pointed above, BFS can only be used to find shortest path in a graph if:

  1. There are no loops

  2. All edges have same weight or no weight.

To find the shortest path, all you have to do is start from the source and perform a breadth first search and stop when you find your destination Node. The only additional thing you need to do is have an array previous[n] which will store the previous node for every node visited. The previous of source can be null.

To print the path, simple loop through the previous[] array from source till you reach destination and print the nodes. DFS can also be used to find the shortest path in a graph under similar conditions.

However, if the graph is more complex, containing weighted edges and loops, then we need a more sophisticated version of BFS, i.e. Dijkstra's algorithm.

Reference — What does this symbol mean in PHP?

Bitwise Operator

What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)

What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------

This representation of 1 Byte

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)

A few examples for better understanding

The "AND" operator: &

$a =  9;
$b = 10;
echo $a & $b;

This would output the number 8. Why? Well let's see using our table example.

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      &     |   0|  0|  0|  0| 1| 0| 0| 0|
------------------------------------------- 

So you can see from the table the only bit they share together is the 8 bit.

Second example

$a =  36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111

The two shared bits are 32 and 4, which when added together return 36.

The "Or" operator: |

$a =  9;
$b = 10;
echo $a | $b;

This would output the number 11. Why?

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      |     |   0|  0|  0|  0| 1| 0| 1| 1|
-------------------------------------------

You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.

Vagrant ssh authentication failure

This might be the last answer in the list but this worked for me and I did not find this answer anywhere, I found it my self after 2 days of researches so you've better try this if nothing else worked for you until now.

In my case the problem came from my VirtualBox. I don't know for what reason an option was disabled and it should have been enabled.

enter image description here

As you can see in the image, there were some network problems with my VirtualBox and what I had to do in order to fix this problem was to select my machine, press on settings, network tab and after that make sure that the option Cable Connected was selected. In my case this option was not selected and I it failed at this step:

default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key

First I thought that the port is already in use, after that I reinstalled Vagrant and I also tried other things but none of them worked for me.

how to bypass Access-Control-Allow-Origin?

It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

Usage:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

You get the idea.

Make a div fill the height of the remaining screen space

None of the solutions posted work when you need the bottom div to scroll when the content is too tall. Here's a solution that works in that case:

_x000D_
_x000D_
.table {_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.table-row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.table-cell {_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
.header {_x000D_
  background: cyan;_x000D_
}_x000D_
_x000D_
.body {_x000D_
  background: yellow;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.body-content-outer-wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.body-content-inner-wrapper {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.body-content {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<div class="table container">_x000D_
  <div class="table-row header">_x000D_
    <div>This is the header whose height is unknown</div>_x000D_
    <div>This is the header whose height is unknown</div>_x000D_
    <div>This is the header whose height is unknown</div>_x000D_
  </div>_x000D_
  <div class="table-row body">_x000D_
    <div class="table-cell body-content-outer-wrapper">_x000D_
      <div class="body-content-inner-wrapper">_x000D_
        <div class="body-content">_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
          <div>This is the scrollable content whose height is unknown</div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Original source: Filling the Remaining Height of a Container While Handling Overflow in CSS

JSFiddle live preview

Escaping ampersand character in SQL string

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');

Remove all special characters with RegExp

I use RegexBuddy for debbuging my regexes it has almost all languages very usefull. Than copy/paste for the targeted language. Terrific tool and not very expensive.

So I copy/pasted your regex and your issue is that [,] are special characters in regex, so you need to escape them. So the regex should be : /!@#$^&%*()+=-[\x5B\x5D]\/{}|:<>?,./im

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

calculating execution time in c++

I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..

What is a non-capturing group in regular expressions?

Open your Google Chrome devTools and then Console tab: and type this:

"Peace".match(/(\w)(\w)(\w)/)

Run it and you will see:

["Pea", "P", "e", "a", index: 0, input: "Peace", groups: undefined]

The JavaScript RegExp engine capture three groups, the items with indexes 1,2,3. Now use non-capturing mark to see the result.

"Peace".match(/(?:\w)(\w)(\w)/)

The result is:

["Pea", "e", "a", index: 0, input: "Peace", groups: undefined]

This is obvious what is non capturing group.

Display XML content in HTML page

If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

$('#container').text(xmlString);

Here's how you'd do it with standard DOM methods:

document.getElementById('container')
        .appendChild(document.createTextNode(xmlString));

If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

data.frame Group By column

This is a common question. In base, the option you're looking for is aggregate. Assuming your data.frame is called "mydf", you can use the following.

> aggregate(B ~ A, mydf, sum)
  A  B
1 1  5
2 2  3
3 3 11

I would also recommend looking into the "data.table" package.

> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
   A V1
1: 1  5
2: 2  3
3: 3 11

How to specify a multi-line shell variable?

Thanks to dimo414's answer to a similar question, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

Pass a PHP array to a JavaScript function

You can pass PHP arrays to JavaScript using json_encode PHP function.

<?php
    $phpArray = array(
        0 => "Mon", 
        1 => "Tue", 
        2 => "Wed", 
        3 => "Thu",
        4 => "Fri", 
        5 => "Sat",
        6 => "Sun",
    )
?>

<script type="text/javascript">

    var jArray = <?php echo json_encode($phpArray); ?>;

    for(var i=0; i<jArray.length; i++){
        alert(jArray[i]);
    }

 </script>

BOOLEAN or TINYINT confusion

As of MySql 5.1 version reference

BIT(M) =  approximately (M+7)/8 bytes, 
BIT(1) =  (1+7)/8 = 1 bytes (8 bits)

=========================================================================

TINYINT(1) take 8 bits.

https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric

What is boilerplate code?

Boilerplate definition is becoming more global in many other programming languages nowadays. It comes from OOP and hybrid languages that have become OOP and were before procedual have now the same goal to keep repeating the code you build with a model/template/class/object hence why they adapt this term. You make a template and the only things you do for each instance of a template are the parameters to individualize an object this part is what we call boilerplate. You simply re-use the code you made a template of, just with different parameters.

Synonyms
a blueprint is a boilerplate
a stencil is a boilerplate
a footer is a boilerplate
a design pattern for multiple use is a boilerplate
a signature of a mail is a boilerplate

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How to remove an iOS app from the App Store

For those who remove app from sale, keep following in mind:

  • In app purchase items will NOT be removed automatically, user still can buy them, you have to change each item status.
  • Users who've downloaded the app before still can restore/redownload app.

See details: Removing and app from sale.

If you want to completely remove your App, you should delete your app.

No internet on Android emulator - why and how to fix?

Allow the ADB to access the network by opening it on the firewall

If you are using winvista and above, go to Windows Advance Firewall under Administrative tool in Control Panel and enable it from there

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

python: how to send mail with TO, CC and BCC?

It did not worked for me until i created:

#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc

and than added cc in recipient [list] like:

s.sendmail(me, [you,cc], msg.as_string())

Why can't decimal numbers be represented exactly in binary?

I'm surprised no one has stated this yet: use continued fractions. Any rational number can be represented finitely in binary this way.

Some examples:

1/3 (0.3333...)

0; 3

5/9 (0.5555...)

0; 1, 1, 4

10/43 (0.232558139534883720930...)

0; 4, 3, 3

9093/18478 (0.49209871198181621387596060179673...)

0; 2, 31, 7, 8, 5

From here, there are a variety of known ways to store a sequence of integers in memory.

In addition to storing your number with perfect accuracy, continued fractions also have some other benefits, such as best rational approximation. If you decide to terminate the sequence of numbers in a continued fraction early, the remaining digits (when recombined to a fraction) will give you the best possible fraction. This is how approximations to pi are found:

Pi's continued fraction:

3; 7, 15, 1, 292 ...

Terminating the sequence at 1, this gives the fraction:

355/113

which is an excellent rational approximation.

Difference between staticmethod and classmethod

@staticmethod just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:

>>> class C(object):
...  pass
... 
>>> def f():
...  pass
... 
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>

As a matter of fact, classmethod has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:

>>> class CMeta(type):
...  def foo(cls):
...   print cls
... 
>>> class C(object):
...  __metaclass__ = CMeta
... 
>>> C.foo()
<class '__main__.C'>

Connecting to Postgresql in a docker container from outside

To connect from the localhost you need to add '--net host':

docker run --name some-postgres --net host -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

You can access the server directly without using exec from your localhost, by using:

psql -h localhost -p 5432 -U postgres

SVG drop shadow using css3

Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope attribute controls how much opacity to give to the dropshadow.

Relevant bits from the example:

<filter id="dropshadow" height="130%">
  <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
  <feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
  <feComponentTransfer>
    <feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
  </feComponentTransfer>
  <feMerge> 
    <feMergeNode/> <!-- this contains the offset blurred image -->
    <feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
  </feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>

Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.

Python Web Crawlers and "getting" html source code

The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.

When you say modify the page and return the modified page what do you mean?

What are the default access modifiers in C#?

Namespace level: internal

Type level: private

HTML Submit-button: Different value / button-text?

It's possible using the button element.

<button name="name" value="value" type="submit">Sök</button>

From the W3C page on button:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.

How to add 10 minutes to my (String) time?

I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Reversing a linked list in Java, recursively

I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.

This should reverse a singly linked list, called with reverse(head,NULL); so if this were your list:

1->2->3->4->5->null
it would become:
5->4->3->2->1->null

    //Takes as parameters a node in a linked list, and p, the previous node in that list
    //returns the head of the new list
    Node reverse(Node n,Node p){   
        if(n==null) return null;
        if(n.next==null){ //if this is the end of the list, then this is the new head
            n.next=p;
            return n;
        }
        Node r=reverse(n.next,n);  //call reverse for the next node, 
                                      //using yourself as the previous node
        n.next=p;                     //Set your next node to be the previous node 
        return r;                     //Return the head of the new list
    }
    

edit: ive done like 6 edits on this, showing that it's still a little tricky for me lol

Set line spacing

Try this property

line-height:200%;

or

line-height:17px;

use the increase & decrease the volume

Error inflating class fragment

My simple approach

If you use <fragment> in your xml then you must provide name attribute i.e;

      <fragment 
        android:name='path.to.your.fragment
        />`

which will initialise your fragment and you don't need to do it from java.

If you want to use Java approach to add fragment then, use any layout like

<LinearLayout
   android:id="@+id/fragment_container"
 />

and use this container for your fragment

transaction.replace(R.id.fragment_container, fragment_obj);

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

Action Bar's onClick listener for the Home button

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();  return true;
    }

    return super.onOptionsItemSelected(item);
}

Sorting hashmap based on keys

Use a TreeMap with a custom comparator.

class MyComparator implements Comparator<String>
    {
        public int compare(String o1,String o2)
        {
            // Your logic for comparing the key strings
        }
    }

TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());

As you add new elements, they will be automatically sorted.

In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

How to receive JSON as an MVC 5 action method parameter

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

Hexadecimal string to byte array in C

Following is the solution I wrote up for performance reasons:

void hex2bin(const char* in, size_t len, unsigned char* out) {

  static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,  60,  61,
    62,  63,  64,  10,  11,  12,  13,  14,  15,  71,  72,  73,  74,  75,
    76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
    90,  91,  92,  93,  94,  95,  96,  10,  11,  12,  13,  14,  15
  };

  static const unsigned char *LOOKUP = TBL - 48;

  const char* end = in + len;

  while(in < end) *(out++) = LOOKUP[*(in++)] << 4 | LOOKUP[*(in++)];

}

Example:

unsigned char seckey[32];

hex2bin("351aaaec0070d13d350afae2bc43b68c7e590268889869dde489f2f7988f3fee", 64, seckey);

/*
  seckey = {
     53,  26, 170, 236,   0, 112, 209,  61,  53,  10, 250, 226, 188,  67, 182, 140, 
    126,  89,   2, 104, 136, 152, 105, 221, 228, 137, 242, 247, 152, 143,  63, 238
  };
*/

If you don't need to support lowercase:

static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,
    60,  61,  62,  63,  64,  10,  11,  12,  13,  14,  15
};

A failure occurred while executing com.android.build.gradle.internal.tasks

search your code you must be referring to color in color.xml in an xml drawable. go and give hex code instead of referencing....

Example: in drawable.xml you must have called

android:fillColor="@color/blue"

change it to android:fillColor="#ffaacc" hope it solve your problem...

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

Excel Date to String conversion

I have no idea about the year of publication of the question; it might be old now. So, I expect my answer to be more of a reference for future similar questions after my post.

I don't know if anybody out there has already given an answer similar to the one I am about to give, which might result -I think- being the simplest, most direct and most effective: If someone has already given it, I apologize, but I haven't seen it. Here, my answer using CStr instead of TEXT:

Asuming cell A1 contains a date, and using VBA code:

Dim strDate As String

'Convert to string the value contained in A1 (a date)
strDate = CStr([A1].Value)

You can, thereafter, manipulate it as any ordinary string using string functions (MID, LEFT, RIGHT, LEN, CONCATENATE (&), etc.)

How to automate drag & drop functionality using Selenium WebDriver Java

Selenium has pretty good documentation. Here is a link to the specific part of the API you are looking for:

WebElement element = driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

This is to drag and drop a single file, How to drag and drop multiple files.

How to find elements by class

Update: 2016 In the latest version of beautifulsoup, the method 'findAll' has been renamed to 'find_all'. Link to official documentation

List of method names changed

Hence the answer will be

soup.find_all("html_element", class_="your_class_name")

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

I originally used @Aliceljm's answer for a file upload project I was working on, but recently ran into an issue where a file was 0.98kb but being read as 1.02mb. Here's the updated code I'm now using.

function formatBytes(bytes){
  var kb = 1024;
  var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
  var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];

  return {
    size: +(bytes / kb / kb).toFixed(2),
    type: fileSizeTypes[ndx]
  };
}

The above would then be called after a file was added like so

// In this case `file.size` equals `26060275` 
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`

Granted, Windows reads the file as being 24.8mb but I'm fine with the extra precision.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

Suppress output of a function

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

how to fix groovy.lang.MissingMethodException: No signature of method:

To help other bug-hunters. I had this error because the function didn't exist.

I had a spelling error.

Cannot ignore .idea/workspace.xml - keeps popping up

If you have multiple projects in your git repo, .idea/workspace.xml will not match to any files.

Instead, do the following:

$ git rm -f **/.idea/workspace.xml

And make your .gitignore look something like this:

# User-specific stuff:
**/.idea/workspace.xml
**/.idea/tasks.xml
**/.idea/dictionaries
**/.idea/vcs.xml
**/.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
**/.idea/dataSources.ids
**/.idea/dataSources.xml
**/.idea/dataSources.local.xml
**/.idea/sqlDataSources.xml
**/.idea/dynamic.xml
**/.idea/uiDesigner.xml

## File-based project format:
*.iws

# IntelliJ
/out/

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

The term 'ng' is not recognized as the name of a cmdlet

After changing the path you have to restart powershell. You do not need to restart your computer.

Python dict how to create key or append an element to key?

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

Plot 3D data in R

I think the following code is close to what you want

x    <- c(0.1, 0.2, 0.3, 0.4, 0.5)
y    <- c(1, 2, 3, 4, 5)
zfun <- function(a,b) {a*b * ( 0.9 + 0.2*runif(a*b) )}
z    <- outer(x, y, FUN="zfun")

It gives data like this (note that x and y are both increasing)

> x
[1] 0.1 0.2 0.3 0.4 0.5
> y
[1] 1 2 3 4 5
> z
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 0.1037159 0.2123455 0.3244514 0.4106079 0.4777380
[2,] 0.2144338 0.4109414 0.5586709 0.7623481 0.9683732
[3,] 0.3138063 0.6015035 0.8308649 1.2713930 1.5498939
[4,] 0.4023375 0.8500672 1.3052275 1.4541517 1.9398106
[5,] 0.5146506 1.0295172 1.5257186 2.1753611 2.5046223

and a graph like

persp(x, y, z)

persp(x, y, z)

How can I change the color of pagination dots of UIPageControl?

You could also use Three20 Library that contains a styleable PageControl and dozens of other helpful UI Controls and Abstractions.

Better way to cast object to int

Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.

So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.

Instead another simple way, but really performance costing is to cast before in dynamic.

(int)(dynamic)myObject.

You can try it in the Interactive window of VS.

public class Test
{
  public static implicit operator int(Test v)
  {
    return 12;
  }
}

(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

Create openssl.conf file:

[req]
default_bits = 2048
default_keyfile = oats.key
encrypt_key = no
utf8 = yes
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = Cary
L = Cary
O  = BigCompany
CN = *.myserver.net

[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = myserver.net
DNS.2 = *.myserver.net

Run this comand:

openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout app.key -out app.crt  -config openssl.conf

Output files app.crt and app.key work for me.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Method #1: Download from Here and insert it to your projects, or
Method #2: use below code before your bootstrap script source:

<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>

UnicodeDecodeError, invalid continuation byte

In binary, 0xE9 looks like 1110 1001. If you read about UTF-8 on Wikipedia, you’ll see that such a byte must be followed by two of the form 10xx xxxx. So, for example:

>>> b'\xe9\x80\x80'.decode('utf-8')
u'\u9000'

But that’s just the mechanical cause of the exception. In this case, you have a string that is almost certainly encoded in latin 1. You can see how UTF-8 and latin 1 look different:

>>> u'\xe9'.encode('utf-8')
b'\xc3\xa9'
>>> u'\xe9'.encode('latin-1')
b'\xe9'

(Note, I'm using a mix of Python 2 and 3 representation here. The input is valid in any version of Python, but your Python interpreter is unlikely to actually show both unicode and byte strings in this way.)

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present