Programs & Examples On #Pik

Pik is a Ruby version manager for Windows

HTTP POST with Json on Body - Flutter/Dart

OK, finally we have an answer...

You are correctly specifying headers: {"Content-Type": "application/json"}, to set your content type. Under the hood either the package http or the lower level dart:io HttpClient is changing this to application/json; charset=utf-8. However, your server web application obviously isn't expecting the suffix.

To prove this I tried it in Java, with the two versions

conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works

Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.

EDIT Later investigation shows that it's the http package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http and use the dart:io HttpClient directly. You end up with a bit of boilerplate which is normally handled for you by http.

Working example below:

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
  String url =
      'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  Map map = {
    'data': {'apikey': '12345678901234567890'},
  };

  print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Access Control Origin Header error using Axios in React Web throwing error in Chrome

!!! I had a similar problem and I found that in my case the withCredentials: true in the request was activating the CORS check while issuing the same in the header would avoid the check:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMIssingAllowCredentials

do not use withCredentials: true but set 'Access-Control-Allow-Credentials':true in the headers

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

_x000D_
_x000D_
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
data.push(feed);_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Instead of :

_x000D_
_x000D_
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_
    data.push(my_json[i]);_x000D_
}_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

How do I get rid of the b-prefix in a string in python?

I got it done by only encoding the output using utf-8. Here is the code example

new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''

with open(file_name, 'a', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(text)

i.e: do not encode when collecting data from api, encode the output (print or write) only.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Correctly Parsing JSON in Swift 3

Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:

  1. Here is our JSON. We can use optional JSON or usual. I'm using optional in our example:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
  1. Helper functions. We need to write them only once and then reuse with any dictionary:
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in
        { f(a, $0) }
    }
}

/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
    return json.flatMap {
        cast($0[key])
    }
}

/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
    return curry(extract)(key)
}

/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
    associativity: right
    higherThan: AssignmentPrecedence
    lowerThan: TernaryPrecedence
}

/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
    return f(a)
}

/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
    return a as? B
}
  1. And here is our magic - extract the value:
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound

Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.

Getting "Cannot call a class as a function" in my React Project

I faced this error when I imported the wrong class and referred to wrong store while using mobx in react-native.

I faced error in this snippet :

import { inject, Observer } from "mobx-react";

@inject ("counter")
@Observer

After few corrections like as below snippet. I resolved my issue like this way.

import { inject, observer } from "mobx-react";

@inject("counterStore")
@observer

What was actually wrong,I was using the wrong class instead of observer I used Observer and instead of counterStore I used counter. I solved my issue like this way.

Is it safe to expose Firebase apiKey to the public?

The API key exposure creates a vulnerability when user/password sign up is enabled. There is an open API endpoint that takes the API key and allows anyone to create a new user account. They then can use this new account to log in to your Firebase Auth protected app or use the SDK to auth with user/pass and run queries.

I've reported this to Google but they say it's working as intended.

If you can't disable user/password accounts you should do the following: Create a cloud function to auto disable new users onCreate and create a new DB entry to manage their access.

Ex: MyUsers/{userId}/Access: 0

exports.addUser = functions.auth.user().onCreate(onAddUser);
exports.deleteUser = functions.auth.user().onDelete(onDeleteUser);

Update your rules to only allow reads for users with access > 1.

On the off chance the listener function doesn't disable the account fast enough then the read rules will prevent them from reading any data.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

How to force Docker for a clean build of an image

In some extreme cases, your only way around recurring build failures is by running:

docker system prune

The command will ask you for your confirmation:

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all networks not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N]

This is of course not a direct answer to the question, but might save some lives... It did save mine.

Forward X11 failed: Network error: Connection refused

you should install a x server such as XMing. and keep the x server is running. config your putty like this :Connection-Data-SSH-X11-Enable X11 forwarding should be checked. and X display location : localhost:0

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Posting 2021 answer in JSON using openapi 3.0.0:

{
  "openapi": "3.0.0",
  ...
  "servers": [
    {
      "url": "/"
    }
  ],
  ...
  "paths": {
    "/skills": {
      "put": {
        "security": [
           {
              "bearerAuth": []
           }
        ],
       ...
  },


  "components": {        
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}

Docker Compose wait for container X before starting Y

you can also just add it to the command option eg.

command: bash -c "sleep 5; start.sh"

https://github.com/docker/compose/issues/374#issuecomment-156546513

to wait on a port you can also use something like this

command: bash -c "while ! curl -s rabbitmq:5672 > /dev/null; do echo waiting for xxx; sleep 3; done; start.sh"

to increment the waiting time you can hack a bit more:

command: bash -c "for i in {1..100} ; do if ! curl -s rabbitmq:5672 > /dev/null ; then echo waiting on rabbitmq for $i seconds; sleep $i; fi; done; start.sh"

How to know a Pod's own IP address from inside a container in the Pod?

kubectl get pods -o wide

Give you a list of pods with name, status, ip, node...

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

Adding subscribers to a list using Mailchimp's API v3

I got it working. I was adding the authentication to the header incorrectly:

$apikey = '<api_key>';
            $auth = base64_encode( 'user:'.$apikey );

            $data = array(
                'apikey'        => $apikey,
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array(
                    'FNAME' => $name
                )
            );
            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                        'Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

            $result = curl_exec($ch);

            var_dump($result);
            die('Mailchimp executed');

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of text like in a messenger

 >>> stex[40]
 array(['Know the famous thing ...

and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:

 >>> stex = (df5.ix[0:,[11]]).values
 >>> a_str = ','.join(str(x) for x in stex)
 >>> a_str = a_str.split()
 >>> fd2 = nltk.FreqDist(a_str)
 >>> fd2.most_common(50)

Open web in new tab Selenium + Python

Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:

def newTab(driver, url="about:blank"):
    wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
    handle = wnd["value"]["handle"]
    driver.switch_to.window(handle)
    driver.get(url) # changes the handle
    return driver.current_window_handle

No connection could be made because the target machine actively refused it 127.0.0.1

I had a similar issue, trying to run a WCF-based HttpSelfHostServer in Debug under my VisualStudio 2013. I tried every possible direction (turn off firewall, disabling IIS completely to eliminate the possibility localhost port is taken by some other service, etc.).

Eventually, what "did the trick" (solved the problem) was re-running VisualStudio 2013 as Administrator.

Amazing.

Simulate a specific CURL in PostMan

As mentioned in multiple answers above you can import the cURL in POSTMAN directly. But if URL is authorized (or is not working for some reason) ill suggest you can manually add all the data points as JSON in your postman body. take the API URL from the cURL.

for the Authorization part- just add an Authorization key and base 64 encoded string as value.

example:

curl -u rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a \ https://api.razorpay.com/v1/orders -X POST \ --data "amount=50000" \ --data "currency=INR" \ --data "receipt=Receipt #20" \ --data "payment_capture=1" https://api.razorpay.com/v1/orders

{ "amount": "5000", "currency": "INR", "receipt": "Receipt #20", "payment_capture": "1" }

Headers: Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J where "cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J" is the encoded form of "rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a"`

small tip: for encoding, you can easily go to your chrome console (right-click => inspect) and type : btoa("string you want to encode") ( or use postman basic authorization)

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

Plotting a fast Fourier transform in Python

The important thing about fft is that it can only be applied to data in which the timestamp is uniform (i.e. uniform sampling in time, like what you have shown above).

In case of non-uniform sampling, please use a function for fitting the data. There are several tutorials and functions to choose from:

https://github.com/tiagopereira/python_tips/wiki/Scipy%3A-curve-fitting http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

If fitting is not an option, you can directly use some form of interpolation to interpolate data to a uniform sampling:

https://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html

When you have uniform samples, you will only have to wory about the time delta (t[1] - t[0]) of your samples. In this case, you can directly use the fft functions

Y    = numpy.fft.fft(y)
freq = numpy.fft.fftfreq(len(y), t[1] - t[0])

pylab.figure()
pylab.plot( freq, numpy.abs(Y) )
pylab.figure()
pylab.plot(freq, numpy.angle(Y) )
pylab.show()

This should solve your problem.

Python and JSON - TypeError list indices must be integers not str

First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Using a HTTP debugging proxy can cause this - such as Fiddler.

I was loading a PFX certificate from a local file (authentication to Apple.com) and it failed because Fiddler wasn't able to pass this certificate on.

Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.

Simple C example of doing an HTTP POST and consuming the response

After weeks of research. I came up with the following code. I believe this is the bare minimum needed to make a secure connection with SSL to a web server.

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>

#define APIKEY "YOUR_API_KEY"
#define HOST "YOUR_WEB_SERVER_URI"
#define PORT "443"

int main() {

    //
    //  Initialize the variables
    //
    BIO* bio;
    SSL* ssl;
    SSL_CTX* ctx;

    //
    //   Registers the SSL/TLS ciphers and digests.
    //
    //   Basically start the security layer.
    //
    SSL_library_init();

    //
    //  Creates a new SSL_CTX object as a framework to establish TLS/SSL
    //  or DTLS enabled connections
    //
    ctx = SSL_CTX_new(SSLv23_client_method());

    //
    //  -> Error check
    //
    if (ctx == NULL)
    {
        printf("Ctx is null\n");
    }

    //
    //   Creates a new BIO chain consisting of an SSL BIO
    //
    bio = BIO_new_ssl_connect(ctx);

    //
    //  Use the variable from the beginning of the file to create a 
    //  string that contains the URL to the site that you want to connect
    //  to while also specifying the port.
    //
    BIO_set_conn_hostname(bio, HOST ":" PORT);

    //
    //   Attempts to connect the supplied BIO
    //
    if(BIO_do_connect(bio) <= 0)
    {
        printf("Failed connection\n");
        return 1;
    }
    else
    {
        printf("Connected\n");
    }

    //
    //  The bare minimum to make a HTTP request.
    //
    char* write_buf = "POST / HTTP/1.1\r\n"
                      "Host: " HOST "\r\n"
                      "Authorization: Basic " APIKEY "\r\n"
                      "Connection: close\r\n"
                      "\r\n";

    //
    //   Attempts to write len bytes from buf to BIO
    //
    if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0)
    {
        //
        //  Handle failed writes here
        //
        if(!BIO_should_retry(bio))
        {
            // Not worth implementing, but worth knowing.
        }

        //
        //  -> Let us know about the failed writes
        //
        printf("Failed write\n");
    }

    //
    //  Variables used to read the response from the server
    //
    int size;
    char buf[1024];

    //
    //  Read the response message
    //
    for(;;)
    {
        //
        //  Get chunks of the response 1023 at the time.
        //
        size = BIO_read(bio, buf, 1023);

        //
        //  If no more data, then exit the loop
        //
        if(size <= 0)
        {
            break;
        }

        //
        //  Terminate the string with a 0, to let know C when the string 
        //  ends.
        //
        buf[size] = 0;

        //
        //  ->  Print out the response
        //
        printf("%s", buf);
    }

    //
    //  Clean after ourselves
    //
    BIO_free_all(bio);
    SSL_CTX_free(ctx);

    return 0;
}

The code above will explain in details how to establish a TLS connection with a remote server.

Important note: this code doesn't check if the public key was signed by a valid authority. Meaning I don't use root certificates for validation. Don't forget to implement this check otherwise you won't know if you are connecting the right website

When it comes to the request itself. It is nothing more then writing the HTTP request by hand.

You can also find under this link an explanation how to instal openSSL in your system, and how to compile the code so it uses the secure library.

How to get value by class name in JavaScript or jquery?

If you get the the text inside the element use

Text()

$(".element-classname").text();

In your code:

$('.HOEnZb').text();

if you want get all the data including html Tags use:

html()

 $(".element-classname").html();

In your code:

$('.HOEnZb').html();

Hope it helps:)

Find column whose name contains a specific string

# select columns containing 'spike'
df.filter(like='spike', axis=1)

You can also select by name, regular expression. Refer to: pandas.DataFrame.filter

TypeError: ObjectId('') is not JSON serializable

Posting here as I think it may be useful for people using Flask with pymongo. This is my current "best practice" setup for allowing flask to marshall pymongo bson data types.

mongoflask.py

from datetime import datetime, date

import isodate as iso
from bson import ObjectId
from flask.json import JSONEncoder
from werkzeug.routing import BaseConverter


class MongoJSONEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, (datetime, date)):
            return iso.datetime_isoformat(o)
        if isinstance(o, ObjectId):
            return str(o)
        else:
            return super().default(o)


class ObjectIdConverter(BaseConverter):
    def to_python(self, value):
        return ObjectId(value)

    def to_url(self, value):
        return str(value)

app.py

from .mongoflask import MongoJSONEncoder, ObjectIdConverter

def create_app():
    app = Flask(__name__)
    app.json_encoder = MongoJSONEncoder
    app.url_map.converters['objectid'] = ObjectIdConverter

    # Client sends their string, we interpret it as an ObjectId
    @app.route('/users/<objectid:user_id>')
    def show_user(user_id):
        # setup not shown, pretend this gets us a pymongo db object
        db = get_db()

        # user_id is a bson.ObjectId ready to use with pymongo!
        result = db.users.find_one({'_id': user_id})

        # And jsonify returns normal looking json!
        # {"_id": "5b6b6959828619572d48a9da",
        #  "name": "Will",
        #  "birthday": "1990-03-17T00:00:00Z"}
        return jsonify(result)


    return app

Why do this instead of serving BSON or mongod extended JSON?

I think serving mongo special JSON puts a burden on client applications. Most client apps will not care using mongo objects in any complex way. If I serve extended json, now I have to use it server side, and the client side. ObjectId and Timestamp are easier to work with as strings and this keeps all this mongo marshalling madness quarantined to the server.

{
  "_id": "5b6b6959828619572d48a9da",
  "created_at": "2018-08-08T22:06:17Z"
}

I think this is less onerous to work with for most applications than.

{
  "_id": {"$oid": "5b6b6959828619572d48a9da"},
  "created_at": {"$date": 1533837843000}
}

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

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

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

This app won't run unless you update Google Play Services (via Bazaar)

 just change it to 

compile 'com.google.android.gms:play-services-maps:9.6.0'
compile 'com.google.android.gms:play-services-location:9.6.0'

this works for me current version is 10.0.1

Missing styles. Is the correct theme chosen for this layout?

What I usually do is the following: a Gradle Clean, Rebuild and Sync all my Gradle files. After that I restart Android Studio, and I go to:

Select Theme -> Project Themes -> AppTheme

uncaught syntaxerror unexpected token U JSON

In my case it was trying to call JSON.parse() on an AJAX variable before the XHRResponse came back. EG:

var response = $.get(URL that returns a valid JSON string);
var data = JSON.parse(response.responseText);

I replaced that with an example out of the jQuery site for $.get:

<script type="text/javascript"> 
    var jqxhr = $.get( "https://jira.atlassian.com/rest/api/2/project", function() {
          alert( "success" );
        })
          .done(function() {
//insert code to assign the projects from Jira to a div.
                jqxhr = jqxhr.responseJSON;
                console.log(jqxhr);
                var div = document.getElementById("products");
                for (i = 0; i < jqxhr.length; i++) {
                    console.log(jqxhr[i].name);
                    div.innerHTML += "<b>Product: " + jqxhr[i].name + "</b><BR/>Key: " + jqxhr[i].key + "<BR/>";
                }
                console.log(div);
            alert( "second success" );
          })
          .fail(function() {
            alert( "error" );
          })
          .always(function() {
            alert( "finished" );
          });

        // Perform other work here ...

        // Set another completion function for the request above
        jqxhr.always(function() {
          alert( "second finished" );
        });
</script>

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

PHP cURL vs file_get_contents

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

Delete all local git branches

git branch -d [branch name] for local delete

git branch -D [branch name] also for local delete but forces it

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

How to Troubleshoot Intermittent SQL Timeout Errors

Since I do troubleshooting everyday as a part of my job, here is what I would like to do:

  1. Since it's SQL Server 2008 R2, you can run SQLDiag which comes as a part of the product. You can refer books online for more details. In brief, capture Server Side trace and blocker script.

  2. Once trace is captured, look for "Attention" event. That would be the spid which has received the error. If you filter by SPID, you would see RPC:Completed event before "Attention". Check the time over there. Is that time 30 seconds? If yes, then client waited for 30 second to get response from SQL and got "timed out" [This is client setting as SQL would never stop and connection]

  3. Now, check if the query which was running really should take 30 seconds?

  4. If yes then tune the query or increase the timeout setting from the client.

  5. If no then this query must be waiting for some resources (blocked)

  6. At this point go back to Blocker Script and check the time frame when "Attention" came

Above is assuming that issue is with SQL Server not network related!

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

Place API key in Headers or URL

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

How to create a CPU spike with a bash command

I went through the Internet to find something like it and found this very handy cpu hammer script.

#!/bin/sh

# unixfoo.blogspot.com

if [ $1 ]; then
    NUM_PROC=$1
else
    NUM_PROC=10
fi

for i in `seq 0 $((NUM_PROC-1))`; do
    awk 'BEGIN {for(i=0;i<10000;i++)for(j=0;j<10000;j++);}' &
done

Python, Matplotlib, subplot: How to set the axis range?

If you know the exact axis you want, then

pylab.ylim([0,1000])

works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft as in the question, then add this after your plot command:

length = (len(fft)) pylab.ylim([0,length])

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

Tricks to manage the available memory in an R session

Ensure you record your work in a reproducible script. From time-to-time, reopen R, then source() your script. You'll clean out anything you're no longer using, and as an added benefit will have tested your code.

Set new id with jQuery

I just wrote a quick plugin to run a test using your same snippet and it works fine

$.fn.test = function() {
      return this.each(function(){
        var new_id = 5;
        $(this).attr('id',   this.id + '_' + new_id);
        $(this).attr('name', this.name + '_' + new_id);
        $(this).attr('value', 'test');
      });
    };

$(document).ready(function() {
    $('#field_id').test()
});

<body>
  <div id="container">

  <input type="text" name="field_name" id="field_id" value="meh" />
  </div>
</body>

So I can only presume something else is going on in your code. Can you provide some more details?

How do I make the method return type generic?

what about

public class Animal {
    private Map<String,<T extends Animal>> friends = new HashMap<String,<T extends Animal>>();

    public <T extends Animal> void addFriend(String name, T animal){
        friends.put(name,animal);
    }

    public <T extends Animal> T callFriend(String name){
        return friends.get(name);
    }
}

What's the best way to check if a String represents an integer in Java?

several answers here saying to try parsing to an integer and catching the NumberFormatException but you should not do this.

That way would create exception object and generates a stack trace each time you called it and it was not an integer.

A better way with Java 8 would be to use a stream:

boolean isInteger = returnValue.chars().allMatch(Character::isDigit);

How to determine total number of open/active connections in ms sql server 2005

This shows the number of connections per each DB:

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame

And this gives the total:

SELECT 
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE 
    dbid > 0

If you need more detail, run:

sp_who2 'Active'

Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

Authenticating in PHP using LDAP through Active Directory

Importing a whole library seems inefficient when all you need is essentially two lines of code...

$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
  // log them in!
} else {
  // error message
}

What is the iPhone 4 user-agent?

You can use:

http://whatsmyuseragent.com/

To find your user agent (Google: "What is my user agent" gives this answer)

Detecting locked tables (locked by LOCK TABLE)

You can create your own lock with GET_LOCK(lockName,timeOut)

If you do a GET_LOCK(lockName, 0) with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName) then all other threads performing a GET_LOCK() will get a value of 0 which will tell them that the lock is being held by another thread.

However this won't work if you don't have all threads calling GET_LOCK() before locking tables. The documentation for locking tables is here

Hope that helps!

wampserver doesn't go green - stays orange

After trying all the other solutions posted here (Skype, updates to C++ Redistributable), I found that another process was using port 80. The culprit was Microsoft Internet Information Server (IIS). You can stop the service from the command line on Windows 7/Vista:

net stop was /y

Or set the service to not start automatically by going to Services: click Start, click Control Panel, click Performance and Maintenance, click Administrative Tools, and then double-click Services. There, locate "WAS Service" and "World Wide Web Publication Service" and set them to manual or deactivate them completely.

Then restart the WAMP server.

More info: http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/

Turn a number into star rating display using jQuery and CSS

If you only have to support modern browsers, you can get away with:

  • No images;
  • Mostly static css;
  • Nearly no jQuery or Javascript;

You only need to convert the number to a class, e.g. class='stars-score-50'.

First a demo of "rendered" markup:

_x000D_
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
_x000D_
_x000D_

Then a demo that uses a wee bit of code:

_x000D_
_x000D_
$(function() {_x000D_
  function addScore(score, $domElement) {_x000D_
    $("<span class='stars-container'>")_x000D_
      .addClass("stars-" + score.toString())_x000D_
      .text("?????")_x000D_
      .appendTo($domElement);_x000D_
  }_x000D_
_x000D_
  addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
_x000D_
_x000D_

The biggest downsides of this solution are:

  1. You need the stars inside the element to generate correct width;
  2. There's no semantic markup, e.g. you'd prefer the score as text inside the element;
  3. It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise width on a pseudo-element).

To fix this the solution above can be easily tweaked. The :before and :after bits need to become actual elements in the DOM (so we need some JS for that).

The latter is left as an excercise for the reader.

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

Use This its is very useful for your solution:

  1. Start > Control Panel > Administrative Tools > Services
  2. Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties
  3. In the window then select 'disabled' in the startup type combo

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

How to change the floating label color of TextInputLayout

you should change your colour here

<style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#673AB7</item>
        <item name="colorPrimaryDark">#512DA8</item>
        <item name="colorAccent">#FF4081</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>

WAMP Cannot access on local network 403 Forbidden

To expand on RiggsFolly’s answer—or for anyone who is facing the same issue but is using Apache 2.2 or below—this format should work well:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
Allow from localhost
Allow from 192.168
Allow from 10
Satisfy Any

For more details on the format changes for Apache 2.4, the official Upgrading to 2.2 from 2.4 page is pretty clear & concise. Key point being:

The old access control idioms should be replaced by the new authentication mechanisms, although for compatibility with old configurations, the new module mod_access_compat is provided.

Which means, system admins around the world don’t necessarily have to panic about changing Apache 2.2 configs to be 2.4 compliant just yet.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

Search for one value in any column of any table inside a database

There is a nice script available on http://www.reddyss.com/SQLDownloads.aspx

To be able to use it on any database you can create it like in: http://nickstips.wordpress.com/2010/10/18/sql-making-a-stored-procedure-available-to-all-databases/

Not sure if there is other way.

To use it then use something like this:

use name_of_database

EXEC spUtil_SearchText 'value_searched', 0, 0

How to update an object in a List<> in C#

Can also try.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();

CSS selector for a checked radio button's label

If your input is a child element of the label and you have more than one labels, you can combine @Mike's trick with Flexbox + order.

enter image description here

_x000D_
_x000D_
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }



/* style the switch */

:root {
  --radio-size: 14px;
}

.switchLabel input.switch  {
  width: var(--radio-size);
  height: var(--radio-size);
  border-radius: 50%;
  border: 1px solid #999999;
  box-sizing: border-box;
  outline: none;
  -webkit-appearance: inherit;
  -moz-appearance: inherit;
  appearance: inherit;
  
  box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}

.switchLabel input.switch:checked {
  box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
  <input type="checkbox" class="switch" />
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
_x000D_
_x000D_
_x000D_ asd

html
<label class="switchLabel">
  <input type="checkbox" class="switch"/>
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
css
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }

See it on JSFiddle.

note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.

How to get system time in Java without creating a new Date

Use System.currentTimeMillis() or System.nanoTime().

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

Call child method from parent

First off, let me express that this is generally not the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: dispatch).

But if you must expose an imperative method on a child component, you can use refs. Remember this is an escape hatch and usually indicates a better design is available.

Previously, refs were only supported for Class-based components. With the advent of React Hooks, that's no longer the case

Using Hooks and Function Components (>= [email protected])

_x000D_
_x000D_
const { forwardRef, useRef, useImperativeHandle } = React;_x000D_
_x000D_
// We need to wrap component in `forwardRef` in order to gain_x000D_
// access to the ref object that is assigned using the `ref` prop._x000D_
// This ref is passed as the second parameter to the function component._x000D_
const Child = forwardRef((props, ref) => {_x000D_
_x000D_
  // The component instance will be extended_x000D_
  // with whatever you return from the callback passed_x000D_
  // as the second argument_x000D_
  useImperativeHandle(ref, () => ({_x000D_
_x000D_
    getAlert() {_x000D_
      alert("getAlert from Child");_x000D_
    }_x000D_
_x000D_
  }));_x000D_
_x000D_
  return <h1>Hi</h1>;_x000D_
});_x000D_
_x000D_
const Parent = () => {_x000D_
  // In order to gain access to the child component instance,_x000D_
  // you need to assign it to a `ref`, so we call `useRef()` to get one_x000D_
  const childRef = useRef();_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <Child ref={childRef} />_x000D_
      <button onClick={() => childRef.current.getAlert()}>Click</button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Parent />,_x000D_
  document.getElementById('root')_x000D_
);
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Documentation for useImperativeHandle() is here:

useImperativeHandle customizes the instance value that is exposed to parent components when using ref.

Using Class Components (>= [email protected])

_x000D_
_x000D_
const { Component } = React;_x000D_
_x000D_
class Parent extends Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.child = React.createRef();_x000D_
  }_x000D_
_x000D_
  onClick = () => {_x000D_
    this.child.current.getAlert();_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        <Child ref={this.child} />_x000D_
        <button onClick={this.onClick}>Click</button>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class Child extends Component {_x000D_
  getAlert() {_x000D_
    alert('getAlert from Child');_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return <h1>Hello</h1>;_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById('root'));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Legacy API (<= [email protected])

For historical purposes, here's the callback-based style you'd use with React versions before 16.3:

_x000D_
_x000D_
const { Component } = React;_x000D_
const { render } = ReactDOM;_x000D_
_x000D_
class Parent extends Component {_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        <Child ref={instance => { this.child = instance; }} />_x000D_
        <button onClick={() => { this.child.getAlert(); }}>Click</button>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class Child extends Component {_x000D_
  getAlert() {_x000D_
    alert('clicked');_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <h1>Hello</h1>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
render(_x000D_
  <Parent />,_x000D_
  document.getElementById('app')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

Python - use list as function parameters

This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.

def some_func(a_char, a_float, a_something):
    print a_char

params = ['a', 3.4, None]
some_func(*params)

>> a

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

Shortcut key for commenting out lines of Python code in Spyder

on Windows F9 to run single line

Select the lines which you want to run on console and press F9 button for multi line

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

you can find the username and password details in your {tomcat installation directory}/conf/tomcat-users.xml

Editing dictionary values in a foreach loop

Along with the other answers, I thought I'd note that if you get sortedDictionary.Keys or sortedDictionary.Values and then loop over them with foreach, you also go through in sorted order. This is because those methods return System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection or SortedDictionary<TKey,TValue>.ValueCollection objects, which maintain the sort of the original dictionary.

Pass array to mvc Action via AJAX

If you are migrating to ASP.NET Core MVC from .Net Framework MVC like I was, things have changed slightly. The ajax call must be on the raw object using stringify so rather than passing data of { vals: arrayOfValues } it should be JSON.stringify(arrayOfValues) as follows:

$.ajax({
   url: 'controller/myaction',
   data: JSON.stringify(arrayOfValues),
   success: function(data) { /* Whatever */ }
});

The other change that has been made in ASP.NET Core is to prevent cross-site request forgery so for calls to an MVC action from an ajax method the [FromBody] atribute must be applied to the action parameter as follows:

public ActionResult MyAction([FromBody] IEnumerable<int> arrayOfValues )

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

insert echo into the specific html element like div which has an id or class

if yo want to place in an div like i have same work and i do it like

<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';  
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>

How to change users in TortoiseSVN

When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing --username and --password does not work, and the SVN client does not cache your credentials on disk, too.

When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.

Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:

  1. Start Control Panel | Credential Manager on the client computer.
  2. Click Add a Windows Credential.
  3. As Internet or network address enter the FQDN of the server machine (e.g., svn.example.com).
  4. As Username enter your domain account's username in the DOMAIN\Username format.
  5. Complete the password field and click OK.

Now when you will contact https://svn.example.com/svn/MyRepo or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.

enter image description here

make *** no targets specified and no makefile found. stop

If after ./configure Makefile.in and Makefile.am are generated and make fail (by showing this following make: *** No targets specified and no makefile found. Stop.) so there is something not configured well, to solve it, first run "autoconf" commande to solve wrong configuration then re-run "./configure" commande and finally "make"

How do I get column datatype in Oracle with PL-SQL with low privileges?

ALL_TAB_COLUMNS should be queryable from PL/SQL. DESC is a SQL*Plus command.

SQL> desc all_tab_columns;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)
 TABLE_NAME                                NOT NULL VARCHAR2(30)
 COLUMN_NAME                               NOT NULL VARCHAR2(30)
 DATA_TYPE                                          VARCHAR2(106)
 DATA_TYPE_MOD                                      VARCHAR2(3)
 DATA_TYPE_OWNER                                    VARCHAR2(30)
 DATA_LENGTH                               NOT NULL NUMBER
 DATA_PRECISION                                     NUMBER
 DATA_SCALE                                         NUMBER
 NULLABLE                                           VARCHAR2(1)
 COLUMN_ID                                          NUMBER
 DEFAULT_LENGTH                                     NUMBER
 DATA_DEFAULT                                       LONG
 NUM_DISTINCT                                       NUMBER
 LOW_VALUE                                          RAW(32)
 HIGH_VALUE                                         RAW(32)
 DENSITY                                            NUMBER
 NUM_NULLS                                          NUMBER
 NUM_BUCKETS                                        NUMBER
 LAST_ANALYZED                                      DATE
 SAMPLE_SIZE                                        NUMBER
 CHARACTER_SET_NAME                                 VARCHAR2(44)
 CHAR_COL_DECL_LENGTH                               NUMBER
 GLOBAL_STATS                                       VARCHAR2(3)
 USER_STATS                                         VARCHAR2(3)
 AVG_COL_LEN                                        NUMBER
 CHAR_LENGTH                                        NUMBER
 CHAR_USED                                          VARCHAR2(1)
 V80_FMT_IMAGE                                      VARCHAR2(3)
 DATA_UPGRADED                                      VARCHAR2(3)
 HISTOGRAM                                          VARCHAR2(15)

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

Html.Textbox VS Html.TextboxFor

Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

What is the difference between association, aggregation and composition?

Association is generalized concept of relations. It includes both Composition and Aggregation.

Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.

Both denotes relationship between object and only differ in their strength.

Trick to remember the difference : has A -Aggregation and Own - cOmpositoin

enter image description here

Now let observe the following image

relations

enter image description here

Analogy:

Composition: The following picture is image composition i.e. using individual images making one image.
enter image description here

Aggregation : collection of image in single location

enter image description here

For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

How do I remove a CLOSE_WAIT socket connection

You can forcibly close sockets with ss command; the ss command is a tool used to dump socket statistics and displays information in similar fashion (although simpler and faster) to netstat.

To kill any socket in CLOSE_WAIT state, run this (as root)

$ ss --tcp state CLOSE-WAIT --kill

Java BigDecimal: Round to the nearest whole value

Here's an awfully complicated solution, but it works:

public static BigDecimal roundBigDecimal(final BigDecimal input){
    return input.round(
        new MathContext(
            input.toBigInteger().toString().length(),
            RoundingMode.HALF_UP
        )
    );
}

Test Code:

List<BigDecimal> bigDecimals =
    Arrays.asList(new BigDecimal("100.12"),
        new BigDecimal("100.44"),
        new BigDecimal("100.50"),
        new BigDecimal("100.75"));
for(final BigDecimal bd : bigDecimals){
    System.out.println(roundBigDecimal(bd).toPlainString());
}

Output:

100
100
101
101

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I got the error with a space in a Sheet Name:

using (var range = _excelApp.Range["Sheet Name Had Space!$A$1"].WithComCleanup())

I fixed it by putting single quotes around Sheet Names with spaces:

using (var range = _excelApp.Range["'Sheet Name Had Space'!$A$1"].WithComCleanup())

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

If you are trying to execute your program/application from the command prompt. Just make sure to restart your cmd after you have changed the JAVA_HOME var. Very simple but easily missed sometimes.

How do I save a stream to a file in C#?

You must not use StreamReader for binary files (like gifs or jpgs). StreamReader is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)

Why do you need to use a StreamReader at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?

EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

To use it to dump a stream to a file, for example:

using (Stream file = File.Create(filename))
{
    CopyStream(input, file);
}

Note that Stream.CopyTo was introduced in .NET 4, serving basically the same purpose.

What is the purpose of willSet and didSet in Swift?

You can also use the didSet to set the variable to a different value. This does not cause the observer to be called again as stated in Properties guide. For example, it is useful when you want to limit the value as below:

let minValue = 1

var value = 1 {
    didSet {
        if value < minValue {
            value = minValue
        }
    }
}

value = -10 // value is minValue now.

Generate random numbers using C++11 random library

Here is some resource you can read about pseudo-random number generator.

https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Basically, random numbers in computer need a seed (this number can be the current system time).

Replace

std::default_random_engine generator;

By

std::default_random_engine generator(<some seed number>);

Why have header files and .cpp files?

Because C, where the concept originated, is 30 years old, and back then, it was the only viable way to link together code from multiple files.

Today, it's an awful hack which totally destroys compilation time in C++, causes countless needless dependencies (because class definitions in a header file expose too much information about the implementation), and so on.

How can I decrypt a password hash in PHP?

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

In your case, run the SQL query using only the username:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

And do the password validation in PHP using a code that is similar to the example above.

The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

What should every programmer know about security?

  1. Why is is important.
  2. It is all about trade-offs.
  3. Cryptography is largely a distraction from security.

How do I list / export private keys from a keystore?

For android development, to convert keystore created in eclipse ADT into public key and private key used in SignApk.jar:

export private key:

keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der
openssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem

edit private.rsa.pem and leave "-----BEGIN PRIVATE KEY-----" to "-----END PRIVATE KEY-----" paragraph, then:

openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der

export public key:

keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der

sign apk:

java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk

How do I get the coordinates of a mouse click on a canvas element?

Using jQuery in 2016, to get click coordinates relative to the canvas, I do:

$(canvas).click(function(jqEvent) {
    var coords = {
        x: jqEvent.pageX - $(canvas).offset().left,
        y: jqEvent.pageY - $(canvas).offset().top
    };
});

This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.

Note that if your canvas is scaled then these coordinates are not the same as canvas logical coordinates. To get those, you would also do:

var logicalCoords = {
    x: coords.x * (canvas.width / $(canvas).width()),
    y: coords.y * (canvas.height / $(canvas).height())
}

Split a List into smaller lists of N size

public static IEnumerable<IEnumerable<T>> SplitIntoSets<T>
    (this IEnumerable<T> source, int itemsPerSet) 
{
    var sourceList = source as List<T> ?? source.ToList();
    for (var index = 0; index < sourceList.Count; index += itemsPerSet)
    {
        yield return sourceList.Skip(index).Take(itemsPerSet);
    }
}

Raising a number to a power in Java

You should use below method-

Math.pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

What is two way binding?

Actually emberjs supports two-way binding, which is one of the most powerful feature for a javascript MVC framework. You can check it out where it mentioning binding in its user guide.

for emberjs, to create two way binding is by creating a new property with the string Binding at the end, then specifying a path from the global scope:

App.wife = Ember.Object.create({
  householdIncome: 80000
});

App.husband = Ember.Object.create({
  householdIncomeBinding: 'App.wife.householdIncome'
});

App.husband.get('householdIncome'); // 80000

// Someone gets raise.
App.husband.set('householdIncome', 90000);
App.wife.get('householdIncome'); // 90000

Note that bindings don't update immediately. Ember waits until all of your application code has finished running before synchronizing changes, so you can change a bound property as many times as you'd like without worrying about the overhead of syncing bindings when values are transient.

Hope it helps in extend of original answer selected.

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

Removing black dots from li and ul

CSS :

ul{
list-style-type:none;
}

You can take a look at W3School

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

my helpful code for others(just one aspx to do text area post)::

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>

<!DOCTYPE html>

    enter code here

<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script src="angular-sanitize.min.js"></script>
    <script>
        angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
            //$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
            $scope.htmlContent = '';
            $scope.withoutSanitize = function () {
                return $sce.getTrustedHtml($scope.htmlContent);
            };
            $scope.postMessage = function () {
                var ValidContent = $sce.trustAsHtml($scope.htmlContent);

                //your ajax call here
            };
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Example to show posting valid content to server with two way binding
        <div ng-controller="x">
            <p ng-bind-html="htmlContent"></p>
            <textarea ng-model="htmlContent" ng-trim="false"></textarea>
            <button ng-click="postMessage()">Send</button>
        </div>
    </form>
</body>
</html>

Disabled href tag

You can use one of these solutions:

HTML

<a>link</a>

JavaScript

<a href="javascript:function() { return false; }">link</a>
<a href="/" onclick="return false;">link</a>

CSS

<a href="www.page.com" disabled="disabled">link</a>

<style type="text/css">
    a[disabled="disabled"] {
        pointer-events: none;
    }
</style>

How to Add a Dotted Underline Beneath HTML Text

Reformatted the answer by @epascarello:

_x000D_
_x000D_
u.dotted {_x000D_
  border-bottom: 1px dashed #999;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
_x000D_
_x000D_

Connecting to SQL Server using windows authentication

I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked

connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Found out that there's no bug there. Just add:

<base href="/" />

to your <head />.

Get the generated SQL statement from a SqlCommand object?

If you're using SQL Server, you could use SQL Server Profiler (if you have it) to view the command string that is actually executed. That would be useful for copy/paste testing purpuses but not for logging I'm afraid.

How do I enable php to work with postgresql?

in my case there are 2 php.ini, I had to uncomment extension pdo_pgsql in both php.ini

  1. in php folder
  2. in apache folder

both inside in wamp folder

How to print current date on python3?

This function allows you to get the date and time in lots of formats (see the bottom of this post).

# Get the current date or time
def getdatetime(timedateformat='complete'):
    from datetime import datetime
    timedateformat = timedateformat.lower()
    if timedateformat == 'day':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2]
    elif timedateformat == 'month':
        return ((str(datetime.now())).split(' ')[0]).split('-')[1]
    elif timedateformat == 'year':
        return ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'minute':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
    elif timedateformat == 'second':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
    elif timedateformat == 'millisecond':
        return (str(datetime.now())).split('.')[1]
    elif timedateformat == 'yearmonthday':
        return (str(datetime.now())).split(' ')[0]
    elif timedateformat == 'daymonthyear':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[1] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hourminutesecond':
        return ((str(datetime.now())).split(' ')[1]).split('.')[0]
    elif timedateformat == 'secondminutehour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'complete':
        return str(datetime.now())
    elif timedateformat == 'datetime':
        return (str(datetime.now())).split('.')[0]
    elif timedateformat == 'timedate':
        return ((str(datetime.now())).split('.')[0]).split(' ')[1] + ' ' + ((str(datetime.now())).split('.')[0]).split(' ')[0]

To obtain the time or date, just use getdatetime("<TYPE>"), replacing <TYPE> with one of the following arguments:

All example outputs use this model information: 25-11-2017 03:23:56.477017

Argument Meaning Example output
day Get the current day 25
month Get the current month 11
year Get the current year 2017
hour Get the current hour 03
minute Get the current minute 23
second Get the current second 56
millisecond Get the current millisecond 477017
yearmonthday Get the year, month and day 2017-11-25
daymonthyear Get the day, month and year 25-11-2017
hourminutesecond Get the hour, minute and second 03:23:56
secondminutehour Get the second, minute and hour 56:23:03
complete Get the complete date and time 2017-11-25 03:23:56.477017
datetime Get the date and time 2017-11-25 03:23:56
timedate Get the time and date 03:23:56 2017-11-25

Javascript receipt printing using POS Printer

You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/

Python : List of dict, if exists increment a dict value, if not append a new dict

Using the default works, but so does:

urls[url] = urls.get(url, 0) + 1

using .get, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

IE9 jQuery AJAX with CORS returns "Access is denied"

I just made all requests JSONP because it was the only solution for all of our supported browsers (IE7+ and the regulars). Mind you, your answer technically works for IE9 so you have the correct answer.

How do I convert between ISO-8859-1 and UTF-8 in Java?

In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found.

To transcode text:

byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");

or

byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");

You can exercise more control by using the lower-level Charset APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.

How to discover number of *logical* cores on Mac OS X?

The following command gives you all information about your CPU

$ sysctl -a | sort | grep cpu

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

SyntaxError: Cannot use import statement outside a module

Recently have the issue. The fix which work for me was to added this to babel.config.json in the plugins section

["@babel/plugin-transform-modules-commonjs", {
    "allowTopLevelThis": true,
    "loose": true,
    "lazy": true
  }],

I had some imported module with // and the error "cannot use import outside a module".

Adding rows dynamically with jQuery

This will get you close, the add button has been removed out of the table so you might want to consider this...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDIT To empty a value of a textbox after insert..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

Scraping data from website using vba

This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.

Sub ExtractLastValue()

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Visible = True

objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")

Do
DoEvents
Loop Until objIE.readystate = 4

MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText

End Sub

And if you are new to web scraping please read this blog post.

Web Scraping - Basics

And also there are various techniques to extract data from web pages. This article explain few of them with examples.

Web Scraping - Collecting Data From a Webpage

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

In one of my projects there was a nuget packages with higher version of System.Net.Http. and in my startup project there reference to System.Net.Http v 4.0.0 , i just installed System.Net.Http nuget package in my startup project and the problem solved

Best way to use PHP to encrypt and decrypt passwords?

Security warning: This code is not secure.

working example

define('SALT', 'whateveryouwant'); 

function encrypt($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

$encryptedmessage = encrypt("your message"); 
echo decrypt($encryptedmessage); 

How to configure port for a Spring Boot application

in the file application.properties add the following: server.port=8888 THE PROT NEEDED ALWAYS MENTIONED HERE

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

Why is super.super.method(); not allowed in Java?

Calling of super.super.method() make sense when you can't change code of base class. This often happens when you are extending an existing library.

Ask yourself first, why are you extending that class? If answer is "because I can't change it" then you can create exact package and class in your application, and rewrite naughty method or create delegate:

package com.company.application;

public class OneYouWantExtend extends OneThatContainsDesiredMethod {

    // one way is to rewrite method() to call super.method() only or 
    // to doStuff() and then call super.method()

    public void method() {
        if (isDoStuff()) {
            // do stuff
        }
        super.method();
    }

    protected abstract boolean isDoStuff();


    // second way is to define methodDelegate() that will call hidden super.method()

    public void methodDelegate() {
        super.method();
    }
    ...
}

public class OneThatContainsDesiredMethod {

    public void method() {...}
    ...
}

For instance, you can create org.springframework.test.context.junit4.SpringJUnit4ClassRunner class in your application so this class should be loaded before the real one from jar. Then rewrite methods or constructors.

Attention: This is absolute hack, and it is highly NOT recommended to use but it's WORKING! Using of this approach is dangerous because of possible issues with class loaders. Also this may cause issues each time you will update library that contains overwritten class.

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

Most Developers log-in to server(I assume you r having user-name and password for mysql database) then from Bash they switch to mysql> prompt then use the command below(which doesn’t work

mysql -h localhost -u root -p

What needs to be done is use the above command in the bash prompt--> on doing so it will ask for password if given it will take directly to mysql prompt and

then database, table can be created one by one

I faced similar deadlock so sharing the experience

How To Convert A Number To an ASCII Character?

To get ascii to a number, you would just cast your char value into an integer.

char ascii = 'a'
int value = (int)ascii

Variable value will now have 97 which corresponds to the value of that ascii character

(Use this link for reference) http://www.asciitable.com/index/asciifull.gif

log4j vs logback

Your decision should be based on

  • your actual need for these "more features"; and
  • your expected cost of implementing the change.

You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."

If your application requires a very sophisticated logging framework, you may want to consider why.

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This version allows you to have more than one case y or Y, n or N

  1. Optionally: Repeat the question until an approve question is provided

  2. Optionally: Ignore any other answer

  3. Optionally: Exit the terminal if you want

    confirm() {
        echo -n "Continue? y or n? "
        read REPLY
        case $REPLY in
        [Yy]) echo 'yup y' ;; # you can change what you do here for instance
        [Nn]) break ;;        # exit case statement gracefully
        # Here are a few optional options to choose between
        # Any other answer:
    
        # 1. Repeat the question
        *) confirm ;;
    
        # 2. ignore
        # *) ;;
    
        # 3. Exit terminal
        # *) exit ;;
    
        esac
        # REPLY=''
    }
    

Notice this too: On the last line of this function clear the REPLY variable. Otherwise if you echo $REPLY you will see it is still set until you open or close your terminal or set it again.

Cassandra cqlsh - connection refused

The first and foremost step to diagnose is to check the Cassandra logs.

Find out the process and there will be hints in the command line parameters to tell you where the logs files are.

ps aux | grep cassandra

In my case, it was in default location /etc/cassandra/conf/cassandra.yaml (if you installed the yum package).

Make sure three things are configured and configured the same host/ip.

  1. listen_address - you may leave it blank it will default to hostname/first IP binding with eth0 network card
  2. rpc_address - this is optional, leave blank if you want it to be same as listen_address
  3. seeds - this is a double quoted string of comma-separated list of IP addresses or hostnames. This was default to a hardcoded "127.0.0.1", changing it to the same as list_address and restart of Cassandra service made it work for me.

References:

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

Replace all elements of Python NumPy Array that are greater than some value

Another way is to use np.place which does in-place replacement and works with multidimentional arrays:

import numpy as np

# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)

# replace 0 with -10
np.place(arr, arr == 0, -10)

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Add a auto increment primary key to existing table in oracle

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

UPDATE table_name
   SET new_pk_column = sequence_name.nextval;

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

ALTER TABLE table_name
  ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )

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

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

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

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

When do I need to use a semicolon vs a slash in Oracle SQL?

Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".

See

http://ss64.com/ora/syntax-sqlplus.html

Rule of thumb would be to use slash with things that do BEGIN .. END or where you can use CREATE OR REPLACE.

For inserts that need to be unique use

INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT 
                  FROM my_table
                  WHERE <identify data that you are trying to insert>)

How to open .dll files to see what is written inside?

Open .dll file with visual studio. Or resource editor.

How to access my localhost from another PC in LAN?

after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:

  <Directory "c:/wamp/www"><!-- maybe other url-->

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
</Directory>

3- Change to: Deny from none
like this:

<Directory "c:/wamp/www">

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from none
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

4- Restart Apache
Don't forget restart Apache or all servises!!!

Creating temporary files in bash

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)

WCF - How to Increase Message Size Quota

I solve the problem ...as follows

    <bindings>
  <netTcpBinding>
    <binding name="ECMSBindingConfig" closeTimeout="00:10:00" openTimeout="00:10:00"
      sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647" portSharingEnabled="true">
      <readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
          maxStringContentLength="2147483647" maxDepth="2147483647"
          maxBytesPerRead="2147483647" />
      <security mode="None" />
    </binding>
  </netTcpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="ECMSServiceBehavior">
      <dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="2147483647" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceTimeouts transactionTimeout="00:10:00" />
      <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="100"
        maxConcurrentInstances="100" />
    </behavior>
  </serviceBehaviors>
</behaviors>

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

What's the difference between primitive and reference types?

The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.

Primatives:

boolean

character

byte

short

integer

long

float

double

Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types

Defining a variable with or without export

export NAME=value for settings and variables that have meaning to a subprocess.

NAME=value for temporary or loop variables private to the current shell process.

In more detail, export marks the variable name in the environment that copies to a subprocesses and their subprocesses upon creation. No name or value is ever copied back from the subprocess.

  • A common error is to place a space around the equal sign:

    $ export FOO = "bar"  
    bash: export: `=': not a valid identifier
    
  • Only the exported variable (B) is seen by the subprocess:

    $ A="Alice"; export B="Bob"; echo "echo A is \$A. B is \$B" | bash
    A is . B is Bob
    
  • Changes in the subprocess do not change the main shell:

    $ export B="Bob"; echo 'B="Banana"' | bash; echo $B
    Bob
    
  • Variables marked for export have values copied when the subprocess is created:

    $ export B="Bob"; echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash &
    [1] 3306
    $ B="Banana"; echo '(sleep 30; echo "Subprocess 2 has B=$B")' | bash 
    Subprocess 1 has B=Bob
    Subprocess 2 has B=Banana
    [1]+  Done         echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash
    
  • Only exported variables become part of the environment (man environ):

     $ ALICE="Alice"; export BOB="Bob"; env | grep "ALICE\|BOB"
     BOB=Bob
    

So, now it should be as clear as is the summer's sun! Thanks to Brain Agnew, alexp, and William Prusell.

Proxy with express.js

First install express and http-proxy-middleware

npm install express http-proxy-middleware --save

Then in your server.js

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();
app.use(express.static('client'));

// Add middleware for http proxying 
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);

// Render your site
const renderIndex = (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);

app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');
});

In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.

http://localhost:3000/api/login redirect to http://localhost:8080/api/login

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.

Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.

Update

You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.

XML and XPath is another viable solution:

SELECT ...
FROM Table
JOIN (
   SELECT x.value(N'.',N'uniqueidentifier') as guid
   FROM @values.nodes(N'/guids/guid') t(x)) as guids
 ON Table.guid = guids.guid;

How do you completely remove the button border in wpf?

You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.

Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

How to recover Git objects damaged by hard disk failure?

The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.

So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository

I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:

"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."

You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:

"git reflog expire --expire=now --all && git gc --prune=now --aggressive"

When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:

"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"

Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".

What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)

I hope this saves someone's time

How to wait until an element is present in Selenium?

WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));

you can use this as some time before loading whole page code gets executed and throws and error. time is in second

How to programmatically set the SSLContext of a JAX-WS client?

You can move your proxy authentication and ssl staff to soap handler

  port = new SomeService().getServicePort();
  Binding binding = ((BindingProvider) port).getBinding();
  binding.setHandlerChain(Collections.<Handler>singletonList(new ProxyHandler()));

This is my example, do all network ops

  class ProxyHandler implements SOAPHandler<SOAPMessageContext> {
    static class TrustAllHost implements HostnameVerifier {
      public boolean verify(String urlHostName, SSLSession session) {
        return true;
      }
    }

    static class TrustAllCert implements X509TrustManager {
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }

      public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
      }

      public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
      }
    }

    private SSLSocketFactory socketFactory;

    public SSLSocketFactory getSocketFactory() throws Exception {
      // just an example
      if (socketFactory == null) {
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCert() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        socketFactory = sc.getSocketFactory();
      }

      return socketFactory;
    }

    @Override public boolean handleMessage(SOAPMessageContext msgCtx) {
      if (!Boolean.TRUE.equals(msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)))
        return true;

      HttpURLConnection http = null;

      try {
        SOAPMessage outMessage = msgCtx.getMessage();
        outMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
        // outMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, true); // Not working. WTF?

        ByteArrayOutputStream message = new ByteArrayOutputStream(2048);
        message.write("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8"));
        outMessage.writeTo(message);

        String endpoint = (String) msgCtx.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
        URL service = new URL(endpoint);

        Proxy proxy = Proxy.NO_PROXY;
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("{proxy.url}", {proxy.port}));

        http = (HttpURLConnection) service.openConnection(proxy);
        http.setReadTimeout(60000); // set your timeout
        http.setConnectTimeout(5000);
        http.setUseCaches(false);
        http.setDoInput(true);
        http.setDoOutput(true);
        http.setRequestMethod("POST");
        http.setInstanceFollowRedirects(false);

        if (http instanceof HttpsURLConnection) {
          HttpsURLConnection https = (HttpsURLConnection) http;
          https.setHostnameVerifier(new TrustAllHost());
          https.setSSLSocketFactory(getSocketFactory());
        }

        http.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
        http.setRequestProperty("Content-Length", Integer.toString(message.size()));
        http.setRequestProperty("SOAPAction", "");
        http.setRequestProperty("Host", service.getHost());
        //http.setRequestProperty("Proxy-Authorization", "Basic {proxy_auth}");

        InputStream in = null;
        OutputStream out = null;

        try {
          out = http.getOutputStream();
          message.writeTo(out);
        } finally {
          if (out != null) {
            out.flush();
            out.close();
          }
        }

        int responseCode = http.getResponseCode();
        MimeHeaders responseHeaders = new MimeHeaders();
        message.reset();

        try {
          in = http.getInputStream();
          IOUtils.copy(in, message);
        } catch (final IOException e) {
          try {
            in = http.getErrorStream();
            IOUtils.copy(in, message);
          } catch (IOException e1) {
            throw new RuntimeException("Unable to read error body", e);
          }
        } finally {
          if (in != null)
            in.close();
        }

        for (Map.Entry<String, List<String>> header : http.getHeaderFields().entrySet()) {
          String name = header.getKey();

          if (name != null)
            for (String value : header.getValue())
              responseHeaders.addHeader(name, value);
        }

        SOAPMessage inMessage = MessageFactory.newInstance()
          .createMessage(responseHeaders, new ByteArrayInputStream(message.toByteArray()));

        if (inMessage == null)
          throw new RuntimeException("Unable to read server response code " + responseCode);

        msgCtx.setMessage(inMessage);
        return false;
      } catch (Exception e) {
        throw new RuntimeException("Proxy error", e);
      } finally {
        if (http != null)
          http.disconnect();
      }
    }

    @Override public boolean handleFault(SOAPMessageContext context) {
      return false;
    }

    @Override public void close(MessageContext context) {
    }

    @Override public Set<QName> getHeaders() {
      return Collections.emptySet();
    }
  }

It use UrlConnection, you can use any library you want in handler. Have fun!

Difference between <input type='submit' /> and <button type='submit'>text</button>

In summary :

<input type="submit">

<button type="submit"> Submit </button>

Both by default will visually draw a button that performs the same action (submit the form).

However, it is recommended to use <button type="submit"> because it has better semantics, better ARIA support and it is easier to style.

How to simulate a touch event in Android?

MotionEvent is generated only by touching the screen.

Search code inside a Github project

Google allows you to search in the project, but not the code :(

site:https://github.com/CreateJS/EaselJS test

How to generate JAXB classes from XSD?

cxf does great support for this kind of stuff e.g

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-xjc-plugin</artifactId>
    <version>2.3.0</version>
    <configuration>
      <extensions>
        <extension>org.apache.cxf.xjcplugins:cxf-xjc-dv:2.3.0</extension>
      </extensions>
    </configuration>
    <executions>
      <execution>
        <id>generate-sources-trans</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>xsdtojava</goal>
        </goals>
        <configuration>
          <sourceRoot>${basedir}/src/main/java</sourceRoot>
          <xsdOptions>
            <xsdOption>
              <xsd>src/main/resources/xxx.xsd</xsd>
            </xsdOption>
          </xsdOptions>
        </configuration>
      </execution>
    </executions>
  </plugin>

Check if value exists in enum in TypeScript

According to sandersn the best way to do this would be:

Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)

Populate nested array in mongoose

You can do this using $lookup aggregation as well and probably the best way as now populate is becoming extinct from the mongo

Project.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(id) } },
  { "$lookup": {
    "from": Pages.collection.name,
    "let": { "pages": "$pages" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [ "$_id", "$$pages" ] } } },
      { "$lookup": {
        "from": Component.collection.name,
        "let": { "components": "$components" },
        "pipeline": [
          { "$match": { "$expr": { "$in": [ "$_id", "$$components" ] } } },
        ],
        "as": "components"
      }},
    ],
    "as": "pages"
  }}
])

Google Maps how to Show city or an Area outline

From what I searched, at this moment there is no option from Google in the Maps API v3 and there is an issue on the Google Maps API going back to 2008. There are some older questions - Add "Search Area" outline onto google maps result , Google has started highlighting search areas in Pink color. Is this feature available in Google Maps API 3? and you might find some newer answers here with updated information, but this is not a feature.

What you can do is draw shapes on your map - but for this you need to have the coordinates of the borders of your region.

Now, in order to get the administrative area boundaries, you will have to do a little work: http://www.gadm.org/country (if you are lucky and there is enough level of detail available there).

On this website you can locally download a file (there are many formats available) with the .kmz extension. Unzip it and you will have a .kml file which contains most administrative areas (cities, villages).

  <?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Schema name="x" id="x">
    <SimpleField name="ID_0" type="int"></SimpleField>
    <SimpleField name="ISO" type="string"></SimpleField>
    <SimpleField name="NAME_0" type="string"></SimpleField>
    <SimpleField name="ID_1" type="string"></SimpleField>
    <SimpleField name="NAME_1" type="string"></SimpleField>
    <SimpleField name="ID_2" type="string"></SimpleField>
    <SimpleField name="NAME_2" type="string"></SimpleField>
    <SimpleField name="TYPE_2" type="string"></SimpleField>
    <SimpleField name="ENGTYPE_2" type="string"></SimpleField>
    <SimpleField name="NL_NAME_2" type="string"></SimpleField>
    <SimpleField name="VARNAME_2" type="string"></SimpleField>
    <SimpleField name="Shape_Length" type="float"></SimpleField>
    <SimpleField name="Shape_Area" type="float"></SimpleField>
</Schema>
<Folder><name>x</name>
  <Placemark>
    <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
    <ExtendedData><SchemaData schemaUrl="#x">
        <SimpleData name="ID_0">186</SimpleData>
        <SimpleData name="ISO">ROU</SimpleData>
        <SimpleData name="NAME_0">Romania</SimpleData>
        <SimpleData name="ID_1">1</SimpleData>
        <SimpleData name="NAME_1">Alba</SimpleData>
        <SimpleData name="ID_2">1</SimpleData>
        <SimpleData name="NAME_2">Abrud</SimpleData>
        <SimpleData name="TYPE_2">Comune</SimpleData>
        <SimpleData name="ENGTYPE_2">Commune</SimpleData>
        <SimpleData name="VARNAME_2">Oras Abrud</SimpleData>
        <SimpleData name="Shape_Length">0.2792904164402</SimpleData>
        <SimpleData name="Shape_Area">0.00302673357146115</SimpleData>
    </SchemaData></ExtendedData>
      <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>23.117561340332031,46.269237518310547 23.108898162841797,46.265365600585937 23.107486724853629,46.264305114746207 23.104681015014762,46.260105133056641 23.101633071899471,46.250000000000114 23.100803375244254,46.249053955078239 23.097520828247184,46.246582031250114 23.0965576171875,46.245487213134822 23.095674514770508,46.244930267334098 23.092174530029354,46.243438720703182 23.088010787963924,46.240383148193473 23.083366394043082,46.238204956054801 23.075212478637809,46.234935760498047 23.071325302123967,46.239696502685547 23.070602416992131,46.241668701171875 23.069700241088924,46.242824554443416 23.068435668945369,46.243541717529354 23.066627502441406,46.244037628173771 23.064964294433651,46.246234893798885 23.062850952148437,46.247486114501953 23.0626220703125,46.248153686523438 23.062761306762752,46.250873565673942 23.061862945556697,46.255172729492301 23.061449050903434,46.256267547607422 23.05998420715332,46.258060455322322 23.057676315307674,46.259838104248161 23.055141448974666,46.262714385986442 23.053401947021484,46.264244079589901 23.049621582031193,46.266674041748161 23.043565750122013,46.268516540527457 23.041521072387695,46.269458770751953 23.034791946411076,46.270542144775334 23.027051925659293,46.27105712890625 23.025453567504826,46.271255493164063 23.022710800170898,46.272083282470703 23.020351409912053,46.271331787109432 23.018688201904297,46.270687103271598 23.015596389770508,46.270793914794922 23.014116287231502,46.271579742431697 23.009817123413143,46.275333404541016 23.006668090820426,46.277061462402401 23.004106521606445,46.279254913330135 23.001775741577205,46.282882690429688 23.005559921264648,46.283077239990348 23.009967803955135,46.28415679931652 23.014947891235465,46.286224365234489 23.019996643066463,46.28900146484375 23.024263381958121,46.292709350586051 23.027633666992301,46.295299530029411 23.028041839599609,46.295692443847656 23.032444000244197,46.294342041015625 23.03491401672369,46.293315887451229 23.044847488403434,46.290401458740234 23.047790527343807,46.28928375244152 23.053009033203239,46.288627624511719 23.057231903076229,46.288341522216797 23.064565658569393,46.287548065185547 23.070388793945426,46.286254882812614 23.075139999389592,46.284847259521428 23.075983047485465,46.284801483154411 23.085800170898494,46.28253173828125 23.098115921020451,46.280982971191406 23.099718093872127,46.280590057373104 23.105833053588981,46.278388977050838 23.112155914306641,46.274082183837947 23.116207122802791,46.270610809326172 23.117561340332031,46.269237518310547</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
  </Placemark>
</Folder>
</Document></kml>

From this point on, when the user searches for a city/village, you simply retrieve the boundaries and draw around those coordinates on the map - https://developers.google.com/maps/documentation/javascript/overlays#Polygons

I hope this helps you! Good luck!

border on Google Map using the above coordinates UPDATE: I made the borders of this city using the coordinates above

                   var ctaLayer = new google.maps.KmlLayer({
                       url: 'https://www.dropbox.com/s/0grhlim3q4572jp/ROU_adm2%20-%20Copy.kml?dl=1'
  });
  ctaLayer.setMap(map);

(I put a small kml file on my Dropbox containing the borders of a single city)

Note that this uses the Google built in KML system, in which it their server gets the file, computes the view and spits it back to you - it has limited usage and I used it to show you how the borders look. In your application you should be able to parse the coordinates from the kml file, put them in an array (as the polygon documentation tells you - https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays ) and display them.

Note that there will be differences between the borders that Google sets on http://www.google.com/maps and the borders that you will get with this data.

Good luck! enter image description here

UPDATE: http://pastebin.com/x2V1aarJ , http://pastebin.com/Gh55EDW5 These are the javascript files (they were minified, so I used an online tool to make them readable) from the website. If you are not fully satisfied with this my solution, feel free to study them.

Best of luck!

How to stop a vb script running in windows

Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

How to list running screen sessions?

The command screen -list may be what you want.

See the man

Does List<T> guarantee insertion order?

Here are 4 items, with their index

0  1  2  3
K  C  A  E

You want to move K to between A and E -- you might think position 3. You have be careful about your indexing here, because after the remove, all the indexes get updated.

So you remove item 0 first, leaving

0  1  2
C  A  E

Then you insert at 3

0  1  2  3
C  A  E  K

To get the correct result, you should have used index 2. To make things consistent, you will need to send to (indexToMoveTo-1) if indexToMoveTo > indexToMove, e.g.

bool moveUp = (listInstance.IndexOf(itemToMoveTo) > indexToMove);
listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, moveUp ? (itemToMoveTo - 1) : itemToMoveTo);

This may be related to your problem. Note my code is untested!

EDIT: Alternatively, you could Sort with a custom comparer (IComparer) if that's applicable to your situation.

Native query with named parameter fails with "Not all named parameters have been set"

This was a bug fixed in version 4.3.11 https://hibernate.atlassian.net/browse/HHH-2851

EDIT: Best way to execute a native query is still to use NamedParameterJdbcTemplate It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

final List<Long> resultList = namedParameterJdbcTemplate.query(query, 
            mapOfNamedParamters, 
            new RowMapper<Long>() {
        @Override
        public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    });

How to coerce a list object to type 'double'

There are problems with some data. Consider:

as.double(as.character("2.e")) # This results in 2

Another solution:

get_numbers <- function(X) {
    X[toupper(X) != tolower(X)] <- NA
    return(as.double(as.character(X)))
}

Django: save() vs update() to update the database?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.

update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.

Can I call a constructor from another constructor (do constructor chaining) in C++?

C++11: Yes!

C++11 and onwards has this same feature (called delegating constructors).

The syntax is slightly different from C#:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

C++03: No

It is worth pointing out that you can call the constructor of a parent class in your constructor e.g.:

 class A { /* ... */ };
    
    class B : public A
    {
        B() : A()
        {
            // ...
        }
    };

But, no, you can't call another constructor of the same class upto C++03.

Maven : error in opening zip file when running maven

I had a similar problem as well. The fix was a mix of both. I had a problem with asm-3.1 (as mentioned in the blog post linked by Takahiko. That jar was corrupt. I needed to manually get the jar from the maven central repository. Removing it and retrying just got the corrupt jar again. It then still failed on the asm-parent, which was a POM file containing the HTML with a 301. Again, it required manually getting the file myself. You may want to check what settings XML to see if you're set to a different repository, such as a local nexus server.

When the proper way to get the new one fails, manually grab it yourself.

How to run function in AngularJS controller on document ready?

I had a similar situation where I needed to execute a controller function after the view was loaded and also after a particular 3rd-party component within the view was loaded, initialized, and had placed a reference to itself on $scope. What ended up working for me was to setup a watch on this scope property and firing my function only after it was initialized.

// $scope.myGrid property will be created by the grid itself
// The grid will have a loadedRows property once initialized

$scope.$watch('myGrid', function(newValue, oldValue) {
    if (newValue && newValue.loadedRows && !oldValue) {
        initializeAllTheGridThings();
    }
});

The watcher is called a couple of times with undefined values. Then when the grid is created and has the expected property, the initialization function may be safely called. The first time the watcher is called with a non-undefined newValue, oldValue will still be undefined.

How to format a floating number to fixed width in Python

It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings:

numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print(f'{number:9.4f}')

Prints:

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000

Does C# support multiple inheritance?

Like Java (which is what C# was indirectly derived from), C# does not support multiple inhertance.

Which is to say that class data (member variables and properties) can only be inherited from a single parent base class. Class behavior (member methods), on the other hand, can be inherited from multiple parent base interfaces.

Some experts, notably Bertrand Meyer (considered by some to be one of the fathers of object-oreiented programming), think that this disqualifies C# (and Java, and all the rest) from being a "true" object-oriented language.

Using PHP with Socket.io

For 'long-lived connection' you mentioned, you can use Ratchet for PHP. It's a library built based on Stream Socket functions that PHP has supported since PHP 5.

For client side, you need to use WebSocket that HTML5 supported instead of Socket.io (since you know, socket.io only works with node.js).

In case you still want to use Socket.io, you can try this way: - find & get socket.io.js for client to use - work with Ratchet to simulate the way socket.io does on server

Hope this helps!

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

This should be rather a SuperUser question.

Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.

However, the problem seemed to be that I've got two ssh-agents running ;(

The first being /usr/bin/ssh-agent (aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent running.

Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK, using lsof I found the two different ssh-agents and then I was able to load the keys (using ssh-add) into the system's default ssh-agent (ie. /usr/bin/ssh-agent), SourceTree was working again.

How to dynamically insert a <script> tag via jQuery after page load?

Try the following:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

http://api.jquery.com/append

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

TL;DR;
Unicode - (nchar, nvarchar, and ntext)
Non-unicode - (char, varchar, and text).

From MSDN

Collations in SQL Server provide sorting rules, case, and accent sensitivity properties for your data. Collations that are used with character data types such as char and varchar dictate the code page and corresponding characters that can be represented for that data type.

Assuming you are using default SQL collation SQL_Latin1_General_CP1_CI_AS then following script should print out all the symbols that you can fit in VARCHAR since it uses one byte to store one character (256 total) if you don't see it on the list printed - you need NVARCHAR.

declare @i int = 0;
while (@i < 256)
begin
print cast(@i as varchar(3)) + '  '+  char(@i)  collate SQL_Latin1_General_CP1_CI_AS 
print cast(@i as varchar(3)) + '  '+ char(@i)  collate Japanese_90_CI_AS  
set @i = @i+1;
end

If you change collation to lets say japanese you will notice that all the weird European letters turned into normal and some symbols into ? marks.

Unicode is a standard for mapping code points to characters. Because it is designed to cover all the characters of all the languages of the world, there is no need for different code pages to handle different sets of characters. If you store character data that reflects multiple languages, always use Unicode data types (nchar, nvarchar, and ntext) instead of the non-Unicode data types (char, varchar, and text).

Otherwise your sorting will go weird.

How to pass the values from one jsp page to another jsp without submit button?

I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.

You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.

Or else the easiest you could do is use sessions.

<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>

<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">

<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>


$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});

This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/

GET parameters in the URL with CodeIgniter

Now it works ok from CodeIgniter 2.1.0

    //By default CodeIgniter enables access to the $_GET array.  If for some
    //reason you would like to disable it, set 'allow_get_array' to FALSE.

$config['allow_get_array']      = TRUE; 

How to update a record using sequelize for node?

I have used sequelize.js, node.js and transaction in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

Error: Local workspace file ('angular.json') could not be found

I was trying to set my Ionic 4 app to run as a pwa. When I run the command:

ng add @angular/pwa

...got the error message. After some try and error I discovered that when my project was created the start command was wrong. I was using an Ionic 3 version:

ionic start myApp tabs --type=ionic-angular

And the correct is:

ionic start myApp tabs --type=angular

with no 'ionic-' in type. This solved the error.

How to determine the longest increasing subsequence using dynamic programming?

Here's another O(n^2) JAVA implementation. No recursion/memoization to generate the actual subsequence. Just a string array that stores the actual LIS at every stage and an array to store the length of the LIS for each element. Pretty darn easy. Have a look:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Shreyans on 4/16/2015
 */

class LNG_INC_SUB//Longest Increasing Subsequence
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter Numbers Separated by Spaces to find their LIS\n");
        String[] s1=br.readLine().split(" ");
        int n=s1.length;
        int[] a=new int[n];//Array actual of Numbers
        String []ls=new String[n];// Array of Strings to maintain LIS for every element
        for(int i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(s1[i]);
        }
        int[]dp=new int[n];//Storing length of max subseq.
        int max=dp[0]=1;//Defaults
        String seq=ls[0]=s1[0];//Defaults
        for(int i=1;i<n;i++)
        {
            dp[i]=1;
            String x="";
            for(int j=i-1;j>=0;j--)
            {
                //First check if number at index j is less than num at i.
                // Second the length of that DP should be greater than dp[i]
                // -1 since dp of previous could also be one. So we compare the dp[i] as empty initially
                if(a[j]<a[i]&&dp[j]>dp[i]-1)
                {
                    dp[i]=dp[j]+1;//Assigning temp length of LIS. There may come along a bigger LIS of a future a[j]
                    x=ls[j];//Assigning temp LIS of a[j]. Will append a[i] later on
                }
            }
            x+=(" "+a[i]);
            ls[i]=x;
            if(dp[i]>max)
            {
                max=dp[i];
                seq=ls[i];
            }
        }
        System.out.println("Length of LIS is: " + max + "\nThe Sequence is: " + seq);
    }
}

Code in action: http://ideone.com/sBiOQx

Converting milliseconds to minutes and seconds with Javascript

this code will do a better job if you want to show hours, and centiseconds or miliseconds after seconds like 1:02:32.21 and if used in a cell phone the timer will show correct timing even after screen lock.

_x000D_
_x000D_
<div id="timer" style="font-family:monospace;">00:00<small>.00</small></div>_x000D_
_x000D_
<script>_x000D_
var d = new Date();_x000D_
var n = d.getTime();_x000D_
var startTime = n;_x000D_
_x000D_
var tm=0;_x000D_
function updateTimer(){_x000D_
  d = new Date();_x000D_
  n = d.getTime();_x000D_
  var currentTime = n;  _x000D_
  tm = (currentTime-startTime);_x000D_
  _x000D_
  //tm +=1; _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm*10;_x000D_
  _x000D_
  var hours = Math.floor(tm / 1000 / 60 / 60);_x000D_
  var minutes = Math.floor(tm / 60000) % 60;_x000D_
  var seconds =  ((tm / 1000) % 60);_x000D_
  // saca los decimales ej 2 d{0,2}_x000D_
  var seconds = seconds.toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
  var miliseconds = ("00" + tm).slice(-3);_x000D_
  var centiseconds;_x000D_
_x000D_
  _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm/10;_x000D_
_x000D_
_x000D_
  centiseconds = miliseconds/10;_x000D_
  centiseconds = (centiseconds).toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
_x000D_
  minutes = (minutes < 10 ? '0' : '') + minutes;_x000D_
  seconds = (seconds < 10 ? '0' : '') + seconds;_x000D_
  centiseconds = (centiseconds < 10 ? '0' : '') + centiseconds;_x000D_
  hours = hours + (hours > 0 ? ':' : '');_x000D_
  if (hours==0){_x000D_
    hours='';_x000D_
  }_x000D_
_x000D_
  document.getElementById("timer").innerHTML = hours + minutes + ':' + seconds + '<small>.' + centiseconds + '</small>';_x000D_
}_x000D_
_x000D_
var timerInterval = setInterval(updateTimer, 10);_x000D_
// clearInterval(timerInterval);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to SHA1 hash a string in Android?

String.format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2], result[3], 
    result[4], result[5], result[6], result[7],
    result[8], result[9], result[10], result[11],
    result[12], result[13], result[14], result[15],
    result[16], result[17], result[18], result[19]);

Convert UTC to local time in Rails 3

If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb.

Like this:

Rails, by default, will save your time record in UTC even if you specify the current timezone.

config.time_zone = "Singapore"

So this is all you have to do and you're good to go.

How to make spring inject value into a static field

I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person entity class ("entity" as in "something with an identity", for example an JPA entity). A Person instance has friends, and for this Person instance to return its friends, it shall delegate to its repository and query for friends there.

@Entity
public class Person {
    private static PersonRepository personRepository;

    @Id
    @GeneratedValue
    private long id;

    public static void setPersonRepository(PersonRepository personRepository){
        this.personRepository = personRepository;
    }

    public Set<Person> getFriends(){
        return personRepository.getFriends(id);
    }

    ...
}

.

@Repository
public class PersonRepository {

    public Person get Person(long id) {
        // do database-related stuff
    }

    public Set<Person> getFriends(long id) {
        // do database-related stuff
    }

    ...
}

So how did I inject that PersonRepository singleton into the static field of the Person class?

I created a @Configuration, which gets picked up at Spring ApplicationContext construction time. This @Configuration gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct annotation, I catch a hook to do all static field injection logic.

@Configuration
public class StaticFieldInjectionConfiguration {

    @Inject
    private PersonRepository personRepository;

    @PostConstruct
    private void init() {
        Person.setPersonRepository(personRepository);
    }
}

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.

What I did the following was:

  1. enable the 2-step verification to google HERE

  2. Create App Password to be use by your system HERE

  3. I selected Others (custom name) and clicked generate

  4. Went to my env file in laravel and edited this

    [email protected]

    MAIL_PASSWORD=thepasswordgenerated

  5. Restarted my apache server and boom! It works again.

This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.

Android error: Failed to install *.apk on device *: timeout

I have encountered the same problem and tried to change the ADB connection timeout. That did not work. I switched between my PC's USB ports (front -> back) and it fixed the problem!!!

How to remove all numbers from string?

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

Convert xlsx to csv in Linux with command line

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

for i   in *.xlsx; do  libreoffice --headless --convert-to csv "$i" ; done

It takes care of spaces in the filename.

Tried again some years later, and it didn't work. This thread gives some tips, but the quickiest solution was to run as root (or running a sudo libreoffice). Not elegant, but quick.

Use the command scalc.exe in Windows

What is the default boolean value in C#?

Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

Only the following variables are automatically initialized to their default values:

  • Static variables
  • Instance variables of class and struct instances
  • Array elements

The default values are as follows (assigned in default constructor of a class):

  • The default value of a variable of reference type is null.
  • For integer types, the default value is 0
  • For char, the default value is `\u0000'
  • For float, the default value is 0.0f
  • For double, the default value is 0.0d
  • For decimal, the default value is 0.0m
  • For bool, the default value is false
  • For an enum type, the default value is 0
  • For a struct type, the default value is obtained by setting all value type fields to their default values

As far as later parts of your question are conerned:

  • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
  • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.

How does the communication between a browser and a web server take place?

Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.

The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).

The Application Layer

...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.

The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.

The Transport Layer

...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.

Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab

The Internet Layer

...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.

The Network Layer

...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.

For more info:

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

How to generate unique ID with node.js

If some one needs cryptographic-strong UUID, there is solution for that as well.

https://www.npmjs.com/package/generate-safe-id

npm install generate-safe-id

Why not UUIDs?

Random UUIDs (UUIDv4) do not have enough entropy to be universally unique (ironic, eh?). Random UUIDs have only 122 bits of entropy, which suggests that a duplicate will occur after only 2^61 IDs. Additionally, some UUIDv4 implementations do not use a cryptographically strong random number generator.

This library generates 240-bit IDs using the Node.js crypto RNG, suggesting the first duplicate will occur after generating 2^120 IDs. Based on the current energy production of the human race, this threshold will be impossible to cross for the foreseeable future.

var generateSafeId = require('generate-safe-id');

var id = generateSafeId();
// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"

I get Access Forbidden (Error 403) when setting up new alias

I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...

The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf file is below...

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#

##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
    ##ServerName dummy-host.example.com
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs"
    ServerName localhost
</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
    </Directory>
</VirtualHost>

I then updated my C:\windows\System32\drivers\etc\hosts file like this...

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1   dev.middleweek.co.uk
127.0.0.1       localhost

Restart your machine for good measure, open the XAMPP Control Panel and start Apache.

Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk

Hope that helps someone!

And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf to include "Options Indexes" like this...

<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
        Options Indexes
    </Directory>
</VirtualHost>

Cheers, Nick

How do I check the difference, in seconds, between two dates?

if you want to compute differences between two known dates, use total_seconds like this:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0

Using curl POST with variables defined in bash script functions

Here's what actually worked for me, after guidance from answers here:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'

Eloquent: find() and where() usage laravel

Your code looks fine, but there are a couple of things to be aware of:

Post::find($id); acts upon the primary key, if you have set your primary key in your model to something other than id by doing:

protected  $primaryKey = 'slug';

then find will search by that key instead.

Laravel also expects the id to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:

public $incrementing = false;

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

My approach was:

openssl version
OpenSSL 1.0.1e 11 Feb 2013

wget https://www.openssl.org/source/openssl-1.0.2a.tar.gz
wget http://www.linuxfromscratch.org/patches/blfs/svn/openssl-1.0.2a-fix_parallel_build-1.patch
tar xzf openssl-1.0.2a.tar.gz
cd openssl-1.0.2a
patch -Np1 -i ../openssl-1.0.2a-fix_parallel_build-1.patch
./config --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic
make
make install

openssl version
OpenSSL 1.0.2a 19 Mar 2015 

Assigning out/ref parameters in Moq

I struggled with many of the suggestions here before I simple created an instance of a new 'Fake' class that implements whatever interface you are trying to Mock out. Then you can simply set the value of the out parameter with the method itself.

How can I plot separate Pandas DataFrames as subplots?

You can see e.gs. in the documentation demonstrating joris answer. Also from the documentation, you could also set subplots=True and layout=(,) within the pandas plot function:

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot() which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

How can I add a hint text to WPF textbox?

  <Grid>
    <TextBox Name="myTextBox"/>
    <TextBlock>
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=myTextBox, Path=Text.IsEmpty}" Value="True">
                        <Setter Property="Text" Value="Prompt..."/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</Grid>

Get Memory Usage in Android

Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Utilities available only on Linux Operating System.
 * 
 * <p>
 * A typical use is to assign a thread to CPU monitoring:
 * </p>
 * 
 * <pre>
 * &#064;Override
 * public void run() {
 *  while (CpuUtil.monitorCpu) {
 * 
 *      LinuxUtils linuxUtils = new LinuxUtils();
 * 
 *      int pid = android.os.Process.myPid();
 *      String cpuStat1 = linuxUtils.readSystemStat();
 *      String pidStat1 = linuxUtils.readProcessStat(pid);
 * 
 *      try {
 *          Thread.sleep(CPU_WINDOW);
 *      } catch (Exception e) {
 *      }
 * 
 *      String cpuStat2 = linuxUtils.readSystemStat();
 *      String pidStat2 = linuxUtils.readProcessStat(pid);
 * 
 *      float cpu = linuxUtils.getSystemCpuUsage(cpuStat1, cpuStat2);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;total&quot;, Float.toString(cpu));
 *      }
 * 
 *      String[] toks = cpuStat1.split(&quot; &quot;);
 *      long cpu1 = linuxUtils.getSystemUptime(toks);
 * 
 *      toks = cpuStat2.split(&quot; &quot;);
 *      long cpu2 = linuxUtils.getSystemUptime(toks);
 * 
 *      cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;&quot; + pid, Float.toString(cpu));
 *      }
 * 
 *      try {
 *          synchronized (this) {
 *              wait(CPU_REFRESH_RATE);
 *          }
 *      } catch (InterruptedException e) {
 *          e.printStackTrace();
 *          return;
 *      }
 *  }
 * 
 *  Log.i(&quot;THREAD CPU&quot;, &quot;Finishing&quot;);
 * }
 * </pre>
 */
public final class LinuxUtils {

    // Warning: there appears to be an issue with the column index with android linux:
    // it was observed that on most present devices there are actually
    // two spaces between the 'cpu' of the first column and the value of 
    // the next column with data. The thing is the index of the idle 
    // column should have been 4 and the first column with data should have index 1. 
    // The indexes defined below are coping with the double space situation.
    // If your file contains only one space then use index 1 and 4 instead of 2 and 5.
    // A better way to deal with this problem may be to use a split method 
    // not preserving blanks or compute an offset and add it to the indexes 1 and 4.

    private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;

    private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;

    /** Return the first line of /proc/stat or null if failed. */
    public String readSystemStat() {

        RandomAccessFile reader = null;
        String load = null;

        try {
            reader = new RandomAccessFile("/proc/stat", "r");
            load = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return load;
    }

    /**
     * Compute and return the total CPU usage, in percent.
     * 
     * @param start
     *            first content of /proc/stat. Not null.
     * @param end
     *            second content of /proc/stat. Not null.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     * @see {@link #readSystemStat()}
     */
    public float getSystemCpuUsage(String start, String end) {
        String[] stat = start.split("\\s");
        long idle1 = getSystemIdleTime(stat);
        long up1 = getSystemUptime(stat);

        stat = end.split("\\s");
        long idle2 = getSystemIdleTime(stat);
        long up2 = getSystemUptime(stat);

        // don't know how it is possible but we should care about zero and
        // negative values.
        float cpu = -1f;
        if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
            if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
                cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
                cpu *= 100.0f;
            }
        }

        return cpu;
    }

    /**
     * Return the sum of uptimes read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemUptime(String[] stat) {
        /*
         * (from man/5/proc) /proc/stat kernel/system statistics. Varies with
         * architecture. Common entries include: cpu 3357 0 4313 1362393
         * 
         * The amount of time, measured in units of USER_HZ (1/100ths of a
         * second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the
         * right value), that the system spent in user mode, user mode with low
         * priority (nice), system mode, and the idle task, respectively. The
         * last value should be USER_HZ times the second entry in the uptime
         * pseudo-file.
         * 
         * In Linux 2.6 this line includes three additional columns: iowait -
         * time waiting for I/O to complete (since 2.5.41); irq - time servicing
         * interrupts (since 2.6.0-test4); softirq - time servicing softirqs
         * (since 2.6.0-test4).
         * 
         * Since Linux 2.6.11, there is an eighth column, steal - stolen time,
         * which is the time spent in other operating systems when running in a
         * virtualized environment
         * 
         * Since Linux 2.6.24, there is a ninth column, guest, which is the time
         * spent running a virtual CPU for guest operating systems under the
         * control of the Linux kernel.
         */

        // with the following algorithm, we should cope with all versions and
        // probably new ones.
        long l = 0L;

        for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
            if (i != IDLE_SYS_CPU_COLUMN_INDEX ) { // bypass any idle mode. There is currently only one.
                try {
                    l += Long.parseLong(stat[i]);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                    return -1L;
                }
            }
        }

        return l;
    }

    /**
     * Return the sum of idle times read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemIdleTime(String[] stat) {
        try {
            return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }

        return -1L;
    }

    /** Return the first line of /proc/pid/stat or null if failed. */
    public String readProcessStat(int pid) {

        RandomAccessFile reader = null;
        String line = null;

        try {
            reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
            line = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return line;
    }

    /**
     * Compute and return the CPU usage for a process, in percent.
     * 
     * <p>
     * The parameters {@code totalCpuTime} is to be the one for the same period
     * of time delimited by {@code statStart} and {@code statEnd}.
     * </p>
     * 
     * @param start
     *            first content of /proc/pid/stat. Not null.
     * @param end
     *            second content of /proc/pid/stat. Not null.
     * @return the CPU use in percent or -1f if the stats are inverted or on
     *         error
     * @param uptime
     *            sum of user and kernel times for the entire system for the
     *            same period of time.
     * @return 12.7 for a cpu usage of 12.7% or -1 if the value is not available
     *         or an error occurred.
     * @see {@link #readProcessStat(int)}
     */
    public float getProcessCpuUsage(String start, String end, long uptime) {

        String[] stat = start.split("\\s");
        long up1 = getProcessUptime(stat);

        stat = end.split("\\s");
        long up2 = getProcessUptime(stat);

        float ret = -1f;
        if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
            ret = 100.f * (up2 - up1) / (float) uptime;
        }

        return ret;
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (utime +
     * stime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessUptime(String[] stat) {
        return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (cutime +
     * cstime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessIdleTime(String[] stat) {
        return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
    }

    /**
     * Return the total CPU usage, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     */
    public float syncGetSystemCpuUsage(long elapse) {

        String stat1 = readSystemStat();
        if (stat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
        }

        String stat2 = readSystemStat();
        if (stat2 == null) {
            return -1.f;
        }

        return getSystemCpuUsage(stat1, stat2);
    }

    /**
     * Return the CPU usage of a process, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param pid
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 6.32 for a CPU usage of 6.32% or -1 if the value is not
     *         available.
     */
    public float syncGetProcessCpuUsage(int pid, long elapse) {

        String pidStat1 = readProcessStat(pid);
        String totalStat1 = readSystemStat();
        if (pidStat1 == null || totalStat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
            e.printStackTrace();
            return -1.f;
        }

        String pidStat2 = readProcessStat(pid);
        String totalStat2 = readSystemStat();
        if (pidStat2 == null || totalStat2 == null) {
            return -1.f;
        }

        String[] toks = totalStat1.split("\\s");
        long cpu1 = getSystemUptime(toks);

        toks = totalStat2.split("\\s");
        long cpu2 = getSystemUptime(toks);

        return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
    }

}

There are several ways of exploiting this class. You can call either syncGetSystemCpuUsage or syncGetProcessCpuUsage but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.

The class can be customized by a few means. The constant CPU_WINDOW defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load. CPU_REFRESH_RATE is the time between each CPU load measurement. Do not set CPU_REFRESH_RATE to 0 because it will suspend the thread after the first read.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;

public final class CpuUtil {

    private static final int CPU_WINDOW = 1000;

    private static final int CPU_REFRESH_RATE = 100; // Warning: anything but > 0

    private static HandlerThread handlerThread;

    private static TestReport output;

    static {
        output = new TestReport();
        output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
    }

    private static boolean monitorCpu;

    /**
     * Construct the class singleton. This method should be called in
     * {@link Application#onCreate()}
     * 
     * @param dir
     *            the parent directory
     * @param append
     *            mode
     */
    public static void setOutput(File dir, boolean append) {
        try {
            File file = new File(dir, "cpu.txt");
            output.setOutputStream(new FileOutputStream(file, append));
            if (!append) {
                output.println(file.getAbsolutePath());
                output.newLine(1);

                // print header
                _printLine(output, "Process", "CPU%");

                output.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** Start CPU monitoring */
    public static boolean startCpuMonitoring() {
        CpuUtil.monitorCpu = true;

        handlerThread = new HandlerThread("CPU monitoring"); //$NON-NLS-1$
        handlerThread.start();

        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
                while (CpuUtil.monitorCpu) {

                    LinuxUtils linuxUtils = new LinuxUtils();

                    int pid = android.os.Process.myPid();
                    String cpuStat1 = linuxUtils.readSystemStat();
                    String pidStat1 = linuxUtils.readProcessStat(pid);

                    try {
                        Thread.sleep(CPU_WINDOW);
                    } catch (Exception e) {
                    }

                    String cpuStat2 = linuxUtils.readSystemStat();
                    String pidStat2 = linuxUtils.readProcessStat(pid);

                    float cpu = linuxUtils
                            .getSystemCpuUsage(cpuStat1, cpuStat2);
                    if (cpu >= 0.0f) {
                        _printLine(output, "total", Float.toString(cpu));
                    }

                    String[] toks = cpuStat1.split(" ");
                    long cpu1 = linuxUtils.getSystemUptime(toks);

                    toks = cpuStat2.split(" ");
                    long cpu2 = linuxUtils.getSystemUptime(toks);

                    cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
                            cpu2 - cpu1);
                    if (cpu >= 0.0f) {
                        _printLine(output, "" + pid, Float.toString(cpu));
                    }

                    try {
                        synchronized (this) {
                            wait(CPU_REFRESH_RATE);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        return;
                    }
                }

                Log.i("THREAD CPU", "Finishing");
            }

        });

        return CpuUtil.monitorCpu;
    }

    /** Stop CPU monitoring */
    public static void stopCpuMonitoring() {
        if (handlerThread != null) {
            monitorCpu = false;
            handlerThread.quit();
            handlerThread = null;
        }
    }

    /** Dispose of the object and release the resources allocated for it */
    public void dispose() {

        monitorCpu = false;

        if (output != null) {
            OutputStream os = output.getOutputStream();
            if (os != null) {
                Streams.close(os);
                output.setOutputStream(null);
            }

            output = null;
        }
    }

    private static void _printLine(TestReport output, String process, String cpu) {
        output.stampln(process + ";" + cpu);
    }

}

Python: most idiomatic way to convert None to empty string?

We can always avoid type casting in scenarios explained below.

customer = "John"
name = str(customer)
if name is None
   print "Name is blank"
else: 
   print "Customer name : " + name

In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail.

customer = "John" # even though its None still it will work properly.
name = customer
if name is None
   print "Name is blank"
else: 
   print "Customer name : " + str(name)

Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.

How do I list the symbols in a .so file

For Android .so files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf, objdump and nm.

Is there a cross-domain iframe height auto-resizer that works?

I ran into this issue while working on something at work (using React). Basically, we have some external html content that we save into our document table in the database and then insert onto the page under certain circumstances when you're in the Documents dataset.

So, given n inlines, of which up to n could contain external html, we needed to devise a system to automatically resize the iframe of each inline once the content fully loaded in each. After spinning my wheels for a bit, this is how I ended up doing it:

  1. Set a message event listener in the index of our React app which checks for a a specific key that we will set from the sender iframe.
  2. In the component that actually renders the iframes, after inserting the external html into it, I append a <script> tag that will wait for the iframe's window.onload to fire. Once that fires, we use postMessage to send a message to the parent window with information about the iframe id, computed height, etc.
  3. If the origin matches and the key is satisfied in the index listener, grab the DOM id of the iframe that we pass in the MessageEvent object
  4. Once we have the iframe, just set the height from the value that is passed from the iframe postMessage.
// index
if (window.postMessage) {
    window.addEventListener("message", (messageEvent) => {
        if (
            messageEvent.data.origin &&
            messageEvent.data.origin === "company-name-iframe"
        ) {
            const iframe = document.getElementById(messageEvent.data.id)
            // this is the only way to ensure that the height of the iframe container matches its body height
            iframe.style.height = `${messageEvent.data.height}px`
            // by default, the iframe will not expand to fill the width of its parent
            iframe.style.width = "100%"
            // the iframe should take precedence over all pointer events of its immediate parent
            // (you can still click around the iframe to segue, for example, but all content of the iframe
            // will act like it has been directly inserted into the DOM)
            iframe.style.pointerEvents = "all"
            // by default, iframes have an ugly web-1.0 border
            iframe.style.border = "none"
        }
    })
}
// in component that renders n iframes
<iframe
    id={`${props.id}-iframe`}
    src={(() => {
        const html = [`data:text/html,${encodeURIComponent(props.thirdLineData)}`]
        if (window.parent.postMessage) {
            html.push(
                `
                <script>
                window.onload = function(event) {
                    window.parent.postMessage(
                        {
                            height: document.body.scrollHeight,
                            id: "${props.id}-iframe",
                            origin: "company-name-iframe",
                        },
                        "${window.location.origin}"
                    );
                };
                </script>
                `
            )
        }

        return html.join("\n")
    })()}
    onLoad={(event) => {
        // if the browser does not enforce a cross-origin policy,
        // then just access the height directly instead
        try {
            const { target } = event
            const contentDocument = (
                target.contentDocument ||
                // Earlier versions of IE or IE8+ where !DOCTYPE is not specified
                target.contentWindow.document
            )
            if (contentDocument) {
                target.style.height = `${contentDocument.body.scrollHeight}px`
            }
        } catch (error) {
            const expectedError = (
                `Blocked a frame with origin "${window.location.origin}" ` +
                `from accessing a cross-origin frame.`
            )
            if (error.message !== expectedError) {
                /* eslint-disable no-console */
                console.err(
                    `An error (${error.message}) ocurred while trying to check to see ` +
                    "if the inner iframe is accessible or not depending " +
                    "on the browser cross-origin policy"
                )
            }
        }
    }}
/>

Flutter plugin not installed error;. When running flutter doctor

IntelliJ IDEA and Android Studio were installed on my machine. I deleted IntelliJ IDEA because i have installed Dart and Flutter plugins on Android Studio. Then flutter doctor command works perfectly, maybe it is useful someone.

Hibernate Criteria for Dates

try this,

    String dateStr = "17-April-2011 19:20:23.707000000 ";
    Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");  

    String newDate = format.format(dateForm);  

    Calendar today = Calendar.getInstance();
    Date fromDate = format.parse(newDate);
    today.setTime(fromDate);
    today.add(Calendar.DAY_OF_YEAR, 1);
    Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
    crit.add(Restrictions.ge("dateFieldName", fromDate));
    crit.add(Restrictions.le("dateFieldName", toDate));
    return crit.list();

Excel to CSV with UTF8 encoding

You can save excel as unicode text, it is tab-delimited.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

A proper REST API should have below components in response

  1. Status Code
  2. Response Body
  3. Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location)

The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.

So if you want to provide the location of resource then using ResponseEntity would be better else it can be avoided.

Consider an example where a API is modified to provide all the options mentioned

// Step 1 - Without any options provided
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public @ResponseBody Spittle spittleById(@PathVariable long id) {
  return spittleRepository.findOne(id);
}

// Step 2- We need to handle exception scenarios, as step 1 only caters happy path.
@ExceptionHandler(SpittleNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Error spittleNotFound(SpittleNotFoundException e) {
  long spittleId = e.getSpittleId();
  return new Error(4, "Spittle [" + spittleId + "] not found");
}

// Step 3 - Now we will alter the service method, **if you want to provide location**
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
public ResponseEntity<Spittle> saveSpittle(
    @RequestBody Spittle spittle,
    UriComponentsBuilder ucb) {

  Spittle spittle = spittleRepository.save(spittle);
  HttpHeaders headers = new HttpHeaders();
  URI locationUri =
  ucb.path("/spittles/")
      .path(String.valueOf(spittle.getId()))
      .build()
      .toUri();
  headers.setLocation(locationUri);
  ResponseEntity<Spittle> responseEntity =
      new ResponseEntity<Spittle>(
          spittle, headers, HttpStatus.CREATED)
  return responseEntity;
}

// Step4 - If you are not interested to provide the url location, you can omit ResponseEntity and go with
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Spittle saveSpittle(@RequestBody Spittle spittle) {
  return spittleRepository.save(spittle);
}

jQuery selectors on custom data attributes using HTML5

Pure/vanilla JS solution (working example here)

// All elements with data-company="Microsoft" below "Companies"
let a = document.querySelectorAll("[data-group='Companies'] [data-company='Microsoft']"); 

// All elements with data-company!="Microsoft" below "Companies"
let b = document.querySelectorAll("[data-group='Companies'] :not([data-company='Microsoft'])"); 

In querySelectorAll you must use valid CSS selector (currently Level3)

SPEED TEST (2018.06.29) for jQuery and Pure JS: test was performed on MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit). Below screenshot shows results for fastest browser (Safari):

enter image description here

PureJS was faster than jQuery about 12% on Chrome, 21% on Firefox and 25% on Safari. Interestingly speed for Chrome was 18.9M operation per second, Firefox 26M, Safari 160.9M (!).

So winner is PureJS and fastest browser is Safari (more than 8x faster than Chrome!)

Here you can perform test on your machine: https://jsperf.com/js-selectors-x

File inside jar is not visible for spring

I had the same issue, ended up using the much more convenient Guava Resources:

Resources.getResource("my.file")

How should I tackle --secure-file-priv in MySQL?

If you're running on Ubuntu, you may also need to configure Apparmor to allow MySQL to write to your folder, e.g. here's my configuration:

Add this line to file /etc/apparmor.d/usr.sbin.mysqld :

/var/lib/mysql-files/* rw

Then add these 2 config lines to /etc/mysql/my.cnf sections:

[client]
loose-local-infile = 1

[mysqld]
secure-file-priv = ""

Here's my SQL:

select id from blahs into outfile '/var/lib/mysql-files/blahs';

It worked for me. Good luck!

Generating Fibonacci Sequence

Here's a simple function to iterate the Fibonacci sequence into an array using arguments in the for function more than the body of the loop:

fib = function(numMax){
    for(var fibArray = [0,1], i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
        x=i+j;
        fibArray.push(x);
    }
    console.log(fibArray);
}

fib(10)

[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

C# compiler error: "not all code paths return a value"

I like to beat dead horses, but I just wanted to make an additional point:

First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).

My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:

bool result = false;
if(conditionA)
{
   DoThings();
   result = true;
}
else if(conditionB)
{
   result = false;
}
else if(conditionC)
{
   DoThings();
   result = true;
}

return result;

So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.

How do I concatenate two lists in Python?

Use a simple list comprehension:

joined_list = [item for list_ in [list_one, list_two] for item in list_]

It has all the advantages of the newest approach of using Additional Unpacking Generalizations - i.e. you can concatenate an arbitrary number of different iterables (for example, lists, tuples, ranges, and generators) that way - and it's not limited to Python 3.5 or later.

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The best way is to use a regular expression, a ternary operator, and the built in .test() method for strings.

I leave you to Google the ins and outs of regular expressions and the test method for strings (they're easy to find), but here we'll use it to test your variable.

/[a-z]/i.test(your-character-here)

This will return TRUE of FALSE based on whether or not your character matches the character set in the regular expression. Our regular expression checks for all letters a-z /[a-z]/ regardless of their case thanks to the i flag.

So, a basic test would be:

var theAnswer = "";
if (/[a-z]/i.test(your-character-here)) {
  theAnswer = "It's a letter."
}

Now we need to determine if it's upper or lower case. So, if we remove the i flag from our regular expression, then our code above will test for lower case letters a-z. And if we stick another if statement in the else of our first if statement, we can test for upper case too by using A-Z. Like this:

var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
  theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
  theAnswer = "It's an upper case letter.";
}

And just in case it's not a letter, we can add a final else statement:

var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
  theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
  theAnswer = "It's an upper case letter.";
} else {
  theAnswer = "It's not a letter."
}

The above code would work. But it's kinda ugly. Instead, we can use a "ternary operator" to replace our if-else statements above. Ternary operators are just shorthand simple ways of coding an if-else. The syntax is easy:

(statement-to-be-evaluated) ? (code-if-true) : (code-if-false)

And these can be nested within each other, too. So a function might look like:

var theAnswer = "";
function whichCase(theLetter) {
  theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : "";
  theAnswer = /[A-Z]/.test(theLetter) ? "It's upper case." : "";
  return(theAnswer);
}

The above code looks good, but won't quite work, because if our character is lower case, theAnswer gets set to "" when it test for uppercase, so lets nest them:

var theAnswer = "";
function whichCase(theLetter) {
  theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : (/[A-Z]/.test(theLetter) ? "It's upper case." : "It's not a letter.");
  return(theAnswer);
}

That will work great! But there's no need to have two seperate lines for setting the variable theAnswer and then returning it. And we should be using let and const rather than var (look those up if you're not sure why). Once we make those changes:

function whichCase(theLetter) {
  return(/[A-Z]/.test(theLetter) ? "It's upper case." : (/[a-z]/.test(theLetter) ? "It's lower case." : "It's not a letter.")); 
}

And we end up with an elegant, concise piece of code. ;)

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

How to extract one column of a csv file

Been using this code for a while, it is not "quick" unless you count "cutting and pasting from stackoverflow".

It uses ${##} and ${%%} operators in a loop instead of IFS. It calls 'err' and 'die', and supports only comma, dash, and pipe as SEP chars (that's all I needed).

err()  { echo "${0##*/}: Error:" "$@" >&2; }
die()  { err "$@"; exit 1; }

# Return Nth field in a csv string, fields numbered starting with 1
csv_fldN() { fldN , "$1" "$2"; }

# Return Nth field in string of fields separated
# by SEP, fields numbered starting with 1
fldN() {
        local me="fldN: "
        local sep="$1"
        local fldnum="$2"
        local vals="$3"
        case "$sep" in
                -|,|\|) ;;
                *) die "$me: arg1 sep: unsupported separator '$sep'" ;;
        esac
        case "$fldnum" in
                [0-9]*) [ "$fldnum" -gt 0 ] || { err "$me: arg2 fldnum=$fldnum must be number greater or equal to 0."; return 1; } ;;
                *) { err "$me: arg2 fldnum=$fldnum must be number"; return 1;} ;;
        esac
        [ -z "$vals" ] && err "$me: missing arg2 vals: list of '$sep' separated values" && return 1
        fldnum=$(($fldnum - 1))
        while [ $fldnum -gt 0 ] ; do
                vals="${vals#*$sep}"
                fldnum=$(($fldnum - 1))
        done
        echo ${vals%%$sep*}
}

Example:

$ CSVLINE="example,fields with whitespace,field3"
$ $ for fno in $(seq 3); do echo field$fno: $(csv_fldN $fno "$CSVLINE");  done
field1: example
field2: fields with whitespace
field3: field3

Good Free Alternative To MS Access

Apache Derby is a nice db alternative.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

An issue with Gulp 4.

For solving this problem try to change your current code:

gulp.task('simpleTaskName', function() {
  // code...
});

for example into this:

gulp.task('simpleTaskName', async function() {
  // code...
});

or into this:

gulp.task('simpleTaskName', done => {
  // code...
  done();
});

How to view table contents in Mysql Workbench GUI?

After displaying the first 1000 records, you can page through them by clicking on the icon beside "Fetch rows:" in the header of the result grid.

What's the difference between text/xml vs application/xml for webservice response

This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):

The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, i try to create config file according FAQ.

BEFORE calling an Init function or put this in a text file called tessdata/configs/digits:

tessedit_char_whitelist 0123456789                 

then, it works by using the command: tesseract imagename outputbase digits

HttpUtility does not exist in the current context

You need to add the System.Web reference;

  1. Right click the "Reference" in the Solution Explorer
  2. Choose "Add Reference"
  3. Check the ".NET" tab is selected.
  4. Search for, and add "System.Web".

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

CreateProcess error=206, The filename or extension is too long when running main() method

I got the same error in android studio. I was able to resolve it by running Build->Clean Project in the IDE.

g++ undefined reference to typeinfo

I've got same error when my interface (with all pure virtual functions) needed one more function and I forgot to "null" it.

I had

class ICommProvider { public: /** * @brief If connection is established, it sends the message into the server. * @param[in] msg - message to be send * @return 0 if success, error otherwise */ virtual int vaSend(const std::string &msg) = 0; /** * @brief If connection is established, it is waiting will server response back. * @param[out] msg is the message received from server * @return 0 if success, error otherwise */ virtual int vaReceive(std::string &msg) = 0; virtual int vaSendRaw(const char *buff, int bufflen) = 0; virtual int vaReceiveRaw(char *buff, int bufflen) = 0; /** * @bief Closes current connection (if needed) after serving * @return 0 if success, error otherwise */ virtual int vaClose(); };

Last vaClose is not virtual so compiled did not know where to get implementation for it and thereby got confused. my message was:

...TCPClient.o:(.rodata+0x38): undefined reference to `typeinfo for ICommProvider'

Simple change from

virtual int vaClose();

to

virtual int vaClose() = 0;

fixed the problem. hope it helps

Regular Expression Validation For Indian Phone Number and Mobile number

For Indian Mobile Numbers

Regular Expression to validate 11 or 12 (starting with 0 or 91) digit number

String regx = "(0/91)?[7-9][0-9]{9}";

String mobileNumber = "09756432848";

check 

if(mobileNumber.matches(regx)){
   "VALID MOBILE NUMBER"
}else{
   "INVALID MOBILE NUMBER"
}

You can check for 10 digit mobile number by removing "(0/91)?" from the regular expression i.e. regx

WinForms DataGridView font size

'   Cell style
 With .DefaultCellStyle
     .BackColor = Color.Black
     .ForeColor = Color.White 
     .Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!,
   System.Drawing.FontStyle.Regular,
   System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      .Alignment = DataGridViewContentAlignment.MiddleRight
 End With

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

Recover from git reset --hard?

(answer suitable for a subset of users)

If you're on (any recent) macOS, and even if you're away from your Time Machine disk, the OS will have saved hourly backups, called local snapshots.

Enter Time Machine and navigate to the file you lost. The OS will then ask you:

The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?

You should be able to recover the file(s) you lost.

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Set session variable in laravel

php artisan make:controller SessionController --plain

Then

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class SessionController extends Controller {
   public function accessSessionData(Request $request) {
      if($request->session()->has('my_name'))
         echo $request->session()->get('my_name');
      else
         echo 'No data in the session';
   }
   public function storeSessionData(Request $request) {
      $request->session()->put('my_name','Ajay kumar');
      echo "Data has been added to session";
   }
   public function deleteSessionData(Request $request) {
      $request->session()->forget('my_name');
      echo "Data has been removed from session.";
   }
}
?>

And all route:

Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');

More Help: How To Set Session In Laravel?

Insert line at middle of file with Python?

A simple but not efficient way is to read the whole content, change it and then rewrite it:

line_index = 3
lines = None
with open('file.txt', 'r') as file_handler:
    lines = file_handler.readlines()

lines.insert(line_index, 'Charlie')

with open('file.txt', 'w') as file_handler:
    file_handler.writelines(lines)

git clone: Authentication failed for <URL>

I had this same issue with my windows 10 machine, I tried many solutions but nor worked until I installed the latest git version. https://git-scm.com/downloads.

How to get device make and model on iOS?

#import <sys/utsname.h>

#define HARDWARE @{@"i386": @"Simulator",@"x86_64": @"Simulator",@"iPod1,1": @"iPod Touch",@"iPod2,1": @"iPod Touch 2nd Generation",@"iPod3,1": @"iPod Touch 3rd Generation",@"iPod4,1": @"iPod Touch 4th Generation",@"iPhone1,1": @"iPhone",@"iPhone1,2": @"iPhone 3G",@"iPhone2,1": @"iPhone 3GS",@"iPhone3,1": @"iPhone 4",@"iPhone4,1": @"iPhone 4S",@"iPhone5,1": @"iPhone 5",@"iPhone5,2": @"iPhone 5",@"iPhone5,3": @"iPhone 5c",@"iPhone5,4": @"iPhone 5c",@"iPhone6,1": @"iPhone 5s",@"iPhone6,2": @"iPhone 5s",@"iPad1,1": @"iPad",@"iPad2,1": @"iPad 2",@"iPad3,1": @"iPad 3rd Generation ",@"iPad3,4": @"iPad 4th Generation ",@"iPad2,5": @"iPad Mini",@"iPad4,4": @"iPad Mini 2nd Generation - Wifi",@"iPad4,5": @"iPad Mini 2nd Generation - Cellular",@"iPad4,1": @"iPad Air 5th Generation - Wifi",@"iPad4,2": @"iPad Air 5th Generation - Cellular"}

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    struct utsname systemInfo;
    uname(&systemInfo);
    NSLog(@"hardware: %@",[HARDWARE objectForKey:[NSString stringWithCString: systemInfo.machine encoding:NSUTF8StringEncoding]]);
}

Round to 5 (or other number) in Python

For integers and with Python 3:

def divround_down(value, step):
    return value//step*step


def divround_up(value, step):
    return (value+step-1)//step*step

Producing:

>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

json.dumps vs flask.jsonify

This is flask.jsonify()

def jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2), mimetype='application/json')

The json module used is either simplejson or json in that order. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.

How to do a FULL OUTER JOIN in MySQL?

Using a union query will remove duplicates, and this is different than the behavior of full outer join that never removes any duplicate:

[Table: t1]                            [Table: t2]
value                                  value
-------                                -------
1                                      1
2                                      2
4                                      2
4                                      5

This is the expected result of full outer join:

value | value
------+-------
1     | 1
2     | 2
2     | 2
Null  | 5
4     | Null
4     | Null

This is the result of using left and right Join with union:

value | value
------+-------
Null  | 5 
1     | 1
2     | 2
4     | Null

[SQL Fiddle]

My suggested query is:

select 
    t1.value, t2.value
from t1 
left outer join t2  
  on t1.value = t2.value
union all      -- Using `union all` instead of `union`
select 
    t1.value, t2.value
from t2 
left outer join t1 
  on t1.value = t2.value
where 
    t1.value IS NULL 

Result of above query that is as same as expected result:

value | value
------+-------
1     | 1
2     | 2
2     | 2
4     | NULL
4     | NULL
NULL  | 5

[SQL Fiddle]


@Steve Chambers: [From comments, with many thanks!]
Note: This may be the best solution, both for efficiency and for generating the same results as a FULL OUTER JOIN. This blog post also explains it well - to quote from Method 2: "This handles duplicate rows correctly and doesn’t include anything it shouldn’t. It’s necessary to use UNION ALL instead of plain UNION, which would eliminate the duplicates I want to keep. This may be significantly more efficient on large result sets, since there’s no need to sort and remove duplicates."


I decided to add another solution that comes from full outer join visualization and math, it is not better that above but more readable:

Full outer join means (t1 ? t2): all in t1 or in t2
(t1 ? t2) = (t1 n t2) + t1_only + t2_only: all in both t1 and t2 plus all in t1 that aren't in t2 and plus all in t2 that aren't in t1:

-- (t1 n t2): all in both t1 and t2
select t1.value, t2.value
from t1 join t2 on t1.value = t2.value    
union all  -- And plus 
-- all in t1 that not exists in t2
select t1.value, null
from t1
where not exists( select 1 from t2 where t2.value = t1.value)    
union all  -- and plus
-- all in t2 that not exists in t1
select null, t2.value
from t2
where not exists( select 1 from t1 where t2.value = t1.value)

[SQL Fiddle]