Programs & Examples On #Asynchronous

Asynchronous programming is a strategy for deferring operations with high latency or low priority, usually in an attempt to improve performance, responsiveness, and / or composability of software. Such strategies are usually employed using some combination of event-driven programming and callbacks, and optionally making use of concurrency through coroutines and / or threads.

SyntaxError: Unexpected token function - Async Await Nodejs

I too had the same problem.

I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.

Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2

This worked for me:

1-

$ npm install -g n

$ n 9.11.2

2-

delete 'node_modules' from the route directory

3-

$ npm install

Still not sure how node/purgecss worked prior to updating.. but this did the trick.

How do you create an asynchronous HTTP request in JAVA?

Based on a link to Apache HTTP Components on this SO thread, I came across the Fluent facade API for HTTP Components. An example there shows how to set up a queue of asynchronous HTTP requests (and get notified of their completion/failure/cancellation). In my case, I didn't need a queue, just one async request at a time.

Here's where I ended up (also using URIBuilder from HTTP Components, example here).

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;

//...

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("myhost.com").setPath("/folder")
    .setParameter("query0", "val0")
    .setParameter("query1", "val1")
    ...;
URI requestURL = null;
try {
    requestURL = builder.build();
} catch (URISyntaxException use) {}

ExecutorService threadpool = Executors.newFixedThreadPool(2);
Async async = Async.newInstance().use(threadpool);
final Request request = Request.Get(requestURL);

Future<Content> future = async.execute(request, new FutureCallback<Content>() {
    public void failed (final Exception e) {
        System.out.println(e.getMessage() +": "+ request);
    }
    public void completed (final Content content) {
        System.out.println("Request completed: "+ request);
        System.out.println("Response:\n"+ content.asString());
    }

    public void cancelled () {}
});

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

function getURL(url){
    return $.ajax({
        type: "GET",
        url: url,
        cache: false,
        async: false
    }).responseText;
}


//example use
var msg=getURL("message.php");
alert(msg);

Wait for a void async method

You don't really need to do anything manually, await keyword pauses the function execution until blah() returns.

private async void SomeFunction()
{
     var x = await LoadBlahBlah(); <- Function is not paused
     //rest of the code get's executed even if LoadBlahBlah() is still executing
}

private async Task<T> LoadBlahBlah()
{
     await DoStuff();  <- function is paused
     await DoMoreStuff();
}

T is type of object blah() returns

You can't really await a void function so LoadBlahBlah() cannot be void

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

JavaScript, Node.js: is Array.forEach asynchronous?

This is a short asynchronous function to use without requiring third party libs

Array.prototype.each = function (iterator, callback) {
    var iterate = function () {
            pointer++;
            if (pointer >= this.length) {
                callback();
                return;
            }
            iterator.call(iterator, this[pointer], iterate, pointer);
    }.bind(this),
        pointer = -1;
    iterate(this);
};

async/await - when to return a Task vs void?

1) Normally, you would want to return a Task. The main exception should be when you need to have a void return type (for events). If there's no reason to disallow having the caller await your task, why disallow it?

2) async methods that return void are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:

static async void f()
{
    await h();
}

static async Task g()
{
    await h();
}

static async Task h()
{
    throw new NotImplementedException();
}

private void button1_Click(object sender, EventArgs e)
{
    f();
}

private void button2_Click(object sender, EventArgs e)
{
    g();
}

private void button3_Click(object sender, EventArgs e)
{
    GC.Collect();
}

f's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException handler runs. You should never let this happen. To use your example,

public static async void AsyncMethod2(int num)
{
    await Task.Factory.StartNew(() => Thread.Sleep(num));
}

Yes, use async and await here, they make sure your method still works correctly if an exception is thrown.

for more information see: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error

WaitAll vs WhenAll

As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll() then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll() then the UI thread is not blocked, and the UI will be updated.

How to check internet access on Android? InetAddress never times out

Very important to check if we have connectivity with isAvailable() and if is possible to establish a connection with isConnected()

private static ConnectivityManager manager;

public static boolean isOnline(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

and you can derterminate the type of network active WiFi :

public static boolean isConnectedWifi(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

or mobile Móvil :

public static boolean isConnectedMobile(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}

don´t forget the permissions:

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

Run PHP Task Asynchronously

Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.

If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.

Why is setState in reactjs Async instead of Sync?

You can call a function after the state value has updated:

this.setState({foo: 'bar'}, () => { 
    // Do something here. 
});

Also, if you have lots of states to update at once, group them all within the same setState:

Instead of:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

Just do this:

this.setState({
    foo: "one",
    bar: "two"
});

How and when to use ‘async’ and ‘await’

The answers here are useful as a general guidance about await/async. They also contain some detail about how await/async is wired. I would like to share some practical experience with you that you should know before using this design pattern.

The term "await" is literal, so whatever thread you call it on will wait for the result of the method before continuing. On the foreground thread, this is a disaster. The foreground thread carries the burden of constructing your app, including views, view models, initial animations, and whatever else you have boot-strapped with those elements. So when you await the foreground thread, you stop the app. The user waits and waits when nothing appears to happen. This provides a negative user experience.

You can certainly await a background thread using a variety of means:

Device.BeginInvokeOnMainThread(async () => { await AnyAwaitableMethod(); });

// Notice that we do not await the following call, 
// as that would tie it to the foreground thread.
try
{
Task.Run(async () => { await AnyAwaitableMethod(); });
}
catch
{}

The complete code for these remarks is at https://github.com/marcusts/xamarin-forms-annoyances. See the solution called AwaitAsyncAntipattern.sln.

The GitHub site also provides links to a more detailed discussion on this topic.

Looping through JSON with node.js

My most preferred way is,

var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

This is more of an observation than an answer, but it may help others who were as frustrated as I was.

I kept getting this error from two tests in my suite. I thought I had simply broken the tests with the refactoring I was doing, so after backing out changes didn't work, I reverted to earlier code, twice (two revisions back) thinking it'd get rid of the error. Doing so changed nothing. I chased my tail all day yesterday, and part of this morning without resolving the issue.

I got frustrated and checked out the code onto a laptop this morning. Ran the entire test suite (about 180 tests), no errors. So the errors were never in the code or tests. Went back to my dev box and rebooted it to clear anything in memory that might have been causing the issue. No change, same errors on the same two tests. So I deleted the directory from my machine, and checked it back out. Voila! No errors.

No idea what caused it, or how to fix it, but deleting the working directory and checking it back out fixed whatever it was.

Hope this helps someone.

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

Callback after all asynchronous forEach callbacks are completed

Array.forEach does not provide this nicety (oh if it would) but there are several ways to accomplish what you want:

Using a simple counter

function callback () { console.log('all done'); }

var itemsProcessed = 0;

[1, 2, 3].forEach((item, index, array) => {
  asyncFunction(item, () => {
    itemsProcessed++;
    if(itemsProcessed === array.length) {
      callback();
    }
  });
});

(thanks to @vanuan and others) This approach guarantees that all items are processed before invoking the "done" callback. You need to use a counter that gets updated in the callback. Depending on the value of the index parameter does not provide the same guarantee, because the order of return of the asynchronous operations is not guaranteed.

Using ES6 Promises

(a promise library can be used for older browsers):

  1. Process all requests guaranteeing synchronous execution (e.g. 1 then 2 then 3)

    function asyncFunction (item, cb) {
      setTimeout(() => {
        console.log('done with', item);
        cb();
      }, 100);
    }
    
    let requests = [1, 2, 3].reduce((promiseChain, item) => {
        return promiseChain.then(() => new Promise((resolve) => {
          asyncFunction(item, resolve);
        }));
    }, Promise.resolve());
    
    requests.then(() => console.log('done'))
    
  2. Process all async requests without "synchronous" execution (2 may finish faster than 1)

    let requests = [1,2,3].map((item) => {
        return new Promise((resolve) => {
          asyncFunction(item, resolve);
        });
    })
    
    Promise.all(requests).then(() => console.log('done'));
    

Using an async library

There are other asynchronous libraries, async being the most popular, that provide mechanisms to express what you want.

Edit

The body of the question has been edited to remove the previously synchronous example code, so i've updated my answer to clarify. The original example used synchronous like code to model asynchronous behaviour, so the following applied:

array.forEach is synchronous and so is res.write, so you can simply put your callback after your call to foreach:

  posts.foreach(function(v, i) {
    res.write(v + ". index " + i);
  });

  res.end();

How to use HttpWebRequest (.NET) asynchronously?

Use HttpWebRequest.BeginGetResponse()

HttpWebRequest webRequest;

void StartWebRequest()
{
    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}

void FinishWebRequest(IAsyncResult result)
{
    webRequest.EndGetResponse(result);
}

The callback function is called when the asynchronous operation is complete. You need to at least call EndGetResponse() from this function.

Simplest way to wait some asynchronous tasks complete, in Javascript?

The way to do it is to pass the tasks a callback that updates a shared counter. When the shared counter reaches zero you know that all tasks have finished so you can continue with your normal flow.

var ntasks_left_to_go = 4;

var callback = function(){
    ntasks_left_to_go -= 1;
    if(ntasks_left_to_go <= 0){
         console.log('All tasks have completed. Do your stuff');
    }
}

task1(callback);
task2(callback);
task3(callback);
task4(callback);

Of course, there are many ways to make this kind of code more generic or reusable and any of the many async programing libraries out there should have at least one function to do this kind of thing.

Is it possible to set async:false to $.getJSON call

Both answers are wrong. You can. You need to call

$.ajaxSetup({
async: false
});

before your json ajax call. And you can set it to true after call retuns ( if there are other usages of ajax on page if you want them async )

How can I create an Asynchronous function in Javascript?

Late, but to show an easy solution using promises after their introduction in ES6, it handles asynchronous calls a lot easier:

You set the asynchronous code in a new promise:

var asyncFunct = new Promise(function(resolve, reject) {
    $('#link').animate({ width: 200 }, 2000, function() {
        console.log("finished");                
        resolve();
    });             
});

Note to set resolve() when async call finishes.
Then you add the code that you want to run after async call finishes inside .then() of the promise:

asyncFunct.then((result) => {
    console.log("Exit");    
});

Here is a snippet of it:

_x000D_
_x000D_
$('#link').click(function () {_x000D_
    console.log("Enter");_x000D_
    var asyncFunct = new Promise(function(resolve, reject) {_x000D_
        $('#link').animate({ width: 200 }, 2000, function() {_x000D_
            console.log("finished");             _x000D_
            resolve();_x000D_
        });    _x000D_
    });_x000D_
    asyncFunct.then((result) => {_x000D_
        console.log("Exit");    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="link">Link</a>_x000D_
<span>Moving</span>
_x000D_
_x000D_
_x000D_

or JSFiddle

How to wrap async function calls into a sync function in Node.js or Javascript?

You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:

function f1() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);   
}

function f2() {
    f1();
    f1();
}

Fiber(function() {
    f2();
}).run();

Inside the fiber you call f1, f2 and sleep as if they were sync.

In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).

load scripts asynchronously

HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.

async - The HTML

<script async src="siteScript.js" onload="myInit()"></script>

defer - The HTML

<script defer src="siteScript.js" onload="myInit()"></script>

While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async

Asynchronous vs synchronous execution, what does it really mean?

When executing a sequence like: a>b>c>d>, if we get a failure in the middle of execution like:

a
b
c
fail

Then we re-start from the beginning:

a
b
c
d

this is synchronous

If, however, we have the same sequence to execute: a>b>c>d>, and we have a failure in the middle:

a
b
c
fail

...but instead of restarting from the beginning, we re-start from the point of failure:

c
d

...this is know as asynchronous.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

In all these scenarios outerScopeVar is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined

Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):

1.

enter image description here

Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png'; and alert(outerScopeVar); meanwhile the event may not occur. i.e, funtion img.onload wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.

2.

2

Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0, but still it registers an asynchronous event it will be added to the last position of the Event Queue for execution, which makes the guaranteed delay.

3.

enter image description here This time ajax callback.

4.

enter image description here

Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.

5.

enter image description here

Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript

Why does .json() return a promise?

In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:

function callApi(url) {
  return fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json().then(response => ({ response }));
      }

      return response.json().then(error => ({ error }));
    })
  ;
}

let url = 'http://jsonplaceholder.typicode.com/posts/6';

const { response, error } = callApi(url);
if (response) {
  // handle json decoded response
} else {
  // handle json decoded 500 series response
}

Node JS Promise.all and forEach

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no error from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the results.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all than to execute things one after the other - each waiting before the next.

Ok, so let's get started:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

When should I use Async Controllers in ASP.NET MVC?

As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.

Take a look here for excellent advise.

How to use jQuery in chrome extension?

Apart from the solutions already mentioned, you can also download jquery.min.js locally and then use it -

For downloading -

wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"

manifest.json -

"content_scripts": [
   {
    "js": ["/path/to/jquery.min.js", ...]
   }
],

in html -

<script src="/path/to/jquery.min.js"></script>

Reference - https://developer.chrome.com/extensions/contentSecurityPolicy

Asynchronous Process inside a javascript for loop

Any recommendation on how to fix this?

Several. You can use bind:

for (i = 0; i < j; i++) {
    asycronouseProcess(function (i) {
        alert(i);
    }.bind(null, i));
}

Or, if your browser supports let (it will be in the next ECMAScript version, however Firefox already supports it since a while) you could have:

for (i = 0; i < j; i++) {
    let k = i;
    asycronouseProcess(function() {
        alert(k);
    });
}

Or, you could do the job of bind manually (in case the browser doesn't support it, but I would say you can implement a shim in that case, it should be in the link above):

for (i = 0; i < j; i++) {
    asycronouseProcess(function(i) {
        return function () {
            alert(i)
        }
    }(i));
}

I usually prefer let when I can use it (e.g. for Firefox add-on); otherwise bind or a custom currying function (that doesn't need a context object).

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

Asynchronous method call in Python?

The native Python way for asynchronous calls in 2021 with Python 3.9 suitable also for Jupyter / Ipython Kernel

Camabeh's answer is the way to go since Python 3.3.

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)


loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

This will work in Jupyter Notebook / Jupyter Lab but throw an error:

RuntimeError: This event loop is already running

Due to Ipython's usage of event loops we need something called nested asynchronous loops which is not yet implemented in Python. Luckily there is nest_asyncio to deal with the issue. All you need to do is:

!pip install nest_asyncio # use ! within Jupyter Notebook, else pip install in shell
import nest_asyncio
nest_asyncio.apply()

(Based on this thread)

Only when you call loop.close() it throws another error as it probably refers to Ipython's main loop.

RuntimeError: Cannot close a running event loop

I'll update this answer as soon as someone answered to this github issue.

Calling async method synchronously

Most of the answers on this thread are either complex or will result in deadlock.

Following method is simple and it will avoid deadlock because we are waiting for the task to finish and only then getting its result-

var task = Task.Run(() => GenerateCodeAsync()); 
task.Wait();
string code = task.Result;

Furthermore, here is a reference to MSDN article that talks about exactly same thing- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/

Run two async tasks in parallel and collect results in .NET 4.5

async Task<int> LongTask1() { 
  ...
  return 0; 
}

async Task<int> LongTask2() { 
  ...
  return 1; 
}

...
{
   Task<int> t1 = LongTask1();
   Task<int> t2 = LongTask2();
   await Task.WhenAll(t1,t2);
   //now we have t1.Result and t2.Result
}

Asynchronous shell exec in PHP

without use queue, you can use the proc_open() like this:

    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")    //here curaengine log all the info into stderror
    );
    $command = 'ping stackoverflow.com';
    $process = proc_open($command, $descriptorspec, $pipes);

nodeJs callbacks simple example

_x000D_
_x000D_
//delay callback function_x000D_
function delay (seconds, callback){_x000D_
    setTimeout(() =>{_x000D_
      console.log('The long delay ended');_x000D_
      callback('Task Complete');_x000D_
    }, seconds*1000);_x000D_
}_x000D_
//Execute delay function_x000D_
delay(1, res => {  _x000D_
    console.log(res);  _x000D_
})
_x000D_
_x000D_
_x000D_

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

How do I make an asynchronous GET request in PHP?

I would recommend you well tested PHP library: curl-easy

<?php
$request = new cURL\Request('http://www.externalsite.com/script2.php?variable=45');
$request->getOptions()
    ->set(CURLOPT_TIMEOUT, 5)
    ->set(CURLOPT_RETURNTRANSFER, true);

// add callback when the request will be completed
$request->addListener('complete', function (cURL\Event $event) {
    $response = $event->response;
    $content = $response->getContent();
    echo $content;
});

while ($request->socketPerform()) {
    // do anything else when the request is processed
}

Why do we need middleware for async flow in Redux?

Redux can't return a function instead of an action. It's just a fact. That's why people use Thunk. Read these 14 lines of code to see how it allows the async cycle to work with some added function layering:

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

https://github.com/reduxjs/redux-thunk

C non-blocking keyboard input

The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

Asynchronous Function Call in PHP

One way is to use pcntl_fork() in a recursive function.

function networkCall(){
  $data = processGETandPOST();
  $response = makeNetworkCall($data);
  processNetworkResponse($response);
  return true;
}

function runAsync($times){
  $pid = pcntl_fork();
  if ($pid == -1) {
    die('could not fork');
  } else if ($pid) {
    // we are the parent
    $times -= 1;
    if($times>0)
      runAsync($times);
    pcntl_wait($status); //Protect against Zombie children
  } else {
    // we are the child
    networkCall();
    posix_kill(getmypid(), SIGKILL);
  }
}

runAsync(3);

One thing about pcntl_fork() is that when running the script by way of Apache, it doesn't work (it's not supported by Apache). So, one way to resolve that issue is to run the script using the php cli, like: exec('php fork.php',$output); from another file. To do this you'll have two files: one that's loaded by Apache and one that's run with exec() from inside the file loaded by Apache like this:

apacheLoadedFile.php

exec('php fork.php',$output);

fork.php

function networkCall(){
  $data = processGETandPOST();
  $response = makeNetworkCall($data);
  processNetworkResponse($response);
  return true;
}

function runAsync($times){
  $pid = pcntl_fork();
  if ($pid == -1) {
    die('could not fork');
  } else if ($pid) {
    // we are the parent
    $times -= 1;
    if($times>0)
      runAsync($times);
    pcntl_wait($status); //Protect against Zombie children
  } else {
    // we are the child
    networkCall();
    posix_kill(getmypid(), SIGKILL);
  }
}

runAsync(3);

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

How should I call 3 functions in order to execute them one after the other?

_x000D_
_x000D_
//sample01_x000D_
(function(_){_[0]()})([_x000D_
 function(){$('#art1').animate({'width':'10px'},100,this[1].bind(this))},_x000D_
 function(){$('#art2').animate({'width':'10px'},100,this[2].bind(this))},_x000D_
 function(){$('#art3').animate({'width':'10px'},100)},_x000D_
])_x000D_
_x000D_
//sample02_x000D_
(function(_){_.next=function(){_[++_.i].apply(_,arguments)},_[_.i=0]()})([_x000D_
 function(){$('#art1').animate({'width':'10px'},100,this.next)},_x000D_
 function(){$('#art2').animate({'width':'10px'},100,this.next)},_x000D_
 function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);_x000D_
_x000D_
//sample03_x000D_
(function(_){_.next=function(){return _[++_.i].bind(_)},_[_.i=0]()})([_x000D_
 function(){$('#art1').animate({'width':'10px'},100,this.next())},_x000D_
 function(){$('#art2').animate({'width':'10px'},100,this.next())},_x000D_
 function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);
_x000D_
_x000D_
_x000D_

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

How to asynchronously call a method in Java

You may wish to also consider the class java.util.concurrent.FutureTask.

If you are using Java 5 or later, FutureTask is a turnkey implementation of "A cancellable asynchronous computation."

There are even richer asynchronous execution scheduling behaviors available in the java.util.concurrent package (for example, ScheduledExecutorService), but FutureTask may have all the functionality you require.

I would even go so far as to say that it is no longer advisable to use the first code pattern you gave as an example ever since FutureTask became available. (Assuming you are on Java 5 or later.)

How can I upload files asynchronously?

Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload from root of your website, this code should work for you:

_x000D_
_x000D_
const asyncFileUpload = () => {
  const fileInput = document.getElementById("file");
  const file = fileInput.files[0];
  const uri = "/upload";
  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = e => {
    const percentage = e.loaded / e.total;
    console.log(percentage);
  };
  xhr.onreadystatechange = e => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("file uploaded");
    }
  };
  xhr.open("POST", uri, true);
  xhr.setRequestHeader("X-FileName", file.name);
  xhr.send(file);
}
_x000D_
<form>
  <span>File</span>
  <input type="file" id="file" name="file" size="10" />
  <input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
_x000D_
_x000D_
_x000D_

Also some further information about XMLHttpReques:

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();


Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

For more details, you can continue reading here...

AngularJS : Initialize service with asynchronous data

What you can do is in your .config for the app is create the resolve object for the route and in the function pass in $q (promise object) and the name of the service you're depending on, and resolve the promise in the callback function for the $http in the service like so:

ROUTE CONFIG

app.config(function($routeProvider){
    $routeProvider
     .when('/',{
          templateUrl: 'home.html',
          controller: 'homeCtrl',
          resolve:function($q,MyService) {
                //create the defer variable and pass it to our service
                var defer = $q.defer();
                MyService.fetchData(defer);
                //this will only return when the promise
                //has been resolved. MyService is going to
                //do that for us
                return defer.promise;
          }
      })
}

Angular won't render the template or make the controller available until defer.resolve() has been called. We can do that in our service:

SERVICE

app.service('MyService',function($http){
       var MyService = {};
       //our service accepts a promise object which 
       //it will resolve on behalf of the calling function
       MyService.fetchData = function(q) {
             $http({method:'GET',url:'data.php'}).success(function(data){
                 MyService.data = data;
                 //when the following is called it will
                 //release the calling function. in this
                 //case it's the resolve function in our
                 //route config
                 q.resolve();
             }
       }

       return MyService;
});

Now that MyService has the data assigned to it's data property, and the promise in the route resolve object has been resolved, our controller for the route kicks into life, and we can assign the data from the service to our controller object.

CONTROLLER

  app.controller('homeCtrl',function($scope,MyService){
       $scope.servicedata = MyService.data;
  });

Now all our binding in the scope of the controller will be able to use the data which originated from MyService.

How to use the 'main' parameter in package.json?

As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.


Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:

-lib/
--bundle.js

Then in your package.json, you tell npm how to access the library (node package):

{
  "name": "my-library-name",
  "main": "lib/bundle.js",
  ...
}

After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:

import { add, subtract } from 'my-library-name';

This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.

module.exports = {
  entry: {
    main: './src/index.js',
    add: './src/add.js',
    subtract: './src/subtract.js',
  },
  output: {
    path: `${__dirname}/lib`,
    filename: '[name].js',
    library: 'my-library-name',
    libraryTarget: 'umd',
  },
  ...
}

Still, you would define one main entry point to your library in your package.json:

{
  "name": "my-library-name",
  "main": "lib/main.js",
  ...
}

Then when using the library, you can import your files from your main entry point:

import { add, subtract } from 'my-library-name';

However, you can also bypass the main entry point from the package.json and import the code splitted bundles:

import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';

After all, the main property in your package.json only points to your main entry point file of your library.

React - Display loading screen while DOM is rendering?

This could be done by placing the loading icon in your html file (index.html for ex), so that users see the icon immediately after the html file has been loaded.

When your app finishes loading, you could simply remove that loading icon in a lifecycle hook, I usually do that in componentDidMount.

What is the difference between synchronous and asynchronous programming (in node.js)

The function makes the second one asynchronous.

The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.

Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

Call An Asynchronous Javascript Function Synchronously

You can force asynchronous JavaScript in NodeJS to be synchronous with sync-rpc.

It will definitely freeze your UI though, so I'm still a naysayer when it comes to whether what it's possible to take the shortcut you need to take. It's not possible to suspend the One And Only Thread in JavaScript, even if NodeJS lets you block it sometimes. No callbacks, events, anything asynchronous at all will be able to process until your promise resolves. So unless you the reader have an unavoidable situation like the OP (or, in my case, are writing a glorified shell script with no callbacks, events, etc.), DO NOT DO THIS!

But here's how you can do this:

./calling-file.js

var createClient = require('sync-rpc');
var mySynchronousCall = createClient(require.resolve('./my-asynchronous-call'), 'init data');

var param1 = 'test data'
var data = mySynchronousCall(param1);
console.log(data); // prints: received "test data" after "init data"

./my-asynchronous-call.js

function init(initData) {
  return function(param1) {
    // Return a promise here and the resulting rpc client will be synchronous
    return Promise.resolve('received "' + param1 + '" after "' + initData + '"');
  };
}
module.exports = init;

LIMITATIONS:

These are both a consequence of how sync-rpc is implemented, which is by abusing require('child_process').spawnSync:

  1. This will not work in the browser.
  2. The arguments to your function must be serializable. Your arguments will pass in and out of JSON.stringify, so functions and non-enumerable properties like prototype chains will be lost.

Android: Cancel Async Task

I would like to improve the code. When you canel the aSyncTask the onCancelled() (callback method of aSyncTask) gets automatically called, and there you can hide your progressBarDialog.

You can include this code as well:

public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            this.cancel(true);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(getApplicationContext(), "asynctack cancelled.....", Toast.LENGTH_SHORT).show();
            dialog.hide(); /*hide the progressbar dialog here...*/
            super.onCancelled();
        }

    }

How to write asynchronous functions for Node.js

Just passing by callbacks is not enough. You have to use settimer for example, to make function async.

Examples: Not async functions:

function a() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };
  b();
};

function b() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };    
  c();
};

function c() {
  for(i=0; i<10000000; i++) {
  };
  console.log("async finished!");
};

a();
console.log("This should be good");

If you will run above example, This should be good, will have to wait untill those functions will finish to work.

Pseudo multithread (async) functions:

function a() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };
    b();
  }, 0);
};

function b() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };  
    c();
  }, 0);
};

function c() {
  setTimeout ( function() {
    for(i=0; i<10000000; i++) {
    };
    console.log("async finished!");
  }, 0);
};

a();
console.log("This should be good");

This one will be trully async. This should be good will be writen before async finished.

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.

How to make an Asynchronous Method return a value?

From C# 5.0, you can specify the method as

public async Task<bool> doAsyncOperation()
{
    // do work
    return true;
}

bool result = await doAsyncOperation();

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

Async always WaitingForActivation

For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task class and TaskStatus enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.

In the context of methods marked as async, the resulting Task is not a Task representing the execution of the method, but a Task for the continuation of the method.

This is only able to make use of a few possible states:

  • Canceled
  • Faulted
  • RanToCompletion
  • WaitingForActivation

I understand that Runningcould appear to have been a better default than WaitingForActivation, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await-ing something else). The other option may have been to add a new value to TaskStatus, however this could have been a breaking change for existing applications and libraries.

All of this is very different to when making use of Task.Run which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus enumeration.

If you wish to keep track of the status of an async method, take a look at the IProgress(T) interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T) interface.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Waiting until the task finishes

Use dispatch group

dispatchGroup.enter()
FirstOperation(completion: { _ in
    dispatchGroup.leave()
})
dispatchGroup.enter()
SecondOperation(completion: { _ in
    dispatchGroup.leave()
})
dispatchGroup.wait() // Waits here on this thread until the two operations complete executing.

What are the best use cases for Akka framework

We use Akka in several projects at work, the most interesting of which is related to vehicle crash repair. Primarily in the UK but now expanding to the US, Asia, Australasia and Europe. We use actors to ensure that crash repair information is provided realtime to enable the safe and cost effective repair of vehicles.

The question with Akka is really more 'what can't you do with Akka'. Its ability to integrate with powerful frameworks, its powerful abstraction and all of the fault tolerance aspects make it a very comprehensive toolkit.

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

asynchronous vs non-blocking

The blocking models require the initiating application to block when the I/O has started. This means that it isn't possible to overlap processing and I/O at the same time. The synchronous non-blocking model allows overlap of processing and I/O, but it requires that the application check the status of the I/O on a recurring basis. This leaves asynchronous non-blocking I/O, which permits overlap of processing and I/O, including notification of I/O completion.

Sleep Command in T-SQL?

Look at the WAITFOR command.

E.g.

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001' is likely to result in no wait at all.

Can't specify the 'async' modifier on the 'Main' method of a console app

If you're using C# 7.1 or later, go with the nawfal's answer and just change the return type of your Main method to Task or Task<int>. If you are not:

  • Have an async Task MainAsync like Johan said.
  • Call its .GetAwaiter().GetResult() to catch the underlying exception like do0g said.
  • Support cancellation like Cory said.
  • A second CTRL+C should terminate the process immediately. (Thanks binki!)
  • Handle OperationCancelledException - return an appropriate error code.

The final code looks like:

private static int Main(string[] args)
{
    var cts = new CancellationTokenSource();
    Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = !cts.IsCancellationRequested;
        cts.Cancel();
    };

    try
    {
        return MainAsync(args, cts.Token).GetAwaiter().GetResult();
    }
    catch (OperationCanceledException)
    {
        return 1223; // Cancelled.
    }
}

private static async Task<int> MainAsync(string[] args, CancellationToken cancellationToken)
{
    // Your code...

    return await Task.FromResult(0); // Success.
}

How to make asynchronous HTTP requests in PHP

Here is a working example, just run it and open storage.txt afterwards, to check the magical result

<?php
    function curlGet($target){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $target);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec ($ch);
        curl_close ($ch);
        return $result;
    }

    // Its the next 3 lines that do the magic
    ignore_user_abort(true);
    header("Connection: close"); header("Content-Length: 0");
    echo str_repeat("s", 100000); flush();

    $i = $_GET['i'];
    if(!is_numeric($i)) $i = 1;
    if($i > 4) exit;
    if($i == 1) file_put_contents('storage.txt', '');

    file_put_contents('storage.txt', file_get_contents('storage.txt') . time() . "\n");

    sleep(5);
    curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));
    curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));

Making interface implementations async

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

Which browsers support <script async="async" />?

From your referenced page:

http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html

Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.

How can I wait for set of asynchronous callback functions?

You can use jQuery's Deferred object along with the when method.

deferredArray = [];
forloop {
    deferred = new $.Deferred();
    ajaxCall(function() {
      deferred.resolve();
    }
    deferredArray.push(deferred);
}

$.when(deferredArray, function() {
  //this code is called after all the ajax calls are done
});

How to use JUnit to test asynchronous processes

I find an library socket.io to test asynchronous logic. It looks simple and brief way using LinkedBlockingQueue. Here is example:

    @Test(timeout = TIMEOUT)
public void message() throws URISyntaxException, InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = client();
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
        @Override
        public void call(Object... objects) {
            socket.send("foo", "bar");
        }
    }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            values.offer(args);
        }
    });
    socket.connect();

    assertThat((Object[])values.take(), is(new Object[] {"hello client"}));
    assertThat((Object[])values.take(), is(new Object[] {"foo", "bar"}));
    socket.disconnect();
}

Using LinkedBlockingQueue take API to block until to get result just like synchronous way. And set timeout to avoid assuming too much time to wait the result.

fs.writeFile in a promise, asynchronous-synchronous stuff

For easy to use asynchronous convert all callback to promise use some library like "bluebird" .

      .then(function(results) {
                fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("JSON saved");
                        return results;
                    }
                })


            }).catch(function(err) {
                console.log(err);
            });

Try solution with promise (bluebird)

var amazon = require('amazon-product-api');
var fs = require('fs');
var Promise = require('bluebird');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});


var array = fs.readFileSync('./test.txt').toString().split('\n');
Promise.map(array, function (ASIN) {
    client.itemLookup({
        domain: 'webservices.amazon.de',
        responseGroup: 'Large',
        idType: 'ASIN',
        itemId: ASIN
    }).then(function(results) {
        fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("JSON saved");
                return results;
            }
        })
    }).catch(function(err) {
        console.log(err);
    });
});

How can I run an external command asynchronously from Python?

I have the same problem trying to connect to an 3270 terminal using the s3270 scripting software in Python. Now I'm solving the problem with an subclass of Process that I found here:

http://code.activestate.com/recipes/440554/

And here is the sample taken from file:

def recv_some(p, t=.1, e=1, tr=5, stderr=0):
    if tr < 1:
        tr = 1
    x = time.time()+t
    y = []
    r = ''
    pr = p.recv
    if stderr:
        pr = p.recv_err
    while time.time() < x or r:
        r = pr()
        if r is None:
            if e:
                raise Exception(message)
            else:
                break
        elif r:
            y.append(r)
        else:
            time.sleep(max((x-time.time())/tr, 0))
    return ''.join(y)

def send_all(p, data):
    while len(data):
        sent = p.send(data)
        if sent is None:
            raise Exception(message)
        data = buffer(data, sent)

if __name__ == '__main__':
    if sys.platform == 'win32':
        shell, commands, tail = ('cmd', ('dir /w', 'echo HELLO WORLD'), '\r\n')
    else:
        shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), '\n')

    a = Popen(shell, stdin=PIPE, stdout=PIPE)
    print recv_some(a),
    for cmd in commands:
        send_all(a, cmd + tail)
        print recv_some(a),
    send_all(a, 'exit' + tail)
    print recv_some(a, e=0)
    a.wait()

Asynchronous Requests with Python requests

I have also tried some things using the asynchronous methods in python, how ever I have had much better luck using twisted for asynchronous programming. It has fewer problems and is well documented. Here is a link of something simmilar to what you are trying in twisted.

http://pythonquirks.blogspot.com/2011/04/twisted-asynchronous-http-request.html

Async await in linq select

Existing code is working, but is blocking the thread.

.Select(async ev => await ProcessEventAsync(ev))

creates a new Task for every event, but

.Select(t => t.Result)

blocks the thread waiting for each new task to end.

In the other hand your code produce the same result but keeps asynchronous.

Just one comment on your first code. This line

var tasks = await Task.WhenAll(events...

will produce a single Task<TResult[]> so the variable should be named in singular.

Finally your last code make the same but is more succinct.

For reference: Task.Wait / Task.WhenAll

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

How to read file with async/await properly?

There is a fs.readFileSync( path, options ) method, which is synchronous.

How to load CSS Asynchronously

The trick to triggering an asynchronous stylesheet download is to use a <link> element and set an invalid value for the media attribute (I'm using media="none", but any value will do). When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.

<link rel="stylesheet" href="css.css" media="none">

Once the stylesheet has finished downloading the media attribute must be set to a valid value so the style rules will be applied to the document. The onload event is used to switch the media property to all:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'">

This method of loading CSS will deliver useable content to visitors much quicker than the standard approach. Critical CSS can still be served with the usual blocking approach (or you can inline it for ultimate performance) and non-critical styles can be progressively downloaded and applied later in the parsing / rendering process.

This technique uses JavaScript, but you can cater for non-JavaScript browsers by wrapping the equivalent blocking <link> elements in a <noscript> element:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="css.css"></noscript>

You can see the operation in www.itcha.edu.sv

enter image description here

Source in http://keithclark.co.uk/

Call async/await functions in parallel

    // A generic test function that can be configured 
    // with an arbitrary delay and to either resolve or reject
    const test = (delay, resolveSuccessfully) => new Promise((resolve, reject) => setTimeout(() => {
        console.log(`Done ${ delay }`);
        resolveSuccessfully ? resolve(`Resolved ${ delay }`) : reject(`Reject ${ delay }`)
    }, delay));

    // Our async handler function
    const handler = async () => {
        // Promise 1 runs first, but resolves last
        const p1 = test(10000, true);
        // Promise 2 run second, and also resolves
        const p2 = test(5000, true);
        // Promise 3 runs last, but completes first (with a rejection) 
        // Note the catch to trap the error immediately
        const p3 = test(1000, false).catch(e => console.log(e));
        // Await all in parallel
        const r = await Promise.all([p1, p2, p3]);
        // Display the results
        console.log(r);
    };

    // Run the handler
    handler();
    /*
    Done 1000
    Reject 1000
    Done 5000
    Done 10000
    */

Whilst setting p1, p2 and p3 is not strictly running them in parallel, they do not hold up any execution and you can trap contextual errors with a catch.

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

How do I return the response from an asynchronous call?

Using ES2017 you should have this as the function declaration

async function foo() {
    var response = await $.ajax({url: '...'})
    return response;
}

And executing it like this.

(async function() {
    try {
        var result = await foo()
        console.log(result)
    } catch (e) {}
})()

Or the Promise syntax

foo().then(response => {
    console.log(response)

}).catch(error => {
    console.log(error)

})

Running multiple async tasks and waiting for them all to complete

Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

var cats = new List<Cat>();
var dog = new Dog();

var loadDataTasks = new Task[]
{
    Task.Run(async () => cats = await LoadCatsAsync()),
    Task.Run(async () => dog = await LoadDogAsync())
};

try
{
    await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
    // handle exception
}

How to reject in async/await syntax?

A better way to write the async function would be by returning a pending Promise from the start and then handling both rejections and resolutions within the callback of the promise, rather than just spitting out a rejected promise on error. Example:

async foo(id: string): Promise<A> {
    return new Promise(function(resolve, reject) {
        // execute some code here
        if (success) { // let's say this is a boolean value from line above
            return resolve(success);
        } else {
            return reject(error); // this can be anything, preferably an Error object to catch the stacktrace from this function
        }
    });
}

Then you just chain methods on the returned promise:

async function bar () {
    try {
        var result = await foo("someID")
        // use the result here
    } catch (error) {
        // handle error here
    }
}

bar()

Source - this tutorial:

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

How would I run an async Task<T> method synchronously?

It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.

Task<MyResult> DoSomethingAsync() { ... }

// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());

// Will block until the task is completed...
MyResult result = task.Result; 

How to create threads in nodejs

There is also at least one library for doing native threading from within Node.js: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.

How to schedule a function to run every hour on Flask?

You may use flask-crontab module, which is quite easy.

Step 1: pip install flask-crontab

Step 2:

from flask import Flask
from flask_crontab import Crontab

app = Flask(__name__)
crontab = Crontab(app)

Step 3:

@crontab.job(minute="0", hour="6", day="*", month="*", day_of_week="*")
def my_scheduled_job():
    do_something()

Step 4: On cmd, hit

flask crontab add

Done. now simply run your flask application, and you can check your function will call at 6:00 every day.

You may take reference from Here (Official DOc).

Understanding dispatch_async

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to force Sequential Javascript Execution?

If you don't insist on using pure Javascript, you can build a sequential code in Livescript and it looks pretty good. You might want to take a look at this example:

# application
do
    i = 3
    console.log td!, "start"
    <- :lo(op) ->
        console.log td!, "hi #{i}"
        i--
        <- wait-for \something
        if i is 0
            return op! # break
        lo(op)
    <- sleep 1500ms
    <- :lo(op) ->
        console.log td!, "hello #{i}"
        i++
        if i is 3
            return op! # break
        <- sleep 1000ms
        lo(op)
    <- sleep 0
    console.log td!, "heyy"

do
    a = 8
    <- :lo(op) ->
        console.log td!, "this runs in parallel!", a
        a--
        go \something
        if a is 0
            return op! # break
        <- sleep 500ms
        lo(op)

Output:

0ms : start
2ms : hi 3
3ms : this runs in parallel! 8
3ms : hi 2
505ms : this runs in parallel! 7
505ms : hi 1
1007ms : this runs in parallel! 6
1508ms : this runs in parallel! 5
2009ms : this runs in parallel! 4
2509ms : hello 0
2509ms : this runs in parallel! 3
3010ms : this runs in parallel! 2
3509ms : hello 1
3510ms : this runs in parallel! 1
4511ms : hello 2
4511ms : heyy

async await return Task

This is a Task that is returning a Task of type String (C# anonymous function or in other word a delegation is used 'Func')

    public static async Task<string> MyTask()
    {
        //C# anonymous AsyncTask
        return await Task.FromResult<string>(((Func<string>)(() =>
        {
            // your code here
            return  "string result here";

        }))());
    }

socket.shutdown vs socket.close

Explanation of shutdown and close: Graceful shutdown (msdn)

Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket.

Omitting shutdown may cause the socket to linger in the OSs stack until the connection has been closed gracefully.

IMO the names 'shutdown' and 'close' are misleading, 'close' and 'destroy' would emphasise their differences.

How do I access store state in React Redux?

You want to do more than just getState. You want to react to changes in the store.

If you aren't using react-redux, you can do this:

function rerender() {
    const state = store.getState();
    render(
        <div>
            { state.items.map((item) => <p> {item.title} </p> )}
        </div>,
        document.getElementById('app')
    );
}

// subscribe to store
store.subscribe(rerender);

// do initial render
rerender();

// dispatch more actions and view will update

But better is to use react-redux. In this case you use the Provider like you mentioned, but then use connect to connect your component to the store.

How to wait for async method to complete?

The following snippet shows a way to ensure the awaited method completes before returning to the caller. HOWEVER, I wouldn't say it's good practice. Please edit my answer with explanations if you think otherwise.

public async Task AnAsyncMethodThatCompletes()
{
    await SomeAsyncMethod();
    DoSomeMoreStuff();
    await Task.Factory.StartNew(() => { }); // <-- This line here, at the end
}

await AnAsyncMethodThatCompletes();
Console.WriteLine("AnAsyncMethodThatCompletes() completed.")

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Simplest way to detect a pinch

You want to use the gesturestart, gesturechange, and gestureend events. These get triggered any time 2 or more fingers touch the screen.

Depending on what you need to do with the pinch gesture, your approach will need to be adjusted. The scale multiplier can be examined to determine how dramatic the user's pinch gesture was. See Apple's TouchEvent documentation for details about how the scale property will behave.

node.addEventListener('gestureend', function(e) {
    if (e.scale < 1.0) {
        // User moved fingers closer together
    } else if (e.scale > 1.0) {
        // User moved fingers further apart
    }
}, false);

You could also intercept the gesturechange event to detect a pinch as it happens if you need it to make your app feel more responsive.

Select count(*) from multiple tables

select @count = sum(data) from
(
select count(*)  as data from #tempregion
union 
select count(*)  as data from #tempmetro
union
select count(*)  as data from #tempcity
union
select count(*)  as data from #tempzips
) a

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

You can use these Extension Methods: (Save as PartialWithScript.cs)

namespace System.Web.Mvc.Html
{
    public static class PartialWithScript
    {
        public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
        {
            if (htmlHelper.ViewBag.ScriptPartials == null)
            {
                htmlHelper.ViewBag.ScriptPartials = new List<string>();
            }

            if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
            {
                htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
            }

            htmlHelper.ViewBag.ScriptPartialHtml = true;
            htmlHelper.RenderPartial(partialViewName);
        }

        public static void RenderPartialScripts(this HtmlHelper htmlHelper)
        {
            if (htmlHelper.ViewBag.ScriptPartials != null)
            {
                htmlHelper.ViewBag.ScriptPartialHtml = false;
                foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
                {
                    htmlHelper.RenderPartial(partial);
                }
            }
        }
    }
}

Use like this:

Example partial: (_MyPartial.cshtml) Put the html in the if, and the js in the else.

@if (ViewBag.ScriptPartialHtml ?? true)
    <p>I has htmls</p>
}
else {
    <script type="text/javascript">
        alert('I has javascripts');
    </script>
}

In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.

@{ Html.RenderPartialScripts(); }

Then to use your partial, simply do this: It will render only the html at this location.

@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

String.Empty and string.Empty are equivalent. String is the BCL class name; string is its C# alias (or shortcut, if you will). Same as with Int32 and int. See the docs for more examples.

As far as "" is concerned, I'm not really sure.

Personally, I always use string.Empty.

FileProvider - IllegalArgumentException: Failed to find configured root

I see that at least you're not providing the same path as others in file_paths.xml. So please make sure you provide the exact the same package name or path in 3 places including:

  • android:authorities attribute in manifest
  • path attribute in file_paths.xml
  • authority argument when calling FileProvider.getUriForFile().

Default visibility for C# classes and members (fields, methods, etc.)?

By default, the access modifier for a class is internal. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.

How can I show a hidden div when a select option is selected?

<select id="test" name="form_select" onchange="showDiv()">
   <option value="0">No</option>
   <option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
<script>
    function showDiv(){
        getSelectValue = document.getElementById("test").value;
        if(getSelectValue == "1"){
            document.getElementById("hidden_div").style.display="block";
        }else{
            document.getElementById("hidden_div").style.display="none";
        }
    }
</script>

How do I create a slug in Django?

In most cases the slug should not change, so you really only want to calculate it on first save:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(editable=False) # hide from admin

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(Test, self).save()

Set Date in a single line

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

Heatmap in matplotlib with pcolor?

The python seaborn module is based on matplotlib, and produces a very nice heatmap.

Below is an implementation with seaborn, designed for the ipython/jupyter notebook.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("http://datasets.flowingdata.com/ppg2008.csv", index_col='Name  ')
# remove index title
nba.index.name = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 
          'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage', 
          'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set(font_scale=1.2)
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm, cmap=plt.cm.Blues, linewidths=.1)
# set the x-axis labels on the top
ax.xaxis.tick_top()
# rotate the x-axis labels
plt.xticks(rotation=90)
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)
fig.savefig("nba.png")

The output looks like this: seaborn nba heatmap I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.

As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

This problem occurs because the Web site does not have the Directory Browsing feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods. To resolve this problem, I followed the steps in Method 1 as mentioned in the MS Support page and its the recommended method.

Method 1: Enable the Directory Browsing feature in IIS (Recommended)

  1. Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.

  2. In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.

  3. In the Features view, double-click Directory Browsing.

  4. In the Actions pane, click Enable.

If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,

Method 2: Add a default document

To resolve this problem, follow these steps:

  • Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
  • In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
  • In the Features view, double-click Default Document.
  • In the Actions pane, click Enable.
  • In the File Name box, type the name of the default document, and then click OK.

Method 3: Enable the Directory Browsing feature in IIS Express

Note This method is for the web developers who experience the issue when they use IIS Express.

Follow these steps:

  • Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express

  • Type the following command, and then press Enter:

    appcmd set config /section:system.webServer/directoryBrowse /enabled:true

jQuery Screen Resolution Height Adjustment

Here is an example on how to center an object vertically with jQuery:

var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2  + 'px');

But you could easily change that to whatever your needs are.

Getting the class name from a static method in Java

Since the question Something like `this.class` instead of `ClassName.class`? is marked as a duplicate for this one (which is arguable because that question is about the class rather than class name), I'm posting the answer here:

class MyService {
    private static Class thisClass = MyService.class;
    // or:
    //private static Class thisClass = new Object() { }.getClass().getEnclosingClass();
    ...
    static void startService(Context context) {
        Intent i = new Intent(context, thisClass);
        context.startService(i);
    }
}

It is important to define thisClass as private because:
1) it must not be inherited: derived classes must either define their own thisClass or produce an error message
2) references from other classes should be done as ClassName.class rather than ClassName.thisClass.

With thisClass defined, access to the class name becomes:

thisClass.getName()

Cropping an UIImage

Here's an updated Swift 3 version based on Noodles answer

func cropping(to rect: CGRect) -> UIImage? {

    if let cgCrop = cgImage?.cropping(to: rect) {
        return UIImage(cgImage: cgCrop)
    }
    else if let ciCrop = ciImage?.cropping(to: rect) {
        return UIImage(ciImage: ciCrop)
    }

    return nil
}

Get the data received in a Flask request

To get request.form as a normal dictionary , use request.form.to_dict(flat=False).

To return JSON data for an API, pass it to jsonify.

This example returns form data as JSON data.

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

Here's an example of POST form data with curl, returning as JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

Are there any free Xml Diff/Merge tools available?

I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.

Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.

It is fully controllable via the command line and can also generate text reports containing the differences between the files.

Project: Merge merging three XML files

How to send custom headers with requests in Swagger UI?

DISCLAIMER: this solution is not using Header.

If someone is looking for a lazy-lazy manner (also in WebApi), I'd suggest:

public YourResult Authorize([FromBody]BasicAuthCredentials credentials)

You are not getting from header, but at least you have an easy alternative. You can always check the object for null and fallback to header mechanism.

How do I use the Simple HTTP client in Android?

You can use this code:

int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.setConnectTimeout(TIME_OUT);
                conection.connect();
                // Getting file length
                int lenghtOfFile = conection.getContentLength();
                // Create a Input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/9androidnet.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                connectionTimeout=true;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

Check the current number of connections to MongoDb

Connect with your mongodb instance from local system

  1. sudo mongo "mongodb://MONGO_HOST_IP:27017" --authenticationDatabase admin

It ll let you know all connected clients and their details

  1. db.currentOp(true)

Calculating Page Table Size

Since we have a virtual address space of 2^32 and each page size is 2^12, we can store (2^32/2^12) = 2^20 pages. Since each entry into this page table has an address of size 4 bytes, then we have 2^20*4 = 4MB. So the page table takes up 4MB in memory.

How can I remove a commit on GitHub?

You'll need to clear out your cache to have it completely wiped. this help page from git will help you out. (it helped me) http://help.github.com/remove-sensitive-data/

Why can't I define a static method in a Java interface?

Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.

With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.

how to use javascript Object.defineProperty

Since you asked a similar question, let's take it to step by step. It's a bit longer, but it may save you much more time than I have spent on writing this:

Property is an OOP feature designed for clean separation of client code. For example, in some e-shop you might have objects like this:

function Product(name,price) {
  this.name = name;
  this.price = price;
  this.discount = 0;
}

var sneakers = new Product("Sneakers",20); // {name:"Sneakers",price:20,discount:0}
var tshirt = new Product("T-shirt",10);  // {name:"T-shirt",price:10,discount:0}

Then in your client code (the e-shop), you can add discounts to your products:

function badProduct(obj) { obj.discount+= 20; ... }
function generalDiscount(obj) { obj.discount+= 10; ... }
function distributorDiscount(obj) { obj.discount+= 15; ... }

Later, the e-shop owner might realize that the discount can't be greater than say 80%. Now you need to find EVERY occurrence of the discount modification in the client code and add a line

if(obj.discount>80) obj.discount = 80;

Then the e-shop owner may further change his strategy, like "if the customer is reseller, the maximal discount can be 90%". And you need to do the change on multiple places again plus you need to remember to alter these lines anytime the strategy is changed. This is a bad design. That's why encapsulation is the basic principle of OOP. If the constructor was like this:

function Product(name,price) {
  var _name=name, _price=price, _discount=0;
  this.getName = function() { return _name; }
  this.setName = function(value) { _name = value; }
  this.getPrice = function() { return _price; }
  this.setPrice = function(value) { _price = value; }
  this.getDiscount = function() { return _discount; }
  this.setDiscount = function(value) { _discount = value; } 
}

Then you can just alter the getDiscount (accessor) and setDiscount (mutator) methods. The problem is that most of the members behave like common variables, just the discount needs special care here. But good design requires encapsulation of every data member to keep the code extensible. So you need to add lots of code that does nothing. This is also a bad design, a boilerplate antipattern. Sometimes you can't just refactor the fields to methods later (the eshop code may grow large or some third-party code may depend on the old version), so the boilerplate is lesser evil here. But still, it is evil. That's why properties were introduced into many languages. You could keep the original code, just transform the discount member into a property with get and set blocks:

function Product(name,price) {
  this.name = name;
  this.price = price;
//this.discount = 0; // <- remove this line and refactor with the code below
  var _discount; // private member
  Object.defineProperty(this,"discount",{
    get: function() { return _discount; },
    set: function(value) { _discount = value; if(_discount>80) _discount = 80; }
  });
}

// the client code
var sneakers = new Product("Sneakers",20);
sneakers.discount = 50; // 50, setter is called
sneakers.discount+= 20; // 70, setter is called
sneakers.discount+= 20; // 80, not 90!
alert(sneakers.discount); // getter is called

Note the last but one line: the responsibility for correct discount value was moved from the client code (e-shop definition) to the product definition. The product is responsible for keeping its data members consistent. Good design is (roughly said) if the code works the same way as our thoughts.

So much about properties. But javascript is different from pure Object-oriented languages like C# and codes the features differently:

In C#, transforming fields into properties is a breaking change, so public fields should be coded as Auto-Implemented Properties if your code might be used in the separately compiled client.

In Javascript, the standard properties (data member with getter and setter described above) are defined by accessor descriptor (in the link you have in your question). Exclusively, you can use data descriptor (so you can't use i.e. value and set on the same property):

  • accessor descriptor = get + set (see the example above)
    • get must be a function; its return value is used in reading the property; if not specified, the default is undefined, which behaves like a function that returns undefined
    • set must be a function; its parameter is filled with RHS in assigning a value to property; if not specified, the default is undefined, which behaves like an empty function
  • data descriptor = value + writable (see the example below)
    • value default undefined; if writable, configurable and enumerable (see below) are true, the property behaves like an ordinary data field
    • writable - default false; if not true, the property is read only; attempt to write is ignored without error*!

Both descriptors can have these members:

  • configurable - default false; if not true, the property can't be deleted; attempt to delete is ignored without error*!
  • enumerable - default false; if true, it will be iterated in for(var i in theObject); if false, it will not be iterated, but it is still accessible as public

* unless in strict mode - in that case JS stops execution with TypeError unless it is caught in try-catch block

To read these settings, use Object.getOwnPropertyDescriptor().

Learn by example:

var o = {};
Object.defineProperty(o,"test",{
  value: "a",
  configurable: true
});
console.log(Object.getOwnPropertyDescriptor(o,"test")); // check the settings    

for(var i in o) console.log(o[i]); // nothing, o.test is not enumerable
console.log(o.test); // "a"
o.test = "b"; // o.test is still "a", (is not writable, no error)
delete(o.test); // bye bye, o.test (was configurable)
o.test = "b"; // o.test is "b"
for(var i in o) console.log(o[i]); // "b", default fields are enumerable

If you don't wish to allow the client code such cheats, you can restrict the object by three levels of confinement:

  • Object.preventExtensions(yourObject) prevents new properties to be added to yourObject. Use Object.isExtensible(<yourObject>) to check if the method was used on the object. The prevention is shallow (read below).
  • Object.seal(yourObject) same as above and properties can not be removed (effectively sets configurable: false to all properties). Use Object.isSealed(<yourObject>) to detect this feature on the object. The seal is shallow (read below).
  • Object.freeze(yourObject) same as above and properties can not be changed (effectively sets writable: false to all properties with data descriptor). Setter's writable property is not affected (since it doesn't have one). The freeze is shallow: it means that if the property is Object, its properties ARE NOT frozen (if you wish to, you should perform something like "deep freeze", similar to deep copy - cloning). Use Object.isFrozen(<yourObject>) to detect it.

You don't need to bother with this if you write just a few lines fun. But if you want to code a game (as you mentioned in the linked question), you should care about good design. Try to google something about antipatterns and code smell. It will help you to avoid situations like "Oh, I need to completely rewrite my code again!", it can save you months of despair if you want to code a lot. Good luck.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

if you find the same problem in windows server, then you need to run the command line with enough permission, such as administrator permission.

How to parse a date?

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

How can I create a copy of an object in Python?

How can I create a copy of an object in Python?

So, if I change values of the fields of the new object, the old object should not be affected by that.

You mean a mutable object then.

In Python 3, lists get a copy method (in 2, you'd use a slice to make a copy):

>>> a_list = list('abc')
>>> a_copy_of_a_list = a_list.copy()
>>> a_copy_of_a_list is a_list
False
>>> a_copy_of_a_list == a_list
True

Shallow Copies

Shallow copies are just copies of the outermost container.

list.copy is a shallow copy:

>>> list_of_dict_of_set = [{'foo': set('abc')}]
>>> lodos_copy = list_of_dict_of_set.copy()
>>> lodos_copy[0]['foo'].pop()
'c'
>>> lodos_copy
[{'foo': {'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]

You don't get a copy of the interior objects. They're the same object - so when they're mutated, the change shows up in both containers.

Deep copies

Deep copies are recursive copies of each interior object.

>>> lodos_deep_copy = copy.deepcopy(list_of_dict_of_set)
>>> lodos_deep_copy[0]['foo'].add('c')
>>> lodos_deep_copy
[{'foo': {'c', 'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]

Changes are not reflected in the original, only in the copy.

Immutable objects

Immutable objects do not usually need to be copied. In fact, if you try to, Python will just give you the original object:

>>> a_tuple = tuple('abc')
>>> tuple_copy_attempt = a_tuple.copy()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'copy'

Tuples don't even have a copy method, so let's try it with a slice:

>>> tuple_copy_attempt = a_tuple[:]

But we see it's the same object:

>>> tuple_copy_attempt is a_tuple
True

Similarly for strings:

>>> s = 'abc'
>>> s0 = s[:]
>>> s == s0
True
>>> s is s0
True

and for frozensets, even though they have a copy method:

>>> a_frozenset = frozenset('abc')
>>> frozenset_copy_attempt = a_frozenset.copy()
>>> frozenset_copy_attempt is a_frozenset
True

When to copy immutable objects

Immutable objects should be copied if you need a mutable interior object copied.

>>> tuple_of_list = [],
>>> copy_of_tuple_of_list = tuple_of_list[:]
>>> copy_of_tuple_of_list[0].append('a')
>>> copy_of_tuple_of_list
(['a'],)
>>> tuple_of_list
(['a'],)
>>> deepcopy_of_tuple_of_list = copy.deepcopy(tuple_of_list)
>>> deepcopy_of_tuple_of_list[0].append('b')
>>> deepcopy_of_tuple_of_list
(['a', 'b'],)
>>> tuple_of_list
(['a'],)

As we can see, when the interior object of the copy is mutated, the original does not change.

Custom Objects

Custom objects usually store data in a __dict__ attribute or in __slots__ (a tuple-like memory structure.)

To make a copyable object, define __copy__ (for shallow copies) and/or __deepcopy__ (for deep copies).

from copy import copy, deepcopy

class Copyable:
    __slots__ = 'a', '__dict__'
    def __init__(self, a, b):
        self.a, self.b = a, b
    def __copy__(self):
        return type(self)(self.a, self.b)
    def __deepcopy__(self, memo): # memo is a dict of id's to copies
        id_self = id(self)        # memoization avoids unnecesary recursion
        _copy = memo.get(id_self)
        if _copy is None:
            _copy = type(self)(
                deepcopy(self.a, memo), 
                deepcopy(self.b, memo))
            memo[id_self] = _copy 
        return _copy

Note that deepcopy keeps a memoization dictionary of id(original) (or identity numbers) to copies. To enjoy good behavior with recursive data structures, make sure you haven't already made a copy, and if you have, return that.

So let's make an object:

>>> c1 = Copyable(1, [2])

And copy makes a shallow copy:

>>> c2 = copy(c1)
>>> c1 is c2
False
>>> c2.b.append(3)
>>> c1.b
[2, 3]

And deepcopy now makes a deep copy:

>>> c3 = deepcopy(c1)
>>> c3.b.append(4)
>>> c1.b
[2, 3]

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Here is a comparison with np.einsum to show how the indices are projected

np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b)        # True 
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b)        # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b))   # True

Rotating and spacing axis labels in ggplot2

I'd like to provide an alternate solution, a robust solution similar to what I am about to propose was required in the latest version of ggtern, since introducing the canvas rotation feature.

Basically, you need to determine the relative positions using trigonometry, by building a function which returns an element_text object, given angle (ie degrees) and positioning (ie one of x,y,top or right) information.

#Load Required Libraries
library(ggplot2)
library(gridExtra)

#Build Function to Return Element Text Object
rotatedAxisElementText = function(angle,position='x'){
  angle     = angle[1]; 
  position  = position[1]
  positions = list(x=0,y=90,top=180,right=270)
  if(!position %in% names(positions))
    stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
  if(!is.numeric(angle))
    stop("'angle' must be numeric",call.=FALSE)
  rads  = (angle - positions[[ position ]])*pi/180
  hjust = 0.5*(1 - sin(rads))
  vjust = 0.5*(1 + cos(rads))
  element_text(angle=angle,vjust=vjust,hjust=hjust)
}

Frankly, in my opinion, I think that an 'auto' option should be made available in ggplot2 for the hjust and vjust arguments, when specifying the angle, anyway, lets demonstrate how the above works.

#Demonstrate Usage for a Variety of Rotations
df    = data.frame(x=0.5,y=0.5)
plots = lapply(seq(0,90,length.out=4),function(a){
  ggplot(df,aes(x,y)) + 
    geom_point() + 
    theme(axis.text.x = rotatedAxisElementText(a,'x'),
          axis.text.y = rotatedAxisElementText(a,'y')) +
    labs(title = sprintf("Rotated %s",a))
})
grid.arrange(grobs=plots)

Which produces the following:

Example

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

You have to provide one of the various SLF4J implementation .jar files in the classpath, as well as the interface .jar file. This is documented.

How to use unicode characters in Windows command line?

Try:

chcp 65001

which will change the code page to UTF-8. Also, you need to use Lucida console fonts.

std::vector versus std::array in C++

To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a

  • small "array" (under 100 elements say) - (a typical stack is about 8MB, so don't allocate more than a few KB on the stack or less if your code is recursive)
  • the size will be fixed
  • the lifetime is in the function scope (or is a member value with the same lifetime as the parent class)
  • you are counting cycles,

definitely use a std::array over a vector. If any of those requirements is not true, then use a std::vector.

<button> background image

try this way

<button> 
    <img height="100%" src="images/s.png"/>
</button>

How can I create objects while adding them into a vector?

Question 1:

   vectorOfGamers.push_back(Player)

This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:

vectorOfGamers.push_back(Player(name, id)) 
  //^^assuming name and id are parameters to the vector, call Player constructor
  //^^In other words, push `instance`  of Player class into vector

Question 2:

These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?

Yes you can. You can create a vector of pointers that points to the base class Gamer. A good choice is to use a vector of smart_pointer, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?

How do you attach and detach from Docker's process?

In the same shell, hold ctrl key and press keys p then q

How to check if an app is installed from a web-page on an iPhone?

The date solution is much better than others, I had to increment the time on 50 like that this is a Tweeter example:

//on click or your event handler..
var twMessage = "Your Message to share";
var now = new Date().valueOf();
setTimeout(function () {
   if (new Date().valueOf() - now > 100) return;
   var twitterUrl = "https://twitter.com/share?text="+twMessage;
   window.open(twitterUrl, '_blank');
}, 50);
window.location = "twitter://post?message="+twMessage;

the only problem on Mobile IOS Safari is when you don't have the app installed on device, and so Safari show an alert that autodismiss when the new url is opened, anyway is a good solution for now!

Size of Matrix OpenCV

cv:Mat mat;
int rows = mat.rows;
int cols = mat.cols;

cv::Size s = mat.size();
rows = s.height;
cols = s.width;

Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.

Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

How do I adb pull ALL files of a folder present in SD Card

if your using jellybean just start cmd, type adb devices to make sure your readable, type adb pull sdcard/ sdcard_(the date or extra) <---this file needs to be made in adb directory beforehand. PROFIT!

In other versions type adb pull mnt/sdcard/ sdcard_(the date or extra)

Remember to make file or your either gonna have a mess or it wont work.

How to put a UserControl into Visual Studio toolBox

Using VS 2010:

Let's say you have a Windows.Forms project. You add a UserControl (say MyControl) to the project, and design it all up. Now you want to add it to your toolbox.

As soon as the project is successfully built once, it will appear in your Framework Components. Right click the Toolbox to get the context menu, select "Choose Items...", and browse to the name of your control (MyControl) under the ".NET Framework Components" tab.

Advantage over using dlls: you can edit the controls in the same project as your form, and the form will build with the new controls. However, the control will only be avilable to this project.

Note: If the control has build errors, resolve them before moving on to the containing forms, or the designer has a heart attack.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Check if your form's action URL includes the www part of the domain, while the original page you have opened is viewed without www.

Typically done for Canonical Urls..

I struggled for hours before stumbling upon this article and found the hint of Cross Domain.

How can I check that two objects have the same set of property names?

If you want to check if both objects have the same properties name, you can do this:

function hasSameProps( obj1, obj2 ) {
  return Object.keys( obj1 ).every( function( prop ) {
    return obj2.hasOwnProperty( prop );
  });
}

var obj1 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] },
    obj2 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] };

console.log(hasSameProps(obj1, obj2));

In this way you are sure to check only iterable and accessible properties of both the objects.

EDIT - 2013.04.26:

The previous function can be rewritten in the following way:

function hasSameProps( obj1, obj2 ) {
    var obj1Props = Object.keys( obj1 ),
        obj2Props = Object.keys( obj2 );

    if ( obj1Props.length == obj2Props.length ) {
        return obj1Props.every( function( prop ) {
          return obj2Props.indexOf( prop ) >= 0;
        });
    }

    return false;
}

In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.

Bonus

A possible enhancement could be to introduce also a type checking to enforce the match on every property.

Typing the Enter/Return key using Python and Selenium

There are the following ways of pressing keys - C#:

Driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);

OR

OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Escape);

OR

IWebElement body = GlobalDriver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Escape);

How to display the function, procedure, triggers source code in postgresql?

There are many possibilities. Simplest way is to just use pgAdmin and get this from SQL window. However if you want to get this programmatically then examinate pg_proc and pg_trigger system catalogs or routines and triggers views from information schema (that's SQL standard way, but it might not cover all features especially PostgreSQL-specific). For example:

SELECT
    routine_definition 
FROM
    information_schema.routines 
WHERE
    specific_schema LIKE 'public'
    AND routine_name LIKE 'functionName';

Java Try Catch Finally blocks without Catch

Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!

Automatically pass $event with ng-click?

Take a peek at the ng-click directive source:

...
compile: function($element, attr) {
  var fn = $parse(attr[directiveName]);
  return function(scope, element, attr) {
    element.on(lowercase(name), function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  };
}

It shows how the event object is being passed on to the ng-click expression, using $event as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event object any other way but through the callback parameter.

Convert a string into an int

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

Best way to compare dates in Android

You could try this

Calendar today = Calendar.getInstance (); 
today.add(Calendar.DAY_OF_YEAR, 0); 
today.set(Calendar.HOUR_OF_DAY, hrs); 
today.set(Calendar.MINUTE, mins ); 
today.set(Calendar.SECOND, 0); 

and you could use today.getTime() to retrieve value and compare.

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

Adding content to a linear layout dynamically?

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);

What does the Java assert keyword do, and when should it be used?

Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
  return a + b;
}

While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
    assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
  final int result = a + b;
    assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
  return result;
}

Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to convert unix timestamp to calendar date moment.js

new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()

How to get current user, and how to use User class in MVC5?

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:

Command to close an application of console?

return; will exit a method in C#.

See code snippet below

using System;

namespace Exercise_strings
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Input string separated by -");

            var stringInput = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(stringInput))
            {
                Console.WriteLine("Nothing entered");
                return;
            }
}

So in this case if a user enters a null string or whitespace, the use of the return method terminates the Main method elegantly.

div inside table

While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.

There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.

Then again, if you're not fussy about how things look, disregard this advice.

how do I query sql for a latest record date for each user

I used this way to take the last record for each user that I have on my table. It was a query to get last location for salesman as per recent time detected on PDA devices.

CREATE FUNCTION dbo.UsersLocation()
RETURNS TABLE
AS
RETURN
Select GS.UserID, MAX(GS.UTCDateTime) 'LastDate'
From USERGPS GS
where year(GS.UTCDateTime) = YEAR(GETDATE()) 
Group By GS.UserID
GO
select  gs.UserID, sl.LastDate, gs.Latitude , gs.Longitude
        from USERGPS gs
        inner join USER s on gs.SalesManNo = s.SalesmanNo 
        inner join dbo.UsersLocation() sl on gs.UserID= sl.UserID and gs.UTCDateTime = sl.LastDate 
        order by LastDate desc

Is there an embeddable Webkit component for Windows / C# development?

The Windows version of Qt 4 includes both WebKit and classes to create ActiveX components. It probably isn't an ideal solution if you aren't already using Qt though.

Placing/Overlapping(z-index) a view above another view in android

If you are adding the View programmatically, you can use yourLayout.addView(view, 1);

where 1 is the index.

Laravel: getting a a single value from a MySQL query

[EDIT] The expected output of the pluck function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1

In Laravel 5.1, pluck gets a single column's value from the first result of a query.

In Laravel 5.2, pluck gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.

So short answer is use the value function if you want one column from the first row and you are using Laravel 5.1 or above.

Thanks to Tomas Buteler for pointing this out in the comments.

[ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.

Consider future proofing your code by using value() instead.

return DB::table('users')->where('username', $username)->value('groupName');

XSS filtering function in PHP

the best and the secure way is to use HTML Purifier. Follow this link for some hints on using it with Zend Framework.

HTML Purifier with Zend Framework

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
     array[index]                -> obj      or nil
     array[start, length]        -> an_array or nil
     array[range]                -> an_array or nil
     array.slice(index)          -> obj      or nil
     array.slice(start, length)  -> an_array or nil
     array.slice(range)          -> an_array or nil
------------------------------------------------------------------------
     Element Reference---Returns the element at index, or returns a 
     subarray starting at start and continuing for length elements, or 
     returns a subarray specified by range. Negative indices count 
     backward from the end of the array (-1 is the last element). 
     Returns nil if the index (or starting index) are out of range.

        a = [ "a", "b", "c", "d", "e" ]
        a[2] +  a[0] + a[1]    #=> "cab"
        a[6]                   #=> nil
        a[1, 2]                #=> [ "b", "c" ]
        a[1..3]                #=> [ "b", "c", "d" ]
        a[4..7]                #=> [ "e" ]
        a[6..10]               #=> nil
        a[-3, 3]               #=> [ "c", "d", "e" ]
        # special cases
        a[5]                   #=> nil
        a[6, 1]                #=> nil
        a[5, 1]                #=> []
        a[5..10]               #=> []

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Ran into this problem today when working with a set of web services, each in different projects, and a separate project containing integration tests for some of those services.

I've been using this setup for some time with EF5, without needing to include references to EF from the Integration Test Project.

Now, after upgrading to EF6, it seems I need to include a reference to EF6 in the integration test project too, even though it is not used there (pretty much as pointed out above by user3004275).

Indications you're facing the same problem:

  • Calls directly to EF (connecting to a DB, getting data, etc) work fine, as long as they are initiated from a project that has references to EF6.
  • Calls to the service via a published service interface work fine; i.e. there are no missing references "internally" in the service.
  • Calls directly to public methods in the service project, from a project outside the service, will cause this error, even though EF is not used in that project itself; only internally in the called project

The third point is what threw me off for a while, and I'm still not sure why this is required. Adding a ref to EF6 in my Integration Test project solved it in any case...

How do you set the EditText keyboard to only consist of numbers on Android?

<EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="number" />

I have tried every thing now try this one it shows other characters but you cant enter in the editText

edit.setRawInputType(Configuration.KEYBOARD_12KEY);

enter image description here

Substring with reverse index

alert("xxxxxxxxxxx_456".substr(-3))

caveat: according to mdc, not IE compatible

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

How to autoplay HTML5 mp4 video on Android?

I simplified the Javascript to trigger the video to start.

_x000D_
_x000D_
 var bg = document.getElementById ("bg"); _x000D_
 function playbg() {_x000D_
   bg.play(); _x000D_
 }
_x000D_
<video id="bg" style="min-width:100%; min-height:100%;"  playsinline autoplay loop muted onload="playbg(); "><source src="Files/snow.mp4" type="video/mp4"></video>_x000D_
</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

*"Files/snow.mp4" is just sample url

Transfer data from one HTML file to another

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed

document.getElementById('here').innerHTML = data.name; 

This needed to be changed to

document.getElementById('here').innerHTML = data.n;

I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

The developers of this app have not set up this app properly for Facebook Login?

This error also occurs when you try to log in in your test version of the Facebook app and you have not added the user you are trying to test the log in with in the Roles -> Testers section.

To fix it, just add the email address of the Facebook account you are trying to log in with in the section above.

Finally, make sure the user you added accepts the request sent before you try to test otherwise the log in process will fail in the second screen just after the user accept the conditions.

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

How to position the form in the center screen?

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Is it possible in Java to catch two exceptions in the same catch block?

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

uppercase first character in a variable with bash

Not exactly what asked but quite helpful

declare -u foo #When the variable is assigned a value, all lower-case characters are converted to upper-case.

foo=bar
echo $foo
BAR

And the opposite

declare -l foo #When the variable is assigned a value, all upper-case characters are converted to lower-case.

foo=BAR
echo $foo
bar

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

Why is pydot unable to find GraphViz's executables in Windows 8?

On Mac brew install graphviz solved the problem for me.

ReactJS map through Object

Also you can use Lodash to direct convert object to array:

_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]

In your case:

_.toArray(subjects).map((subject, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">Name: {subject[name]}</span>
    </li>
))}

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

align 3 images in same row with equal spaces?

The modern approach: flexbox

Simply add the following CSS to the container element (here, the div):

div {
  display: flex;
  justify-content: space-between;
}

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The old way (for ancient browsers - prior to flexbox)

Use text-align: justify; on the container element.

Then stretch the content to take up 100% width

MARKUP

<div>
 <img src="http://placehold.it/100x100" alt=""  /> 
 <img src="http://placehold.it/100x100" alt=""  />
 <img src="http://placehold.it/100x100" alt="" />
</div>

CSS

div {
    text-align: justify;
}

div img {
    display: inline-block;
    width: 100px;
    height: 100px;
}

div:after {
    content: '';
    display: inline-block;
    width: 100%;
}

_x000D_
_x000D_
div {_x000D_
    text-align: justify;_x000D_
}_x000D_
_x000D_
div img {_x000D_
    display: inline-block;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
div:after {_x000D_
    content: '';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

MongoDB query with an 'or' condition

Using a $where query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.

An empty Regex or MaxKey (if you language supports it) are both good choices.

regex pattern to match the end of a string

Use the $ metacharacter to match the end of a string.

In Perl, this looks like:

my $str = 'red/white/blue';
my($last_match) = $str =~ m/.*\/(.*)$/;

Written in JavaScript, this looks like:

var str = 'red/white/blue'.match(/.*\/(.*)$/);

Dropdown select with images

Seems like a straightforward html menu would be simpler. Use html5 data attributes for values or whatever method you want to store them and css to handle images as backgrounds or put them in the html itself.

Edit: If you are forced to convert from an existing select that you can't get rid of, there are some good plugins as well to modify a select to html. Wijmo and Chosen are a couple that come to mind

AngularJS: How to run additional code after AngularJS has rendered a template?

In some scenarios where you update a service and redirect to a new view(page) and then your directive gets loaded before your services are updated then you can use $rootScope.$broadcast if your $watch or $timeout fails

View

<service-history log="log" data-ng-repeat="log in requiedData"></service-history>

Controller

app.controller("MyController",['$scope','$rootScope', function($scope, $rootScope) {

   $scope.$on('$viewContentLoaded', function () {
       SomeSerive.getHistory().then(function(data) {
           $scope.requiedData = data;
           $rootScope.$broadcast("history-updation");
       });
  });

}]);

Directive

app.directive("serviceHistory", function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
           log: '='
        },
        link: function($scope, element, attrs) {
            function updateHistory() {
               if(log) {
                   //do something
               }
            }
            $rootScope.$on("history-updation", updateHistory);
        }
   };
});

MVC4 StyleBundle not resolving images

After little investigation I concluded the followings: You have 2 options:

  1. go with transformations. Very usefull package for this: https://bundletransformer.codeplex.com/ you need following transformation for every problematic bundle:

    BundleResolver.Current = new CustomBundleResolver();
    var cssTransformer = new StyleTransformer();
    standardCssBundle.Transforms.Add(cssTransformer);
    bundles.Add(standardCssBundle);
    

Advantages: of this solution, you can name your bundle whatever you want => you can combine css files into one bundle from different directories. Disadvantages: You need to transform every problematic bundle

  1. Use the same relative root for the name of the bundle like where the css file is located. Advantages: there is no need for transformation. Disadvantages: You have limitation on combining css sheets from different directories into one bundle.

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

Plot a bar using matplotlib using a dictionary

You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range(len(D)), D.values(), align='center')  # python 2.x
# plt.xticks(range(len(D)), D.keys())  # in python 2.x

plt.show()

Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.

Using module 'subprocess' with timeout

You can do this using select

import subprocess
from datetime import datetime
from select import select

def call_with_timeout(cmd, timeout):
    started = datetime.now()
    sp = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    while True:
        p = select([sp.stdout], [], [], timeout)
        if p[0]:
            p[0][0].read()
        ret = sp.poll()
        if ret is not None:
            return ret
        if (datetime.now()-started).total_seconds() > timeout:
            sp.kill()
            return None

Fastest way to convert Image to Byte array

There is a RawFormat property of Image parameter which returns the file format of the image. You might try the following:

// extension method
public static byte[] imageToByteArray(this System.Drawing.Image image)
{
    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}

PHP - warning - Undefined property: stdClass - fix?

if(isset($response->records))
    print "we've got records!";

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

How to split a string between letters and digits (or between digits and letters)?

If you are looking for solution without using Java String functionality (i.e. split, match, etc.) then the following should help:

List<String> splitString(String string) {
        List<String> list = new ArrayList<String>();
        String token = "";
        char curr;
        for (int e = 0; e < string.length() + 1; e++) {
            if (e == 0)
                curr = string.charAt(0);
            else {
                curr = string.charAt(--e);
            }

            if (isNumber(curr)) {
                while (e < string.length() && isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            } else {
                while (e < string.length() && !isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            }

        }

        return list;
    }

boolean isNumber(char c) {
        return c >= '0' && c <= '9';
    }

This solution will split numbers and 'words', where 'words' are strings that don't contain numbers. However, if you like to have only 'words' containing English letters then you can easily modify it by adding more conditions (like isNumber method call) depending on your requirements (for example you may wish to skip words that contain non English letters). Also note that the splitString method returns ArrayList which later can be converted to String array.

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

MySQL 'Order By' - sorting alphanumeric correctly

This is a simple example.

SELECT HEX(some_col) h        
FROM some_table 
ORDER BY h

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

How to import existing *.sql files in PostgreSQL 8.4?

From the command line:

psql -f 1.sql
psql -f 2.sql

From the psql prompt:

\i 1.sql
\i 2.sql

Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:

for f in *.sql ; do psql -f $f ; done

Here's the documentation of the psql application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html

What are some alternatives to ReSharper?

The main alternative is:

  • CodeRush, by DevExpress. Most consider either this or ReSharper the way to go. You cannot go wrong with either. Both have their fans, both are powerful, and both have talented teams constantly improving them. We have all benefited from the competition between these two. I won't repeat the many good discussions/comparisons about them that can be found on Stack Overflow and elsewhere.

Another alternative worth checking out:

  • JustCode, by Telerik. This is new, still with kinks, but initial reports are positive. An advantage could be licensing with other Telerik products and integration with them. There are bundled licenses available that could make things cheaper / easier to handle.

Adding image to JFrame

As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class JPictureBox extends JComponent {

    private Icon icon = null;
    private final Dimension dimension = new Dimension(100, 100);
    private Image image = null;
    private ImageIcon ii = null;
    private SizeMode sizeMode = SizeMode.STRETCH;
    private int newHeight, newWidth, originalHeight, originalWidth;

    public JPictureBox() {
        JPictureBox.this.setPreferredSize(dimension);
        JPictureBox.this.setOpaque(false);
        JPictureBox.this.setSizeMode(SizeMode.STRETCH);
    }

    @Override
    public void paintComponent(Graphics g) {
        if (ii != null) {
            switch (getSizeMode()) {
                case NORMAL:
                    g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                case ZOOM:
                    aspectRatio();
                    g.drawImage(image, 0, 0, newWidth, newHeight, null);
                    break;
                case STRETCH:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
                    break;
                case CENTER:
                    g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                default:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
            }
        }
    }

    public Icon getIcon() {
        return icon;
    }

    public void setIcon(Icon icon) {
        this.icon = icon;
        ii = (ImageIcon) icon;
        image = ii.getImage();
        originalHeight = ii.getIconHeight();
        originalWidth = ii.getIconWidth();
    }

    public SizeMode getSizeMode() {
        return sizeMode;
    }

    public void setSizeMode(SizeMode sizeMode) {
        this.sizeMode = sizeMode;
    }

    public enum SizeMode {
        NORMAL,
        STRETCH,
        CENTER,
        ZOOM
    }

    private void aspectRatio() {
        if (ii != null) {
            newHeight = this.getHeight();
            newWidth = (originalWidth * newHeight) / originalHeight;
        }
    }

}

If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:

  • NORMAL value, the image is positioned in the upper-left corner of the JPictureBox.
  • STRETCH value causes the image to stretch or shrink to fit the JPictureBox.
  • ZOOM value causes the image to be stretched or shrunk to fit the JPictureBox; however, the aspect ratio in the original is maintained.
  • CENTER value causes the image to be centered in the client area.

If you want to learn more about this topic, you can check this video.

Also you can see the code on Gitlab or Github.

Check if xdebug is working

Starting with xdebug 3 you can use the following command line :

php -r "xdebug_info();"

And it will display useful information about your xdebug installation.

How to provide animation when calling another activity in Android?

You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.

Example:

@Override
public void onResume(){
    // TODO LC: preliminary support for views transitions
    this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Use a service api.

URL: https://fcm.googleapis.com/fcm/send

Method Type: POST

Headers:

Content-Type: application/json
Authorization: key=your api key

Body/Payload:

{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
  },
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
    },
  "to" : "to_id(firebase refreshedToken)"
} 

And with this in your app you can add below code in your activity to be called:

<intent-filter>
    <action android:name="OPEN_ACTIVITY_1" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Also check the answer on Firebase onMessageReceived not called when app in background

Map.Entry: How to use it?

Note that you can also create your own structures using a Map.Entry as the main type, using its basic implementation AbstractMap.SimpleEntry. For instance, if you wanted to have an ordered list of entries, you could write:

List<Map.Entry<String, Integer>> entries = new ArrayList<>();
entries.add(new AbstractMap.SimpleEntry<String, Integer>(myStringValue, myIntValue));

And so on. From there, you have a list of tuples. Very useful when you want ordered tuples and a basic Map is a no-go.

How to get file's last modified date on Windows command line?

you can get a files modified date using vbscript too

Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
WScript.Echo objFS.GetFile(strFile).DateLastModified

save the above as mygetdate.vbs and on command line

c:\test> cscript //nologo mygetdate.vbs myfile

JavaScript: Parsing a string Boolean value?

You can try the following:

function parseBool(val)
{
    if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
        return true;
    else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
        return false;

    return null;
}

If it's a valid value, it returns the equivalent bool value otherwise it returns null.

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

Constraint Layout Vertical Align Center

It's possible to set the center aligned view as an anchor for other views. In the example below "@+id/stat_2" centered horizontally in parent and it serves as an anchor for other views in this layout.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/stat_1"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="10"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/divider_1" />

    <TextView
        android:id="@+id/stat_detail_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Streak"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_1"
        app:layout_constraintStart_toStartOf="@+id/stat_1"
        app:layout_constraintEnd_toEndOf="@+id/stat_1" />

    <View
        android:id="@+id/divider_1"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginEnd="16dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/stat_2"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2" />

    <TextView
        android:id="@+id/stat_2"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="1"
        android:text="243"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

    <TextView
        android:id="@+id/stat_detail_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Calories Burned"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_2"
        app:layout_constraintStart_toStartOf="@+id/stat_2"
        app:layout_constraintEnd_toEndOf="@+id/stat_2" />

    <View
        android:id="@+id/divider_2"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:background="#ccc"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2"
        app:layout_constraintStart_toEndOf="@+id/stat_2"
        app:layout_constraintTop_toTopOf="@+id/stat_2" />

    <TextView
        android:id="@+id/stat_3"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="3200"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintStart_toEndOf="@+id/divider_2" />

    <TextView
        android:id="@+id/stat_detail_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Steps"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_3"
        app:layout_constraintStart_toStartOf="@+id/stat_3"
        app:layout_constraintEnd_toEndOf="@+id/stat_3" />

</android.support.constraint.ConstraintLayout>

Here's how it works on smallest smartphone (3.7 480x800 Nexus One) vs largest smartphone (5.5 1440x2560 Pixel XL)

Result view

Calling method using JavaScript prototype

No, you would need to give the do function in the constructor and the do function in the prototype different names.

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

Git: See my last commit

git log -1 --stat

could work

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

How to start rails server?

For rails 4.1.4 you can start server:

$ bin/rails server

Python - Create list with numbers between 2 values?

Use list comprehension in python. Since you want 16 in the list too.. Use x2+1. Range function excludes the higher limit in the function.

list=[x for x in range(x1,x2+1)]

PHP, Get tomorrows date from date

<? php 

//1 Day = 24*60*60 = 86400

echo date("d-m-Y", time()+86400); 

?>

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

Why not inherit from List<T>?

I think I don't agree with your generalization. A team isn't just a collection of players. A team has so much more information about it - name, emblem, collection of management/admin staff, collection of coaching crew, then collection of players. So properly, your FootballTeam class should have 3 collections and not itself be a collection; if it is to properly model the real world.

You could consider a PlayerCollection class which like the Specialized StringCollection offers some other facilities - like validation and checks before objects are added to or removed from the internal store.

Perhaps, the notion of a PlayerCollection betters suits your preferred approach?

public class PlayerCollection : Collection<Player> 
{ 
}

And then the FootballTeam can look like this:

public class FootballTeam 
{ 
    public string Name { get; set; }
    public string Location { get; set; }

    public ManagementCollection Management { get; protected set; } = new ManagementCollection();

    public CoachingCollection CoachingCrew { get; protected set; } = new CoachingCollection();

    public PlayerCollection Players { get; protected set; } = new PlayerCollection();
}

See whether an item appears more than once in a database column

It should be:

SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1

Regarding your initial query:

  1. You cannot do a SELECT * since this operation requires a GROUP BY and columns need to either be in the GROUP BY or in an aggregate function (i.e. COUNT, SUM, MIN, MAX, AVG, etc.)
  2. As this is a GROUP BY operation, a HAVING clause will filter it instead of a WHERE

Edit:

And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):

;WITH cte AS (
    SELECT  *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
    FROM    AXDelNotesNoTracking
)
SELECT  *
FROM    cte
WHERE   cte.Num > 1

Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.

Edit2:

The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.

SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
    (     SELECT SalesID
          FROM AXDelNotesNoTracking
          GROUP BY SalesID
          HAVING COUNT(*) > 1
    )
ORDER BY SalesID

Case-Insensitive List Search

You can use StringComparer:

    var list = new List<string>();
    list.Add("cat");
    list.Add("dog");
    list.Add("moth");

    if (list.Contains("MOTH", StringComparer.OrdinalIgnoreCase))
    {
        Console.WriteLine("found");
    }

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

If you want the sum of all bars to be equal unity, weight each bin by the total number of values:

weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)

Hope that helps, although the thread is quite old...

Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division

How to pass a null variable to a SQL Stored Procedure from C#.net code

Let's say the name of the parameter is "Id" in your SQL stored procedure, and the C# function you're using to call the database stored procedure is name of type int?. Given that, following might solve your issue :

public void storedProcedureName(Nullable<int> id, string name)
{
    var idParameter = id.HasValue ?
                new SqlParameter("Id", id) :
                new SqlParameter { ParameterName = "Id", SqlDbType = SqlDbType.Int, Value = DBNull.Value };

    // to be continued...

How to decrypt a password from SQL server?

A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!

See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/

Dynamic button click event handler

Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):

   Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    If sender.name = "radioFit_Components" And sender.visible Then
        If sender.checked Then
            For Each ctrl As Control In TabControl1.SelectedTab.Controls
                Select Case ctrl.Name
                    Case "embChartSSE_Components"
                        ctrl.BringToFront()
                    Case "embChartSSE_Fit_Curve"
                        ctrl.SendToBack()
                    Case "dgvFit_Components"
                        ctrl.BringToFront()
                End Select
            Next

        End If
    End If

End Sub

This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Screen Size Class

-

  1. Hidden on all .d-none

  2. Hidden only on xs .d-none .d-sm-block

  3. Hidden only on sm .d-sm-none .d-md-block

  4. Hidden only on md .d-md-none .d-lg-block

  5. Hidden only on lg .d-lg-none .d-xl-block

  6. Hidden only on xl .d-xl-none

  7. Visible on all .d-block

  8. Visible only on xs .d-block .d-sm-none

  9. Visible only on sm .d-none .d-sm-block .d-md-none

  10. Visible only on md .d-none .d-md-block .d-lg-none

  11. Visible only on lg .d-none .d-lg-block .d-xl-none

  12. Visible only on xl .d-none .d-xl-block

Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements

error: request for member '..' in '..' which is of non-class type

If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write

 type substance1();

but

 type substance;

Proxy Error 502 : The proxy server received an invalid response from an upstream server

I had this issue once. It turned out to be database query issue. After re-create tables and index it has been fixed.

Although it says proxy error, when you look at server log, it shows execute query timeout. This is what I had before and how I solved it.

Copying sets Java

Starting from Java 10:

Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);

Set.copyOf() returns an unmodifiable Set containing the elements of the given Collection.

The given Collection must not be null, and it must not contain any null elements.

Running conda with proxy

One mistake I was making was saving the file as a.condarc or b.condarc.

Save it only as .condarc and paste the following code in the file and save the file in your home directory. Make necessary changes to hostname, user etc.

channels:
- defaults

show_channel_urls: True
allow_other_channels: True

proxy_servers:
    http: http://user:pass@hostname:port
    https: http://user:pass@hostname:port


ssl_verify: False

How to filter a RecyclerView with a SearchView

In Adapter:

public void setFilter(List<Channel> newList){
        mChannels = new ArrayList<>();
        mChannels.addAll(newList);
        notifyDataSetChanged();
    }

In Activity:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toLowerCase();
                ArrayList<Channel> newList = new ArrayList<>();
                for (Channel channel: channels){
                    String channelName = channel.getmChannelName().toLowerCase();
                    if (channelName.contains(newText)){
                        newList.add(channel);
                    }
                }
                mAdapter.setFilter(newList);
                return true;
            }
        });

What is the best IDE to develop Android apps in?

You can also develop rich UI filled Android applications using Adobe AIR. If you plan to go that route then Flex Builder Burrito is the best IDE. Take a look at this post as to how easy it is to build an AIR4Android app http://blog.air4android.com/?p=13

Android - How to achieve setOnClickListener in Kotlin?

Add in build.gradle module file

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

For Activity add

private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

Add on click

binding.button.setOnClickListener { Log.d("TAG", "Example") }

UTF-8 encoding in JSP page

This thread can help you: Passing request parameters as UTF-8 encoded strings

Basically:

request.setCharacterEncoding("UTF-8");
String login = request.getParameter("login");
String password = request.getParameter("password");

Or you use javascript on jsp file:

var userInput = $("#myInput").val();            
var encodedUserInput = encodeURIComponent(userInput);
$("#hiddenImput").val(encodedUserInput);

and after recover on class:

String parameter = URLDecoder.decode(request.getParameter("hiddenImput"), "UTF-8");

Trying to Validate URL Using JavaScript

Someone mentioned the Jquery Validation plugin, seems overkill if you just want to validate the url, here is the line of regex from the plugin:

return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);

Here is where they got it from: http://projects.scottsplayground.com/iri/

Pointed out by @nhahtdh This has been updated to:

        // Copyright (c) 2010-2013 Diego Perini, MIT licensed
        // https://gist.github.com/dperini/729294
        // see also https://mathiasbynens.be/demo/url-regex
        // modified to allow protocol-relative URLs
        return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );

source: https://github.com/jzaefferer/jquery-validation/blob/c1db10a34c0847c28a5bd30e3ee1117e137ca834/src/core.js#L1349

Modify a Column's Type in sqlite3

It is possible by dumping, editing and reimporting the table.

This script will do it for you (Adapt the values at the start of the script to your needs):

#!/bin/bash

DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql

echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP

echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP

read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 

echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"

echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
  echo "DROP INDEX '$idx';" | sqlite3 $DB
done

echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB

Convert python long/int to fixed size byte array

Everyone has overcomplicated this answer:

some_int = <256 bit integer>
some_bytes = some_int.to_bytes(32, sys.byteorder)
my_bytearray = bytearray(some_bytes)

You just need to know the number of bytes that you are trying to convert. In my use cases, normally I only use this large of numbers for crypto, and at that point I have to worry about modulus and what-not, so I don't think this is a big problem to be required to know the max number of bytes to return.

Since you are doing it as 768-bit math, then instead of 32 as the argument it would be 96.

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

How can a windows service programmatically restart itself?

I don't think it can. When a service is "stopped", it gets totally unloaded.

Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.

Get key and value of object in JavaScript?

for (var i in a) {
   console.log(a[i],i)
}

Center Oversized Image in Div

i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center attribute to center it regardless of screen size

The infamous java.sql.SQLException: No suitable driver found

It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.

Windows JAR File Properties Dialog:
Windows JAR File Properties Dialog

Create a string with n characters

how about this?

public String fillSpaces(int len) {
    /* the spaces string should contain spaces exceeding the max needed */  
    String spaces = "                                                   ";
    return spaces.substring(0,len);
}

EDIT: I've written a simple code to test the concept and here what i found.

Method 1: adding single space in a loop:

  public String execLoopSingleSpace(int len){
    StringBuilder sb = new StringBuilder();

    for(int i=0; i < len; i++) {
        sb.append(' ');
    }

    return sb.toString();
  }

Method 2: append 100 spaces and loop, then substring:

  public String execLoopHundredSpaces(int len){
    StringBuilder sb = new StringBuilder("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");

    for (int i=0; i < len/100 ; i++) {
        sb.append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");
    }

    return sb.toString().substring(0,len);
  }

The result I get creating 12,345,678 spaces:

C:\docs\Projects> java FillSpace 12345678
method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
Process java exited with code 0

and for 10,000,000 spaces:

C:\docs\Projects> java FillSpace 10000000
method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
Process java exited with code 0

combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.

But please continue to comment :-)

Embed Google Map code in HTML with marker

I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_

Java JTextField with input hint

You could create your own:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {

  public static void main(String[] args) {

    final JFrame frame = new JFrame();

    frame.setLayout(new BorderLayout());

    final JTextField textFieldA = new HintTextField("A hint here");
    final JTextField textFieldB = new HintTextField("Another hint here");

    frame.add(textFieldA, BorderLayout.NORTH);
    frame.add(textFieldB, BorderLayout.CENTER);
    JButton btnGetText = new JButton("Get text");

    btnGetText.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String message = String.format("textFieldA='%s', textFieldB='%s'",
            textFieldA.getText(), textFieldB.getText());
        JOptionPane.showMessageDialog(frame, message);
      }
    });

    frame.add(btnGetText, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.pack();
  }
}

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Unknown column in 'field list' error on MySQL Update query

You might check your choice of quotes (use double-/ single quotes for values, strings, etc and backticks for column-names).

Since you only want to update the table master_user_profile I'd recommend a nested query:

UPDATE
   master_user_profile
SET
   master_user_profile.fellow = 'y'
WHERE
   master_user_profile.user_id IN (
      SELECT tran_user_branch.user_id
      FROM tran_user_branch WHERE tran_user_branch.branch_id = 17);

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

Make Adobe fonts work with CSS3 @font-face in IE9

If you want to do this with a Python script instead of having to run C / PHP code, here's a Python3 function that you can use to remove the embedding permissions from the font:

def convert_restricted_font(filename):
with open(filename, 'rb+') as font:

    font.read(12)
    while True:
        _type = font.read(4)
        if not _type:
            raise Exception('Could not read the table definitions of the font.')
        try:
            _type = _type.decode()
        except UnicodeDecodeError:
            pass
        except Exception as err:
            pass
        if _type != 'OS/2':
            continue
        loc = font.tell()
        font.read(4)
        os2_table_pointer = int.from_bytes(font.read(4), byteorder='big')
        length = int.from_bytes(font.read(4), byteorder='big')
        font.seek(os2_table_pointer + 8)

        fs_type = int.from_bytes(font.read(2), byteorder='big')
        print(f'Installable Embedding: {fs_type == 0}')
        print(f'Restricted License: {fs_type & 2}')
        print(f'Preview & Print: {fs_type & 4}')
        print(f'Editable Embedding: {fs_type & 8}')

        print(f'No subsetting: {fs_type & 256}')
        print(f'Bitmap embedding only: {fs_type & 512}')

        font.seek(font.tell()-2)
        installable_embedding = 0 # True
        font.write(installable_embedding.to_bytes(2, 'big'))
        font.seek(os2_table_pointer)
        checksum = 0
        for i in range(length):
            checksum += ord(font.read(1))
        font.seek(loc)
        font.write(checksum.to_bytes(4, 'big'))
        break


if __name__ == '__main__':
    convert_restricted_font("19700-webfont.ttf")

it works, but I ended up solving the problem of loading fonts in IE by https like this this

thanks NobleUplift

Original source in C can be found here.

Is JavaScript's "new" keyword considered harmful?

Case 1: new isn't required and should be avoided

var str = new String('asd');  // type: object
var str = String('asd');      // type: string

var num = new Number(12);     // type: object
var num = Number(12);         // type: number

Case 2: new is required, otherwise you'll get an error

new Date().getFullYear();     // correct, returns the current year, i.e. 2010
Date().getFullYear();         // invalid, returns an error

Is there a MessageBox equivalent in WPF?

If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows

here is xaml :

<Window x:Class="popup.MessageboxNew"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:popup"
        mc:Ignorable="d"
        Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
        >
    <Window.Resources>

    </Window.Resources>
    <Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Window.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <Grid Loaded="FrameworkElement_OnLoaded">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border Name="Mask" CornerRadius="8" Background="White" />
            <Grid x:Name="Grid" Background="White">
                <Grid.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=Mask}"/>
                </Grid.OpacityMask>
                <StackPanel Name="StackPanel" >
                    <TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14" 
                             Foreground="Black" FontWeight="Normal"
                             Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
                    <DockPanel Name="ContentHost" Margin="0,10,0,10" >
                        <TextBlock Margin="10" Name="Textbar"></TextBlock>
                    </DockPanel>
                    <DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
                        <Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
                        <Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
                    </DockPanel>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

for cs of this file :

public partial class MessageboxNew : Window
    {
        public MessageboxNew()
        {
            InitializeComponent();
            //second time show error solved
            if (Application.Current == null) new Application();
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.MouseDown += delegate { DragMove(); };
        }
    }

then create a class to use this :

public class Mk_MessageBox
{
    public static bool? Show(string title, string text)
    {
        MessageboxNew msg = new MessageboxNew
        {
            TitleBar = {Text = title},
            Textbar = {Text = text}
        };
        msg.noBtn.Focus();
        return msg.ShowDialog();
    }
}

now you can create your message box like this:

var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
            if (result == true)
            {
                // whatever
            }

copy this to App.xaml inside

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
            <!-- Accent and AppTheme setting -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />

            <!--two new guys-->
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />

            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

--------------IMAGE of Result-----------------

My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/

for logic how can i make my own messagebox

What's the difference between a temp table and table variable in SQL Server?

In which scenarios does one out-perform the other?

For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

How do I install pip on macOS or OS X?

The simplest solution is to follow the installation instruction from pip's home site.

Basically, this consists in:

  • downloading get-pip.py. Be sure to do this by following a trusted link since you will have to run the script as root.
  • call sudo python get-pip.py

The main advantage of that solution is that it install pip for the python version that has been used to run get-pip.py, which means that if you use the default OS X installation of python to run get-pip.py you will install pip for the python install from the system.

Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.

How to cut first n and last n columns?

Cut can take several ranges in -f:

Columns up to 4 and from 7 onwards:

cut -f -4,7-

or for fields 1,2,5,6 and from 10 onwards:

cut -f 1,2,5,6,10-

etc

How can I force a long string without any blank to be wrapped?

for block elements:

_x000D_
_x000D_
<textarea style="width:100px; word-wrap:break-word;">_x000D_
  ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

for inline elements:

_x000D_
_x000D_
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
   ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
_x000D_
_x000D_

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Call Python function from MATLAB

A little known (and little documented) fact about MATLAB's system() function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL or MATLAB_SHELL at the time of starting MATLAB. So if you start MATLAB with

SHELL='/usr/bin/python' matlab

any subsequent system() calls will use Python instead of your default shell as an interpreter.

Android Studio: Gradle: error: cannot find symbol variable

Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file

my_file.xml
my_file.xml(v21)

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is what worked for me:

Log on SSIS with Windows authentication.

1. Open services and find MSSQL NT Service account name and copy it:

enter image description here

2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**

enter image description here

  1. You will probably get "Multiple names found error", just select MSSQL user:

enter image description here

Your BULK INSERT query should run fine now. If problem persists try adding SQL Server Agent account to folder permissions in same way. Make sure you restart MSSQL server in services after you are done.

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

What is thread Safe in java?

As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.

Consider the following method:

private int myInt = 0;
public int AddOne()
{
    int tmp = myInt;
    tmp = tmp + 1;
    myInt = tmp;
    return tmp;
}

Now thread A and thread B both would like to execute AddOne(). but A starts first and reads the value of myInt (0) into tmp. Now for some reason the scheduler decides to halt thread A and defer execution to thread B. Thread B now also reads the value of myInt (still 0) into it's own variable tmp. Thread B finishes the entire method, so in the end myInt = 1. And 1 is returned. Now it's Thread A's turn again. Thread A continues. And adds 1 to tmp (tmp was 0 for thread A). And then saves this value in myInt. myInt is again 1.

So in this case the method AddOne() was called two times, but because the method was not implemented in a thread safe way the value of myInt is not 2, as expected, but 1 because the second thread read the variable myInt before the first thread finished updating it.

Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.

Using cut command to remove multiple columns

You should be able to continue the sequences directly in your existing -f specification.

To skip both 5 and 7, try:

cut -d, -f-4,6-6,8-

As you're skipping a single sequential column, this can also be written as:

cut -d, -f-4,6,8-

To keep it going, if you wanted to skip 5, 7, and 11, you would use:

cut -d, -f-4,6-6,8-10,12-

To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:

cut -d, -f2-4,6-10,12-20

So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".

AngularJs event to call after content is loaded

I use setInterval to wait for the content loaded. I hope this can help you to solve that problem.

var $audio = $('#audio');
var src = $audio.attr('src');
var a;
a = window.setInterval(function(){
    src = $audio.attr('src');
    if(src != undefined){
        window.clearInterval(a);
        $('audio').mediaelementplayer({
            audioWidth: '100%'
        });
    }
}, 0);

Difference between String replace() and replaceAll()

As alluded to in wickeD's answer, with replaceAll the replacement string is handled differently between replace and replaceAll. I expected a[3] and a[4] to have the same value, but they are different.

public static void main(String[] args) {
    String[] a = new String[5];
    a[0] = "\\";
    a[1] = "X";
    a[2] = a[0] + a[1];
    a[3] = a[1].replaceAll("X", a[0] + "X");
    a[4] = a[1].replace("X", a[0] + "X");

    for (String s : a) {
        System.out.println(s + "\t" + s.length());
    }
}

The output of this is:

\   1
X   1
\X  2
X   1
\X  2

This is different from perl where the replacement does not require the extra level of escaping:

#!/bin/perl
$esc = "\\";
$s = "X";

$s =~ s/X/${esc}X/;
print "$s " . length($s) . "\n";

which prints \X 2

This can be quite a nuisance, as when trying to use the value returned by java.sql.DatabaseMetaData.getSearchStringEscape() with replaceAll().

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

node.js Error: connect ECONNREFUSED; response from server

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

Installing mysql-python on Centos

I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.

For me it worked with the following command:

# pip install mysql-python

Note pre-requisites here:

Install Python pip:

# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

# yum -y update
Reboot the machine (if kernel is also updated)

# yum -y install python-pip

Install Python devel packages:

# yum install python-devel

Install MySQL devel packages:

# yum install mysql-devel

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

to pass many options you can pass a object to a @Input decorator with custom data in a single line.

In the template

<li *ngFor = 'let opt of currentQuestion.options' 
                [selectable] = 'opt'
                [myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
                (selectedOption) = 'onOptionSelection($event)' >
     {{opt.option}}
</li>

so in Directive class

@Directive({
  selector: '[selectable]'
})

export class SelectableDirective{
  private el: HTMLElement;
  @Input('selectable') option:any;
  @Input('myOptions') data;

  //do something with data.first
  ...
  // do something with data.second
}

What is an index in SQL?

Indexes are all about finding data quickly.

Indexes in a database are analogous to indexes that you find in a book. If a book has an index, and I ask you to find a chapter in that book, you can quickly find that with the help of the index. On the other hand, if the book does not have an index, you will have to spend more time looking for the chapter by looking at every page from the start to the end of the book.

In a similar fashion, indexes in a database can help queries find data quickly. If you are new to indexes, the following videos, can be very useful. In fact, I have learned a lot from them.

Index Basics
Clustered and Non-Clustered Indexes
Unique and Non-Unique Indexes
Advantages and disadvantages of indexes

Disable browser cache for entire ASP.NET website

I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

error: expected declaration or statement at end of input in c

For me I just noticed that it was my .h archive with a '{'. Maye that can help someone =)

Allow only numbers and dot in script

Hope this could help someone

$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});

Change drive in git bash for windows

Now which drive letter did that removable device get?

Two ways to locate e.g. a USB-disk in git Bash:


    $ cat /proc/partitions
    major minor  #blocks  name   win-mounts

        8     0 500107608 sda
        8     1   1048576 sda1
        8     2    131072 sda2
        8     3 496305152 sda3   C:\
        8     4   1048576 sda4
        8     5   1572864 sda5
        8    16         0 sdb
        8    32         0 sdc
        8    48         0 sdd
        8    64         0 sde
        8    80   3952639 sdf
        8    81   3950592 sdf1   E:\

    $ mount
    C:/Program Files/Git on / type ntfs (binary,noacl,auto)
    C:/Program Files/Git/usr/bin on /bin type ntfs (binary,noacl,auto)
    C:/Users/se2982/AppData/Local/Temp on /tmp type ntfs (binary,noacl,posix=0,usertemp)
    C: on /c type ntfs (binary,noacl,posix=0,user,noumount,auto)
    E: on /e type vfat (binary,noacl,posix=0,user,noumount,auto)
    G: on /g type ntfs (binary,noacl,posix=0,user,noumount,auto)
    H: on /h type ntfs (binary,noacl,posix=0,user,noumount,auto)

... so; likely drive letter in this example => /e (or E:\ if you must), when knowing that C, G, and H are other things (in Windows).

'list' object has no attribute 'shape'

Use numpy.array to use shape attribute.

>>> import numpy as np
>>> X = np.array([
...     [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
...     [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
...     [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]
... ])
>>> X.shape
(3L, 3L, 1L)

NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.

Generate random numbers uniformly over an entire range

@Solution ((double) rand() / (RAND_MAX+1)) * (max-min+1) + min

Warning: Don't forget due to stretching and possible precision errors (even if RAND_MAX were large enough), you'll only be able to generate evenly distributed "bins" and not all numbers in [min,max].


@Solution: Bigrand

Warning: Note that this doubles the bits, but still won't be able to generate all numbers in your range in general, i.e., it is not necessarily true that BigRand() will generate all numbers between in its range.


Info: Your approach (modulo) is "fine" as long as the range of rand() exceeds your interval range and rand() is "uniform". The error for at most the first max - min numbers is 1/(RAND_MAX +1).

Also, I suggest to switch to the new random packagee in C++11 too, which offers better and more varieties of implementations than rand().

Windows batch: formatted date into variable

Just use the %date% variable:

echo %date%

How can foreign key constraints be temporarily disabled using T-SQL?

If you want to disable all constraints in the database just run this code:

-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

To switch them back on, run: (the print is optional of course and it is just listing the tables)

-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

If you are deleting all the data you may find this solution to be helpful.

Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.

Full Screen DialogFragment in Android

According to this link DialogFragment fullscreen shows padding on sides this will work like a charm.

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    // the content
    final RelativeLayout root = new RelativeLayout(getActivity());
    root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    // creating the fullscreen dialog
    final Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(root);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    return dialog;
}

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

parseInt with jQuery

var test = parseInt($("#testid").val());

How to pass the button value into my onclick event function?

Maybe you can take a look at closure in JavaScript. Here is a working solution:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8" />_x000D_
        <title>Test</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <p class="button">Button 0</p>_x000D_
        <p class="button">Button 1</p>_x000D_
        <p class="button">Button 2</p>_x000D_
        <script>_x000D_
            var buttons = document.getElementsByClassName('button');_x000D_
            for (var i=0 ; i < buttons.length ; i++){_x000D_
              (function(index){_x000D_
                buttons[index].onclick = function(){_x000D_
                  alert("I am button " + index);_x000D_
                };_x000D_
              })(i)_x000D_
            }_x000D_
        </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

mysql_* functions have been removed in PHP 7.

You now have two alternatives: MySQLi and PDO.

The following is a before (-) and after (+) comparison of a migration to the MySQLi alternative, taken straight out of working code:

-if (!$dbLink = mysql_connect($dbHost, $dbUser, $dbPass))
+if (!$dbLink = mysqli_connect($dbHost, $dbUser, $dbPass))

-if (!mysql_select_db($dbName, $dbLink))
+if (!mysqli_select_db($dbLink, $dbName))

-if (!$result = mysql_query($query, $dbLink)) {
+if (!$result = mysqli_query($dbLink, $query)) {

-if (mysql_num_rows($result) > 0) {
+if (mysqli_num_rows($result) > 0) {

-while ($row = mysql_fetch_array( $result, MYSQL_ASSOC )) {
+while ($row = mysqli_fetch_array( $result, MYSQLI_ASSOC )) {

-mysql_close($dbLink);
+mysqli_close($dbLink);

Sorting by date & time in descending order?

putting the UNIX_TIMESTAMP will do the trick.

SELECT id, NAME, form_id, UNIX_TIMESTAMP(updated_at) AS DATE
    FROM wp_frm_items
    WHERE user_id = 11 && form_id=9
    ORDER BY DATE DESC

Checkout one file from Subversion

I wanted to checkout a single file to a directory, which was not part of a working copy.

Let's get the file at the following URL: http://subversion.repository.server/repository/module/directory/myfile

svn co  http://subversion.repository.server/repository/module/directory/myfile /**directoryb**

So I checked out the given directory containing the target file I wanted to get to a dummy directory, (say etcb for the URL ending with /etc).

Then I emptied the file .svn/entries from all files of the target directory I didn't needed, to leave just the file I wanted. In this .svn/entries file, you have a record for each file with its attributes so leave just the record concerning the file you want to get and save.

Now you need just to copy then ''.svn'' to the directory which will be a new "working copy". Then you just need to:

cp .svn /directory
cd /directory
svn update myfile

Now the directory directory is under version control. Do not forget to remove the directory directoryb which was just a ''temporary working copy''.

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

How can I make XSLT work in chrome?

As close as I can tell, Chrome is looking for the header

Content-Type: text/xml

Then it works --- other iterations have failed.

Make sure your web server is providing this. It also explains why it fails for file://URI xml files.

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

How to host material icons offline?

With angular cli

npm install angular-material-icons --save

or

npm install material-design-icons-iconfont --save

material-design-icons-iconfont is the latest updated version of the icons. angular-material-icons is not updated for a long time

Wait wait wait install to be done and then add it to angular.json -> projects -> architect -> styles

 "styles": [
          "node_modules/material-design-icons/iconfont/material-icons.css",
          "src/styles.scss"
        ],

or if you installed material-desing-icons-iconfont then

"styles": [
              "node_modules/material-design-icons-iconfont/dist/material-design-icons.css",
              "src/styles.scss"
            ],

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

ERROR: Sonar server 'http://localhost:9000' can not be reached

Please check if postgres(or any other database service) is running properly.

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.