Programs & Examples On #Task parallel library

The Task Parallel Library is part of .NET 4 and .NET 4.5. It is a set of APIs to enable developers to program asynchronous applications.

Synchronously waiting for an async operation, and why does Wait() freeze the program here

The await inside your asynchronous method is trying to come back to the UI thread.

Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.

Moving the async call to Task.Run() solves the issue.
Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.

Alternatively, you could call StartAsTask().ConfigureAwait(false) before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.

Best practice to call ConfigureAwait for all server-side code

I have some general thoughts about the implementation of Task:

  1. Task is disposable yet we are not supposed to use using.
  2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
  3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
  4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
  5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

How can I tell Moq to return a Task?

Your method doesn't have any callbacks so there is no reason to use .CallBack(). You can simply return a Task with the desired values using .Returns() and Task.FromResult, e.g.:

MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.FromResult(someValue));

Update 2014-06-22

Moq 4.2 has two new extension methods to assist with this.

mock.Setup(arg=>arg.DoSomethingAsync())
    .ReturnsAsync(someValue);

mock.Setup(arg=>arg.DoSomethingAsync())        
    .ThrowsAsync(new InvalidOperationException());

Update 2016-05-05

As Seth Flowers mentions in the other answer, ReturnsAsync is only available for methods that return a Task<T>. For methods that return only a Task,

.Returns(Task.FromResult(default(object)))

can be used.

As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);, e.g.:

mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

Passing a method parameter using Task.Factory.StartNew

class Program
{
    static void Main(string[] args)
    {
        Task.Factory.StartNew(() => MyMethod("param value"));
    }

    private static void MyMethod(string p)
    {
        Console.WriteLine(p);
    }
}

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

It's weekend now!

    public async void Go()
    {
        Console.WriteLine("Start fosterage...");

        var t1 = Sleep(5000, "Kevin");
        var t2 = Sleep(3000, "Jerry");
        var result = await Task.WhenAll(t1, t2);

        Console.WriteLine($"My precious spare time last for only {result.Max()}ms");
        Console.WriteLine("Press any key and take same beer...");
        Console.ReadKey();
    }

    private static async Task<int> Sleep(int ms, string name)
    {
            Console.WriteLine($"{name} going to sleep for {ms}ms :)");
            await Task.Delay(ms);
            Console.WriteLine("${name} waked up after {ms}ms :(";
            return ms;
    }

Nesting await in Parallel.ForEach

Using DataFlow as svick suggested may be overkill, and Stephen's answer does not provide the means to control the concurrency of the operation. However, that can be achieved rather simply:

public static async Task RunWithMaxDegreeOfConcurrency<T>(
     int maxDegreeOfConcurrency, IEnumerable<T> collection, Func<T, Task> taskFactory)
{
    var activeTasks = new List<Task>(maxDegreeOfConcurrency);
    foreach (var task in collection.Select(taskFactory))
    {
        activeTasks.Add(task);
        if (activeTasks.Count == maxDegreeOfConcurrency)
        {
            await Task.WhenAny(activeTasks.ToArray());
            //observe exceptions here
            activeTasks.RemoveAll(t => t.IsCompleted); 
        }
    }
    await Task.WhenAll(activeTasks.ToArray()).ContinueWith(t => 
    {
        //observe exceptions in a manner consistent with the above   
    });
}

The ToArray() calls can be optimized by using an array instead of a list and replacing completed tasks, but I doubt it would make much of a difference in most scenarios. Sample usage per the OP's question:

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

EDIT Fellow SO user and TPL wiz Eli Arbel pointed me to a related article from Stephen Toub. As usual, his implementation is both elegant and efficient:

public static Task ForEachAsync<T>(
      this IEnumerable<T> source, int dop, Func<T, Task> body) 
{ 
    return Task.WhenAll( 
        from partition in Partitioner.Create(source).GetPartitions(dop) 
        select Task.Run(async delegate { 
            using (partition) 
                while (partition.MoveNext()) 
                    await body(partition.Current).ContinueWith(t => 
                          {
                              //observe exceptions
                          });
                      
        })); 
}

If my interface must return Task what is the best way to have a no-operation implementation?

Recently encountered this and kept getting warnings/errors about the method being void.

We're in the business of placating the compiler and this clears it up:

    public async Task MyVoidAsyncMethod()
    {
        await Task.CompletedTask;
    }

This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

Asynchronously wait for Task<T> to complete with timeout

So this is ancient, but there's a much better modern solution. Not sure what version of c#/.NET is required, but this is how I do it:


... Other method code not relevant to the question.

// a token source that will timeout at the specified interval, or if cancelled outside of this scope
using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token);

async Task<MessageResource> FetchAsync()
{
    try
    {
        return await MessageResource.FetchAsync(m.Sid);
    } catch (TaskCanceledException e)
    {
        if (timeoutTokenSource.IsCancellationRequested)
            throw new TimeoutException("Timeout", e);
        throw;
    }
}

return await Task.Run(FetchAsync, linkedTokenSource.Token);

the CancellationTokenSource constructor takes a TimeSpan parameter which will cause that token to cancel after that interval has elapsed. You can then wrap your async (or syncronous, for that matter) code in another call to Task.Run, passing the timeout token.

This assumes you're passing in a cancellation token (the token variable). If you don't have a need to cancel the task separately from the timeout, you can just use timeoutTokenSource directly. Otherwise, you create linkedTokenSource, which will cancel if the timeout ocurrs, or if it's otherwise cancelled.

We then just catch OperationCancelledException and check which token threw the exception, and throw a TimeoutException if a timeout caused this to raise. Otherwise, we rethrow.

Also, I'm using local functions here, which were introduced in C# 7, but you could easily use lambda or actual functions to the same affect. Similarly, c# 8 introduced a simpler syntax for using statements, but those are easy enough to rewrite.

Parallel foreach with asynchronous lambda

In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:

var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);

Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)

Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.

Task.Run with Parameter(s)?

Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct

struct Job { public int P1; public int P2; }
…
for (int i = 0; i < 100; i++) {
    var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
    Task.Run(() => DoSomething(job));
}

Running multiple async tasks and waiting for them all to complete

The best option I've seen is the following extension method:

public static Task ForEachAsync<T>(this IEnumerable<T> sequence, Func<T, Task> action) {
    return Task.WhenAll(sequence.Select(action));
}

Call it like this:

await sequence.ForEachAsync(item => item.SomethingAsync(blah));

Or with an async lambda:

await sequence.ForEachAsync(async item => {
    var more = await GetMoreAsync(item);
    await more.FrobbleAsync();
});

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Use FromResult Method

public async Task<string> GetString()
{
   System.Threading.Thread.Sleep(5000);
   return await Task.FromResult("Hello");
}

Using async/await for multiple tasks

You can use Task.WhenAll function that you can pass n tasks; Task.WhenAll will return a task which runs to completion when all the tasks that you passed to Task.WhenAll complete. You have to wait asynchronously on Task.WhenAll so that you'll not block your UI thread:

   public async Task DoSomeThing() {

       var Task[] tasks = new Task[numTasks];
       for(int i = 0; i < numTask; i++)
       {
          tasks[i] = CallSomeAsync();
       }
       await Task.WhenAll(tasks);
       // code that'll execute on UI thread
   }

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

var response = taskwithresponse.Result;
          var jsonString = response.ReadAsAsync<List<Job>>().Result;

HttpClient - A task was cancelled?

Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)

What is the difference between task and thread?

In computer science terms, a Task is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.) Basically, a Task<T> "promises" to return you a T, but not right now honey, I'm kinda busy, why don't you come back later?

A Thread is a way of fulfilling that promise. But not every Task needs a brand-new Thread. (In fact, creating a thread is often undesirable, because doing so is much more expensive than re-using an existing thread from the thread pool. More on that in a moment.) If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and wait for the data when it can be servicing other requests. Instead, the Task might register a callback to receive the value(s) when they're ready.

In particular, the Task does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might that it takes a long time to fetch. Only in the former case would you use a Thread to run a Task. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs. For example, in Windows, a thread weighs 12 KiByte (I think), in Linux, a thread weighs as little as 4 KiByte, in Erlang/BEAM even just 400 Byte. In .NET, it's 1 MiByte!)

WaitAll vs WhenAll

What do they do:

  • Internally both do the same thing.

What's the difference:

  • WaitAll is a blocking call
  • WhenAll - not - code will continue executing

Use which when:

  • WaitAll when cannot continue without having the result
  • WhenAll when what just to be notified, not blocked

No ConcurrentList<T> in .Net 4.0?

System.Collections.Generic.List<t> is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)

Awaiting multiple Tasks with different results

Use Task.WhenAll and then await the results:

var tCat = FeedCat();
var tHouse = SellHouse();
var tCar = BuyCar();
await Task.WhenAll(tCat, tHouse, tCar);
Cat cat = await tCat;
House house = await tHouse;
Tesla car = await tCar; 
//as they have all definitely finished, you could also use Task.Value.

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

What is the difference between Task.Run() and Task.Factory.StartNew()

The Task.Run got introduced in newer .NET framework version and it is recommended.

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task.

The Task.Factory.StartNew has more options, the Task.Run is a shorthand:

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

And by shorthand I mean a technical shortcut:

public static Task Run(Action action)
{
    return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
        TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}

Calling async method synchronously

Microsoft Identity has extension methods which call async methods synchronously. For example there is GenerateUserIdentityAsync() method and equal CreateIdentity()

If you look at UserManagerExtensions.CreateIdentity() it look like this:

 public static ClaimsIdentity CreateIdentity<TUser, TKey>(this UserManager<TUser, TKey> manager, TUser user,
        string authenticationType)
        where TKey : IEquatable<TKey>
        where TUser : class, IUser<TKey>
    {
        if (manager == null)
        {
            throw new ArgumentNullException("manager");
        }
        return AsyncHelper.RunSync(() => manager.CreateIdentityAsync(user, authenticationType));
    }

Now lets see what AsyncHelper.RunSync does

  public static TResult RunSync<TResult>(Func<Task<TResult>> func)
    {
        var cultureUi = CultureInfo.CurrentUICulture;
        var culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew(() =>
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap().GetAwaiter().GetResult();
    }

So, this is your wrapper for async method. And please don't read data from Result - it will potentially block your code in ASP.

There is another way - which is suspicious for me, but you can consider it too

  Result r = null;

            YourAsyncMethod()
                .ContinueWith(t =>
                {
                    r = t.Result;
                })
                .Wait();

How to safely call an async method in C# without await

I end up with this solution :

public async Task MyAsyncMethod()
{
    // do some stuff async, don't return any data
}

public string GetStringData()
{
    // Run async, no warning, exception are catched
    RunAsync(MyAsyncMethod()); 
    return "hello world";
}

private void RunAsync(Task task)
{
    task.ContinueWith(t =>
    {
        ILog log = ServiceLocator.Current.GetInstance<ILog>();
        log.Error("Unexpected Error", t.Exception);

    }, TaskContinuationOptions.OnlyOnFaulted);
}

How to cancel a Task in await?

Or, in order to avoid modifying slowFunc (say you don't have access to the source code for instance):

var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code

//original code: await task;  
await Task.WhenAny(task, completionSource.Task); //New code

You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:

await Task.WhenAny(task, source.Token.AsTask());

Catch an exception thrown by an async void method

Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.

public async Task DoFoo()
    {
        try
        {
            return await Foo();
        }
        catch (ProtocolException ex)
        {
            /* Exception with chronological stack trace */     
        }
    }

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

check if "it's a number" function in Oracle

One additional idea, mentioned here is to use a regular expression to check:

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^[[:digit:]]+$');

The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I had this issue when using the history API.

window.history.pushState(null, null, URL);

Even with a local server (localhost), you want to add 'http://' to your URL so that you have something similar to:

http://localhost...

TypeScript: casting HTMLElement

As of TypeScript 0.9 the lib.d.ts file uses specialized overload signatures that return the correct types for calls to getElementsByTagName.

This means you no longer need to use type assertions to change the type:

// No type assertions needed
var script: HTMLScriptElement = document.getElementsByTagName('script')[0];
alert(script.type);

How to check undefined in Typescript

It's because it's already null or undefined. Null or undefined does not have any type. You can check if it's is undefined first. In typescript (null == undefined) is true.

  if (uemail == undefined) {
      alert('undefined');
  } else {
      alert('defined');
  }

or

  if (uemail == null) {
      alert('undefined');
  } else {
      alert('defined');
  }

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

first call Looper.prepare() and then call Toast.makeText().show() last call Looper.loop() like:

Looper.prepare() // to be able to make toast
Toast.makeText(context, "not connected", Toast.LENGTH_LONG).show()
Looper.loop()

What is the meaning of 'No bundle URL present' in react-native?

following these steps:

  • open ios file project with xcode
  • in project bundle delete main.jsbundle file
  • add new empty file by main.jsbundle name
  • Run comment: react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios
  • now react-native run-ios

youtube link: https://www.youtube.com/watch?v=eCs2GsWNkoo

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

How to create an android app using HTML 5

When people talk about HTML5 applications they're most likely talking about writing just a simple web page or embedding a web page into their app (which will essentially provide the user interface). For the later there are different frameworks available, e.g. PhoneGap. These are used to provide more than the default browser features (e.g. multi touch) as well as allowing the app to run seamingly "standalone" and without the browser's navigation bars etc.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

cURL error 60: SSL certificate: unable to get local issuer certificate

If you are using PHP 5.6 with Guzzle, Guzzle has switched to using the PHP libraries autodetect for certificates rather than it's process (ref). PHP outlines the changes here.

Finding out Where PHP/Guzzle is Looking for Certificates

You can dump where PHP is looking using the following PHP command:

 var_dump(openssl_get_cert_locations());

Getting a Certificate Bundle

For OS X testing, you can use homebrew to install openssl brew install openssl and then use openssl.cafile=/usr/local/etc/openssl/cert.pem in your php.ini or Zend Server settings (under OpenSSL).

A certificate bundle is also available from curl/Mozilla on the curl website: https://curl.haxx.se/docs/caextract.html

Telling PHP Where the Certificates Are

Once you have a bundle, either place it where PHP is already looking (which you found out above) or update openssl.cafile in php.ini. (Generally, /etc/php.ini or /etc/php/7.0/cli/php.ini or /etc/php/php.ini on Unix.)

How to get a value from the last inserted row?

The sequences in postgresql are transaction safe. So you can use the

currval(sequence)

Quote:

currval

Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer even if other sessions are executing nextval meanwhile.

CSS background image alt attribute

Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.

It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.

The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.

HTML

<div class="hotwire-fitness" title="Fitness Centre"></div>

CSS

.hotwire-fitness {
    float: left;
    margin-right: 5px;
    background: url(/prostyle/images/new_amenities.png) -71px 0;
    width: 21px;
    height: 21px;
}

According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute

Title

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

alt

The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.

A text equivalent brings the following benefits to your website and its visitors in the following common situations:

  • nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
  • some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
  • search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

EDIT: Courtesy of @Laurynas, consider this:

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

Programmatically obtain the phone number of the Android phone

This is a more simplified answer:

public String getMyPhoneNumber()
{
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
            .getLine1Number();
}

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

Create Directory if it doesn't exist with Ruby

How about just Dir.mkdir('dir') rescue nil ?

Prevent screen rotation on Android

You can try This way

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Login_Activity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Python Pandas : pivot table with aggfunc = count unique distinct

aggfunc=pd.Series.nunique will only count unique values for a series - in this case count the unique values for a column. But this doesn't quite reflect as an alternative to aggfunc='count'

For simple counting, it better to use aggfunc=pd.Series.count

Short form for Java if statement

Use the ternary operator:

name = ((city.getName() == null) ? "N/A" : city.getName());

I think you have the conditions backwards - if it's null, you want the value to be "N/A".

What if city is null? Your code *hits the bed in that case. I'd add another check:

name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());

Undoing a git rebase

git reset --hard origin/{branchName}

is the correct solution to reset all your local changes done by rebase.

html button to send email

As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.

But here's a working example:

HTML (with Bootstrap styles):

<p><input id="subject" type="text" placeholder="type your subject here" 
    class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here" 
    class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>

JavaScript (with jQuery):

<script type="text/javascript">
    function loadEvents() {
        var mailString;
        function updateMailString() {
            mailString = '?subject=' + encodeURIComponent($('#subject').val())
                + '&body=' + encodeURIComponent($('#message').val());
            $('#mail-link').attr('href',  'mailto:[email protected]' + mailString);
        }
        $( "#subject" ).focusout(function() { updateMailString(); });
        $( "#message" ).focusout(function() { updateMailString(); });
        updateMailString();
    }
</script>

Notes:

  • The <form> element with associated action attribute is not used.
  • The <input> element of type button is also not used.
    • <a> styled as a button (here using Bootstrap) replaces <input type="button">
    • focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
    • updateMailString() is also called when document is loaded in case the input fields are prepopulated.
  • Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

  • Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
  • E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

Bootstrap: how do I change the width of the container?

Go to the Customize section on Bootstrap site and choose the size you prefer. You'll have to set @gridColumnWidth and @gridGutterWidth variables.

For example: @gridColumnWidth = 65px and @gridGutterWidth = 20px results on a 1000px layout.

Then download it.

YouTube Video Embedded via iframe Ignoring z-index?

Joshc's answer was on the right track, but I found that it totally deletes the ?rel=0 querystring and replaces it with the ?wmode=transparent item - which has the effect of displaying the YouTube Suggested Videos list at the end of the playback, even though you originally didn't want this to happen.

I changed the code so that the src attribute of the embedded video is scanned first, to see if there is a question mark ? in it already (because this denotes the presence of a pre-existing query string, which might be something like ?rel=0 but could in theory be anything that YouTube choose to append in the future). If there's a query string already there, we want to preserve it, not destroy it, because it represents a setting chosen by whoever pasted in this YouTube video, and they presumably chose it for a reason!

So, if ? is found, the wmode=transparent will be appended using the format: &mode=transparent to just tag it on the end of the pre-existing query string.

If no ? is found, then the code will work in exactly the same way as it did originally (in toomanyairmiles's post), appending just ?wmode=transparent as a new query string to the URL.

Now, regardless of what may or may not be on the end of the YouTube URL as a query string already, it gets preserved, and the required wmode parameters get injected or added without damage to what was there before.

Here's the code to drop into your document.ready function:

$('iframe').each(function() {
  var url = $(this).attr("src");
  if (url.indexOf("?") > 0) {
    $(this).attr({
      "src" : url + "&wmode=transparent",
      "wmode" : "opaque"
    });
  }
  else {
    $(this).attr({
      "src" : url + "?wmode=transparent",
      "wmode" : "opaque"
    });
  }
});

PostgreSQL return result set as JSON array?

TL;DR

SELECT json_agg(t) FROM t

for a JSON array of objects, and

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:

[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]

9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.

9.2

9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )::jsonb
FROM t

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

or

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)

9.2

In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Documentation

Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.

Design

If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.

Nulls

Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t

Or

SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

How can I create an observable with a delay

What you want is a timer:

// RxJS v6+
import { timer } from 'rxjs';

//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Playing a video in VideoView in Android

//just copy this code to your main activity.

 if ( ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){

            }else {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }else {
        }

Disabling of EditText in Android

Disable = FOCUS+CLICK+CURSOR

Disabling focus, click, and cursor visibility does the trick for me.

Here is the code in XML

<EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:cursorVisible="false"
    android:clickable="false"
    />

Update Eclipse with Android development tools v. 23

I have done following to resolve an issue.

  1. Go to http://developer.android.com/sdk/installing/installing-adt.html and download the latest ADT ZIP file (at the bottom of page).

  2. Go to Eclipse ? menu Help ? About Eclipse ? Installation details

  3. Delete Android DDM, Android Development Tools, Hierarchy Viewer, Native Development Tools, TraceView, etc., 22.X version.

  4. Menu Help* ? Install New Software ? Add ? Archive ? *Select the downloaded ZIP file in step 1.

  5. Select all the latest version of all 23 which I have deleted in step 3 and accept the license agreement.

Restart Eclipse, and it fixes my issue.

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

How do you convert a C++ string to an int?

Use the C++ streams.

std::string       plop("123");
std::stringstream str(plop);
int x;

str >> x;

/* Lets not forget to error checking */
if (!str)
{
     // The conversion failed.
     // Need to do something here.
     // Maybe throw an exception
}

PS. This basic principle is how the boost library lexical_cast<> works.

My favorite method is the boost lexical_cast<>

#include <boost/lexical_cast.hpp>

int x = boost::lexical_cast<int>("123");

It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).

How can I make a thumbnail <img> show a full size image when clicked?

That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).

How to obtain the query string from the current URL with JavaScript?

Have a look at the MDN article about window.location.

The QueryString is available in window.location.search.

Solution that work in legacy browsers as well

MDN provide an example (no longer available in the above referenced article) of how to the get value of a single key available in the QueryString. Something like this:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

In modern browsers

In modern browsers you have the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

Notice that the browser support is still limited on this interface, so if you need to support legacy browsers, stick with the first example or use a polyfill.

How to trigger the window resize event in JavaScript?

A pure JS that also works on IE (from @Manfred comment)

var evt = window.document.createEvent('UIEvents'); 
evt.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(evt);

Or for angular:

$timeout(function() {
    var evt = $window.document.createEvent('UIEvents'); 
    evt.initUIEvent('resize', true, false, $window, 0); 
    $window.dispatchEvent(evt);
});

sql query to return differences between two tables

Presenting the Cadillac of Diffs as an SP. See within for the basic template that was based on answer by @erikkallen. It supports

  • Duplicate row sensing (most other answers here do not)
  • Sort results by argument
  • Limit to specific columns
  • Ignore columns (e.g. ModifiedUtc)
  • Cross database tables names
  • Temp tables (use as workaround to diff views)

Usage:

exec Common.usp_DiffTableRows '#t1', '#t2';

exec Common.usp_DiffTableRows 
    @pTable0          = 'ydb.ysh.table1',
    @pTable1          = 'xdb.xsh.table2',
    @pOrderByCsvOpt   = null,  -- Order the results
    @pOnlyCsvOpt      = null,  -- Only compare these columns
    @pIgnoreCsvOpt    = null;  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)

Code:

alter proc [Common].[usp_DiffTableRows]    
    @pTable0          varchar(300),
    @pTable1          varchar(300),
    @pOrderByCsvOpt   nvarchar(1000) = null,  -- Order the Results
    @pOnlyCsvOpt      nvarchar(4000) = null,  -- Only compare these columns
    @pIgnoreCsvOpt    nvarchar(4000) = null,  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)
    @pDebug           bit = 0
as
/*---------------------------------------------------------------------------------------------------------------------
    Purpose:  Compare rows between two tables.

      Usage:  exec Common.usp_DiffTableRows '#a', '#b';

    Modified    By          Description
    ----------  ----------  -------------------------------------------------------------------------------------------
    2015.10.06  crokusek    Initial Version
    2019.03.13  crokusek    Added @pOrderByCsvOpt
    2019.06.26  crokusek    Support for @pIgnoreCsvOpt, @pOnlyCsvOpt.    
    2019.09.04  crokusek    Minor debugging improvement
    2020.03.12  crokusek    Detect duplicate rows in either source table
  ---------------------------------------------------------------------------------------------------------------------*/
begin try

    if (substring(@pTable0, 1, 1) = '#')
        set @pTable0 = 'tempdb..' + @pTable0; -- object_id test below needs full names for temp tables

    if (substring(@pTable1, 1, 1) = '#')
        set @pTable1 = 'tempdb..' + @pTable1; -- object_id test below needs full names for temp tables

    if (object_id(@pTable0) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable0);

    if (object_id(@pTable1) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable1);

    create table #ColumnGathering
    (
        Name nvarchar(300) not null,
        Sequence int not null,
        TableArg tinyint not null
    );

    declare
        @usp          varchar(100) = object_name(@@procid),    
        @sql          nvarchar(4000),
        @sqlTemplate  nvarchar(4000) = 
        '  
            use $database$;

            insert into #ColumnGathering
            select Name, column_id as Sequence, $TableArg$ as TableArg
              from sys.columns c
             where object_id = object_id(''$table$'', ''U'')
        ';          

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 0),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable0))),
        '$table$', @pTable0);

    if (@pDebug = 1)
        print 'Sql #CG 0: ' + @sql;

    exec sp_executesql @sql;

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 1),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable1))),
        '$table$', @pTable1);

    if (@pDebug = 1)
        print 'Sql #CG 1: ' + @sql;

    exec sp_executesql @sql;

    if (@pDebug = 1)
        select * from #ColumnGathering;

    select Name, 
           min(Sequence) as Sequence, 
           convert(bit, iif(min(TableArg) = 0, 1, 0)) as InTable0,
           convert(bit, iif(max(TableArg) = 1, 1, 0)) as InTable1
      into #Columns
      from #ColumnGathering
     group by Name
    having (     @pOnlyCsvOpt is not null 
             and Name in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pOnlyCsvOpt, default)))
        or 
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is not null 
             and Name not in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pIgnoreCsvOpt, default)))
        or 
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is null)

    if (exists (select 1 from #Columns where InTable0 = 0 or InTable1 = 0))
    begin
        select 1; -- without this the debugging info doesn't stream sometimes
        select * from #Columns order by Sequence;        
        waitfor delay '00:00:02';  -- give results chance to stream before raising exception
        raiserror('Columns are not equal between tables, consider using args @pIgnoreCsvOpt, @pOnlyCsvOpt.  See Result Sets for details.', 16, 1);    
    end

    if (@pDebug = 1)
        select * from #Columns order by Sequence;

    declare 
        @columns nvarchar(4000) = --iif(@pOnlyCsvOpt is null and @pIgnoreCsvOpt is null,
           -- '*',     
            (
              select substring((select ',' + ac.name
                from #Columns ac
               order by Sequence
                 for xml path('')),2,200000) as csv
            );

    if (@pDebug = 1)
    begin
        print 'Columns: ' + @columns;
        waitfor delay '00:00:02';  -- give results chance to stream before possibly raising exception
    end

    -- Based on https://stackoverflow.com/a/2077929/538763
    --     - Added sensing for duplicate rows
    --     - Added reporting of source table location
    --
    set @sqlTemplate = '
            with 
               a as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $a$), 
               b as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $b$)
            select 0 as SourceTable, ~
              from 
                 (
                   select * from a
                   except
                   select * from b
                 )  anb
              union all
             select 1 as SourceTable, ~
               from 
                 (
                   select * from b
                   except
                   select * from a
                 )  bna
             order by $orderBy$
        ';    

     set @sql = replace(replace(replace(replace(@sqlTemplate, 
            '$a$', @pTable0), 
            '$b$', @pTable1),
            '~', @columns),
            '$orderBy$', coalesce(@pOrderByCsvOpt, @columns + ', SourceTable')
        );

     if (@pDebug = 1)
        print 'Sql: ' + @sql;

     exec sp_executesql @sql;

end try
begin catch
    declare        
        @CatchingUsp  varchar(100) = object_name(@@procid);    

    if (xact_state() = -1)
        rollback;    

    -- Disabled for S.O. post

    --exec Common.usp_Log
        --@pMethod = @CatchingUsp;

    --exec Common.usp_RethrowError        
        --@pCatchingMethod = @CatchingUsp;

    throw;
end catch
go

create function Common.Trim
(
    @pOriginalString nvarchar(max), 
    @pCharsToTrim nvarchar(50) = null -- specify null or 'default' for whitespae 
)  
returns table
with schemabinding
as 
/*--------------------------------------------------------------------------------------------------
    Purpose:   Trim the specified characters from a string.

    Modified    By              Description
    ----------  --------------  --------------------------------------------------------------------
    2012.09.25  S.Rutszy/crok   Modified from https://dba.stackexchange.com/a/133044/9415    
  --------------------------------------------------------------------------------------------------*/ 
return
with cte AS
(
  select patindex(N'%[^' + EffCharsToTrim + N']%', @pOriginalString) AS [FirstChar],
         patindex(N'%[^' + EffCharsToTrim + N']%', reverse(@pOriginalString)) AS [LastChar],
         len(@pOriginalString + N'~') - 1 AS [ActualLength]
   from
   (
         select EffCharsToTrim = coalesce(@pCharsToTrim, nchar(0x09) + nchar(0x20) + nchar(0x0d) + nchar(0x0a))
   ) c
)
select substring(@pOriginalString, [FirstChar],
                 ((cte.[ActualLength] - [LastChar]) - [FirstChar] + 2)
       ) AS [TrimmedString]
       --
       --cte.[ActualLength],
       --[FirstChar],
       --((cte.[ActualLength] - [LastChar]) + 1) AS [LastChar]              
from cte;
go

create function [Common].[ufn_UsvToNVarcharKeyTable] (
    @pCsvList     nvarchar(MAX),
    @pSeparator   nvarchar(1) = ','       -- can pass keyword 'default' when calling using ()'s
    )    
    --
    -- SQL Server 2012 distinguishes nvarchar keys up to maximum of 450 in length (900 bytes)
    -- 
    returns @tbl table (Value nvarchar(450) not null primary key(Value)) as
/*-------------------------------------------------------------------------------------------------
    Purpose:  Converts a comma separated list of strings into a sql NVarchar table.  From

              http://www.programmingado.net/a-398/SQL-Server-parsing-CSV-into-table.aspx     

              This may be called from RunSelectQuery:

                  GRANT SELECT ON Common.ufn_UsvToNVarcharTable TO MachCloudDynamicSql;

    Modified    By              Description
    ----------  --------------  -------------------------------------------------------------------
    2011.07.13  internet        Initial version
    2011.11.22  crokusek        Support nvarchar strings and a custom separator.
    2017.12.06  crokusek        Trim leading and trailing whitespace from each element.
    2019.01.26  crokusek        Remove newlines
  -------------------------------------------------------------------------------------------------*/     
begin
    declare 
        @pos      int,
        @textpos  int,
        @chunklen smallint,
        @str      nvarchar(4000),
        @tmpstr   nvarchar(4000),
        @leftover nvarchar(4000),
        @csvList nvarchar(max) = iif(@pSeparator not in (char(13), char(10), char(13) + char(10)),
            replace(replace(@pCsvList, char(13), ''), char(10), ''),
            @pCsvList); -- remove newlines

    set @textpos = 1
    set @leftover = ''  
    while @textpos <= len(@csvList)
    begin
        set @chunklen = 4000 - len(@leftover)
        set @tmpstr = ltrim(@leftover + substring(@csvList, @textpos, @chunklen))
        set @textpos = @textpos + @chunklen

        set @pos = charindex(@pSeparator, @tmpstr)
        while @pos > 0
        begin
            set @str = substring(@tmpstr, 1, @pos - 1)
            set @str = (select TrimmedString from Common.Trim(@str, default));
            insert @tbl (value) values(@str);
            set @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
            set @pos = charindex(@pSeparator, @tmpstr)
        end

        set @leftover = @tmpstr
    end

    -- Handle @leftover

    set @str = (select TrimmedString from Common.Trim(@leftover, default));

    if @str <> ''
       insert @tbl (value) values(@str);

    return
end
GO

create function Common.ufn_SplitDbIdentifier(@pIdentifier nvarchar(300))
returns @table table 
(    
    InstanceName          nvarchar(300) not null,
    DatabaseName          nvarchar(300) not null,
    SchemaName            nvarchar(300),
    BaseName              nvarchar(300) not null,
    FullTempDbBaseName    nvarchar(300),            -- non-null for tempdb (e.g. #Abc____...)
    InstanceWasSpecified  bit not null,
    DatabaseWasSpecified  bit not null,
    SchemaWasSpecified    bit not null,
    IsCurrentInstance     bit not null,
    IsCurrentDatabase     bit not null,
    IsTempDb              bit not null,
    OrgIdentifier         nvarchar(300) not null
) as
/*-----------------------------------------------------------------------------------------------------------
    Purpose:  Split a Sql Server Identifier into its parts, providing appropriate default values and
              handling temp table (tempdb) references.

    Example:  select * from Common.ufn_SplitDbIdentifier('t')
              union all
              select * from Common.ufn_SplitDbIdentifier('s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('i.d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('#d')
              union all
              select * from Common.ufn_SplitDbIdentifier('tempdb..#d'); 

              -- Empty
              select * from Common.ufn_SplitDbIdentifier('illegal name'); 

    Modified    By              Description
    ----------  --------------  -----------------------------------------------------------------------------
    2013.09.27  crokusek        Initial version.  
  -----------------------------------------------------------------------------------------------------------*/
begin
    declare 
        @name nvarchar(300) = ltrim(rtrim(@pIdentifier));

    -- Return an empty table as a "throw"
    --
    --Removed for SO post
    --if (Common.ufn_IsSpacelessLiteralIdentifier(@name) = 0)
      --  return;

    -- Find dots starting from the right by reversing first.

    declare 
        @revName nvarchar(300) = reverse(@name);

    declare
        @firstDot int = charindex('.', @revName);

    declare
        @secondDot  int = iif(@firstDot = 0,  0, charindex('.', @revName, @firstDot + 1));

    declare
        @thirdDot   int = iif(@secondDot = 0, 0, charindex('.', @revName, @secondDot + 1));

    declare
        @fourthDot  int = iif(@thirdDot = 0, 0, charindex('.', @revName, @thirdDot + 1));

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

    -- Undo the reverse() (first dot is first from the right).
    --
    set @firstDot = iif(@firstDot = 0, 0, len(@name) - @firstDot + 1);
    set @secondDot = iif(@secondDot = 0, 0, len(@name) - @secondDot + 1);
    set @thirdDot = iif(@thirdDot = 0, 0, len(@name) - @thirdDot + 1);
    set @fourthDot = iif(@fourthDot = 0, 0, len(@name) - @fourthDot + 1);

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

    declare
        @baseName   nvarchar(300)  = substring(@name, @firstDot + 1, len(@name) - @firstdot);

    declare
        @schemaName nvarchar(300) = iif(@firstDot - @secondDot - 1 <= 0, 
                                        null,
                                        substring(@name, @secondDot + 1, @firstDot - @secondDot - 1));
    declare
        @dbName     nvarchar(300) = iif(@secondDot - @thirdDot - 1 <= 0, 
                                        null,
                                        substring(@name, @thirdDot + 1, @secondDot - @thirdDot - 1));
    declare
        @instName   nvarchar(300) = iif(@thirdDot - @fourthDot - 1 <= 0, 
                                        null, 
                                        substring(@name, @fourthDot + 1, @thirdDot - @fourthDot - 1));

    with input as (
        select
           coalesce(@instName, '[' + @@servername + ']') as InstanceName,
           coalesce(@dbName,     iif(left(@baseName, 1) = '#', 'tempdb', db_name())) as DatabaseName,
           coalesce(@schemaName, iif(left(@baseName, 1) = '#', 'dbo', schema_name())) as SchemaName,
           @baseName as BaseName,
           iif(left(@baseName, 1) = '#',
               (
                  select [name] from tempdb.sys.objects
                  where object_id = object_id('tempdb..' + @baseName)
               ), 
               null) as FullTempDbBaseName,                
           iif(@instName is null, 0, 1) InstanceWasSpecified,       
           iif(@dbName is null, 0, 1) DatabaseWasSpecified,
           iif(@schemaName is null, 0, 1) SchemaWasSpecified    
     )
     insert into @table           
     select i.InstanceName, i.DatabaseName, i.SchemaName, i.BaseName, i.FullTempDbBaseName,
            i.InstanceWasSpecified, i.DatabaseWasSpecified, i.SchemaWasSpecified,
            iif(i.InstanceName = '[' + @@servername + ']', 1, 0) as IsCurrentInstance,
            iif(i.DatabaseName = db_name(), 1, 0) as IsCurrentDatabase,
            iif(left(@baseName, 1) = '#', 1, 0) as IsTempDb,
            @name as OrgIdentifier
       from input i;

    return;
end
GO

C# List<> Sort by x then y

For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

Convert char to int in C#

This converts to an integer and handles unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

You can read more here.

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

I was getting the same problem onenter image description here Spring Tool Suite 3.2 and changed the version of jstl to 1.2 (from 1.1.2) manually when adding it to the dependency list, and the error got disappeared.

Insert line break in wrapped cell via code

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test"

Note that this automatically sets WrapText to True.

Proof:

Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub

finished with non zero exit value

In my case, I had to install "libz.so.1" library to make it work, on Ubuntu 15.04

sudo apt-get install lib32z1

How to import Angular Material in project?

The MaterialModule was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.

The developers have now 2 options:

  • Create a custom MyMaterialModule which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.
  • Import directly the individual material modules that a module requires into it.

Take the following as example (extracted from material page)

First approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  imports: [MdButtonModule, MdCheckboxModule],
  exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Then you can import this module into any of yours.

Second approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule, MdCheckboxModule],
  ...
})
export class PizzaPartyAppModule { }

Now you can use the respective material components in all the components declared in PizzaPartyAppModule

It is worth mentioning the following:

  • With the latest version of material, you need to import BrowserAnimationsModule into your main module if you want the animations to work
  • With the latest version developers now need to add @angular/cdk to their package.json (material dependency)
  • Import the material modules always after BrowserModule, as stated by the docs:

Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.

jquery find closest previous sibling with class

Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().

var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
  category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();

This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.

How do I get time of a Python program's execution?

You do this simply in Python. There is no need to make it complicated.

import time

start = time.localtime()
end = time.localtime()
"""Total execution time in minutes$ """
print(end.tm_min - start.tm_min)
"""Total execution time in seconds$ """
print(end.tm_sec - start.tm_sec)

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
    IF NOT <@PortfolioID contains Comma>
    BEGIN
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
    END ELSE
    BEGIN
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>
    END
END

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.

Open text file and program shortcut in a Windows batch file

Don't put quotes around the name of the file that you are trying to open; start "myfile.txt" opens a new command prompt with the title myfile.txt, while start myfile.txt opens myfile.txt in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt" works.

How do you check that a number is NaN in JavaScript?

NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this

var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
    alert('nanValue is NaN');

This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.

jQuery: Get height of hidden element in jQuery

By definition, an element only has height if it's visible.

Just curious: why do you need the height of a hidden element?

One alternative is to effectively hide an element by putting it behind (using z-index) an overlay of some kind).

Proper way to exit iPhone application?

In addition to the above, good, answer I just wanted to add, think about cleaning up your memory.

After your application exits, the iPhone OS will automatically clean up anything your application left behind, so freeing all memory manually can just increase the amount of time it takes your application to exit.

test attribute in JSTL <c:if> tag

The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:

<c:if test="true">
    <li>user</li>
</c:if>

and then the c:if tag would be executed.

PHP header redirect 301 - what are the implications?

This is better:

<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

How to save a pandas DataFrame table as a png

The best solution to your problem is probably to first export your dataframe to HTML and then convert it using an HTML-to-image tool. The final appearance could be tweaked via CSS.

Popular options for HTML-to-image rendering include:


Let us assume we have a dataframe named df. We can generate one with the following code:

import string
import numpy as np
import pandas as pd


np.random.seed(0)  # just to get reproducible results from `np.random`
rows, cols = 5, 10
labels = list(string.ascii_uppercase[:cols])
df = pd.DataFrame(np.random.randint(0, 100, size=(5, 10)), columns=labels)
print(df)
#     A   B   C   D   E   F   G   H   I   J
# 0  44  47  64  67  67   9  83  21  36  87
# 1  70  88  88  12  58  65  39  87  46  88
# 2  81  37  25  77  72   9  20  80  69  79
# 3  47  64  82  99  88  49  29  19  19  14
# 4  39  32  65   9  57  32  31  74  23  35

Using WeasyPrint

This approach uses a pip-installable package, which will allow you to do everything using the Python ecosystem. One shortcoming of weasyprint is that it does not seem to provide a way of adapting the image size to its content. Anyway, removing some background from an image is relatively easy in Python / PIL, and it is implemented in the trim() function below (adapted from here). One also would need to make sure that the image will be large enough, and this can be done with CSS's @page size property.

The code follows:

import weasyprint as wsp
import PIL as pil


def trim(source_filepath, target_filepath=None, background=None):
    if not target_filepath:
        target_filepath = source_filepath
    img = pil.Image.open(source_filepath)
    if background is None:
        background = img.getpixel((0, 0))
    border = pil.Image.new(img.mode, img.size, background)
    diff = pil.ImageChops.difference(img, border)
    bbox = diff.getbbox()
    img = img.crop(bbox) if bbox else img
    img.save(target_filepath)


img_filepath = 'table1.png'
css = wsp.CSS(string='''
@page { size: 2048px 2048px; padding: 0px; margin: 0px; }
table, td, tr, th { border: 1px solid black; }
td, th { padding: 4px 8px; }
''')
html = wsp.HTML(string=df.to_html())
html.write_png(img_filepath, stylesheets=[css])
trim(img_filepath)

table_weasyprint


Using wkhtmltopdf/wkhtmltoimage

This approach uses an external open source tool and this needs to be installed prior to the generation of the image. There is also a Python package, pdfkit, that serves as a front-end to it (it does not waive you from installing the core software yourself), but I will not use it.

wkhtmltoimage can be simply called using subprocess (or any other similar means of running an external program in Python). One would also need to output to disk the HTML file.

The code follows:

import subprocess


df.to_html('table2.html')
subprocess.call(
    'wkhtmltoimage -f png --width 0 table2.html table2.png', shell=True)

table_wkhtmltoimage

and its aspect could be further tweaked with CSS similarly to the other approach.


How to insert a text at the beginning of a file?

If the file is only one line, you can use:

sed 's/^/insert this /' oldfile > newfile

If it's more than one line. one of:

sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

sed -i 'whatever command you choose' filename

to do in-place editing.

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

Changing project port number in Visual Studio 2013

Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.

enter image description here

On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file

C:\Users\<username>\Documents\IISExpress\config\applicationhost.config

I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

change image captcha refresh

html:

 <img id="captcha_img" src="http://localhost/captcha.php" /> 

jquery:

$("#captcha_img").click(function()
    {
        var capt_rand=Math.floor((Math.random() * 9999) + 1);
        $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
    });

IOS 7 Navigation Bar text and arrow color

Swift3, ios 10

To globally assign the color, in AppDelegate didFinishLaunchingWithOptions:

let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
UINavigationBar.appearance().titleTextAttributes = textAttributes

Swift 4, iOS 11

let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
UINavigationBar.appearance().titleTextAttributes = textAttributes

How do you import an Eclipse project into Android Studio now?

In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.

/workspace/android-support-v7-appcompat

being a common one.

In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.

To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.

<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>

That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:

dependencies {
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Check if two lists are equal

Use SequenceEqual to check for sequence equality because Equals method checks for reference equality.

var a = ints1.SequenceEqual(ints2);

Or if you don't care about elements order use Enumerable.All method:

var a = ints1.All(ints2.Contains);

The second version also requires another check for Count because it would return true even if ints2 contains more elements than ints1. So the more correct version would be something like this:

var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;

In order to check inequality just reverse the result of All method:

var a = !ints1.All(ints2.Contains)

Hidden features of Windows batch files

Setting environment variables from a file with SET /P

SET /P SVNVERSION=<ver.tmp

How to do a deep comparison between 2 objects with lodash?

this was based on @JLavoie, using lodash

let differences = function (newObj, oldObj) {
      return _.reduce(newObj, function (result, value, key) {
        if (!_.isEqual(value, oldObj[key])) {
          if (_.isArray(value)) {
            result[key] = []
            _.forEach(value, function (innerObjFrom1, index) {
              if (_.isNil(oldObj[key][index])) {
                result[key].push(innerObjFrom1)
              } else {
                let changes = differences(innerObjFrom1, oldObj[key][index])
                if (!_.isEmpty(changes)) {
                  result[key].push(changes)
                }
              }
            })
          } else if (_.isObject(value)) {
            result[key] = differences(value, oldObj[key])
          } else {
            result[key] = value
          }
        }
        return result
      }, {})
    }

https://jsfiddle.net/EmilianoBarboza/0g0sn3b9/8/

Toggle button using two image on different state

AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:

<ToggleButton 
    android:id="@+id/toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/check"   //check.xml
    android:background="@null"/>

check.xml:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
          android:state_checked="false"/>
    </selector>

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

Remove Primary Key in MySQL

I believe Quassnoi has answered your direct question. Just a side note: Maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field. This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields. Thus, you cannot "drop the primary key on a column". You can drop the primary key, or not drop the primary key. If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.

Disable a textbox using CSS

You can't disable anything with CSS, that's a functional-issue. CSS is meant for design-issues. You could give the impression of a textbox being disabled, by setting washed-out colors on it.

To actually disable the element, you should use the disabled boolean attribute:

<input type="text" name="lname" disabled />

Demo: http://jsfiddle.net/p6rja/

Or, if you like, you can set this via JavaScript:

document.forms['formName']['inputName'].disabled = true;????

Demo: http://jsfiddle.net/655Su/

Keep in mind that disabled inputs won't pass their values through when you post data back to the server. If you want to hold the data, but disallow to directly edit it, you may be interested in setting it to readonly instead.

// Similar to <input value="Read-only" readonly>
document.forms['formName']['inputName'].readOnly = true;

Demo: http://jsfiddle.net/655Su/1/

This doesn't change the UI of the element, so you would need to do that yourself:

input[readonly] { 
    background: #CCC; 
    color: #333; 
    border: 1px solid #666 
}

You could also target any disabled element:

input[disabled] { /* styles */ }

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Serializing enums with Jackson

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

Gaussian fit for Python

Here is corrected code:

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

result:
enter image description here

Capture Image from Camera and Display in Activity

Here you can open camera or gallery and set the selected image into imageview

private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView;  // imageview
private int GALLERY = 1, CAMERA = 2;

Add permissions in manifest

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

In onCreate()

    requestMultiplePermissions(); // check permission 

    circleImageView = findViewById(R.id.profile_image);
    circleImageView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showPictureDialog();
        }
    });

Show options dialog box (to select image from camera or gallery)

private void showPictureDialog() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                        case 1:
                            takePhotoFromCamera();
                            break;
                    }
                }
            });
    pictureDialog.show();
}

Get photo from Gallery

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY);
}

Get photo from Camera

private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);
}

Once the image is get selected or captured then ,

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                String path = saveImage(bitmap);
                Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
                circleImageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
            }
        }

    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        circleImageView.setImageBitmap(thumbnail);
        saveImage(thumbnail);
        Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
    }
}

Now its time to store the picture

public String saveImage(Bitmap myBitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
    if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.
        wallpaperDirectory.mkdirs();
    }

    try {
        File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        MediaScannerConnection.scanFile(this,
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);
        fo.close();
        Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

        return f.getAbsolutePath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return "";
}

Request permission

    private void requestMultiplePermissions() {
    Dexter.withActivity(this)
            .withPermissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                        Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                    }

                    if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
                        // show alert dialog navigating to Settings
                        //openSettingsDialog();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).
            withErrorListener(new PermissionRequestErrorListener() {
                @Override
                public void onError(DexterError error) {
                    Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                }
            })
            .onSameThread()
            .check();
}

Keep CMD open after BAT file executes

Depending on how you are running the command, you can put /k after cmd to keep the window open.

cmd /k my_script.bat

Simply adding cmd /k to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.

Defining static const integer members in class definition

Bjarne Stroustrup's example in his C++ FAQ suggests you are correct, and only need a definition if you take the address.

class AE {
    // ...
public:
    static const int c6 = 7;
    static const int c7 = 31;
};

const int AE::c7;   // definition

int f()
{
    const int* p1 = &AE::c6;    // error: c6 not an lvalue
    const int* p2 = &AE::c7;    // ok
    // ...
}

He says "You can take the address of a static member if (and only if) it has an out-of-class definition". Which suggests it would work otherwise. Maybe your min function invokes addresses somehow behind the scenes.

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

How do I update the password for Git?

In my Windows machine, I tried the solution of @nzrytmn i.e., Control Panel>Search Credentials>Select "ManageCredentials">modified new credentials under git option category corresponding to my username. And then,

Deleted current password:

git config --global --unset user.password

Added new password:

git config --global --add user.password "new_password"

And It worked for me.

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

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

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/>

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);

5 - Get the result in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

How to set default value for HTML select?

You could use...

<option <?= ($temp == $value) ? "SELECTED" : "" ?> >$value</opton>

Edit: I thought I was looking at PHP questions... Sorry.

How can I compare two dates in PHP?

$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db 
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);

//echo $timeDiff;
if($diff->days >= 30){
    echo "Expired.";
}else{
    echo "Not expired.";
}

How to Select a substring in Oracle SQL up to a specific character?

Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):

SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1), 
"STRING_COLUMN") 
AS OUTPUT FROM DUAL

Extract subset of key-value pairs from Python dictionary object?

Okay, this is something that has bothered me a few times, so thank you Jayesh for asking it.

The answers above seem like as good a solution as any, but if you are using this all over your code, it makes sense to wrap the functionality IMHO. Also, there are two possible use cases here: one where you care about whether all keywords are in the original dictionary. and one where you don't. It would be nice to treat both equally.

So, for my two-penneth worth, I suggest writing a sub-class of dictionary, e.g.

class my_dict(dict):
    def subdict(self, keywords, fragile=False):
        d = {}
        for k in keywords:
            try:
                d[k] = self[k]
            except KeyError:
                if fragile:
                    raise
        return d

Now you can pull out a sub-dictionary with

orig_dict.subdict(keywords)

Usage examples:

#
## our keywords are letters of the alphabet
keywords = 'abcdefghijklmnopqrstuvwxyz'
#
## our dictionary maps letters to their index
d = my_dict([(k,i) for i,k in enumerate(keywords)])
print('Original dictionary:\n%r\n\n' % (d,))
#
## constructing a sub-dictionary with good keywords
oddkeywords = keywords[::2]
subd = d.subdict(oddkeywords)
print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,))
#
## constructing a sub-dictionary with mixture of good and bad keywords
somebadkeywords = keywords[1::2] + 'A'
try:
    subd2 = d.subdict(somebadkeywords)
    print("We shouldn't see this message")
except KeyError:
    print("subd2 construction fails:")
    print("\toriginal dictionary doesn't contain some keys\n\n")
#
## Trying again with fragile set to false
try:
    subd3 = d.subdict(somebadkeywords, fragile=False)
    print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,))
except KeyError:
    print("We shouldn't see this message")

If you run all the above code, you should see (something like) the following output (sorry for the formatting):

Original dictionary:
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}

Dictionary from odd numbered keys:
{'a': 0, 'c': 2, 'e': 4, 'g': 6, 'i': 8, 'k': 10, 'm': 12, 'o': 14, 'q': 16, 's': 18, 'u': 20, 'w': 22, 'y': 24}

subd2 construction fails:
original dictionary doesn't contain some keys

Dictionary constructed using some bad keys:
{'b': 1, 'd': 3, 'f': 5, 'h': 7, 'j': 9, 'l': 11, 'n': 13, 'p': 15, 'r': 17, 't': 19, 'v': 21, 'x': 23, 'z': 25}

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

You can change this by using the VM arguments as well in the launch configuration.

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')

What is the best way to paginate results in SQL Server

Incredibly, no other answer has mentioned the fastest way to do pagination in all SQL Server versions. Offsets can be terribly slow for large page numbers as is benchmarked here. There is an entirely different, much faster way to perform pagination in SQL. This is often called the "seek method" or "keyset pagination" as described in this blog post here.

SELECT TOP 10 first_name, last_name, score, COUNT(*) OVER()
FROM players
WHERE (score < @previousScore)
   OR (score = @previousScore AND player_id < @previousPlayerId)
ORDER BY score DESC, player_id DESC

The "seek predicate"

The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead.

With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).

This is the best way to implement pagination when lazy loading more data in web applications, for instance.

Note, the "seek method" is also called keyset pagination.

Total records before pagination

The COUNT(*) OVER() window function will help you count the number of total records "before pagination". If you're using SQL Server 2000, you will have to resort to two queries for the COUNT(*).

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

How to do paging in AngularJS?

Below solution quite simple.

<pagination  
        total-items="totalItems" 
        items-per-page= "itemsPerPage"
        ng-model="currentPage" 
        class="pagination-sm">
</pagination>

<tr ng-repeat="country in countries.slice((currentPage -1) * itemsPerPage, currentPage * itemsPerPage) "> 

Here is sample jsfiddle

Fastest way to implode an associative array with keys

A one-liner for creating string of HTML attributes (with quotes) from a simple array:

$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

Example:

$attrArray = array("id"    => "email", 
                   "name"  => "email",
                   "type"  => "email",
                   "class" => "active large");

echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

// Output:
// id="email" name="email" type="email" class="active large"

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

How to hide keyboard in swift on pressing return key?

Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.

self.textField.delegate = self

I do not want to inherit the child opacity from the parent in CSS

If you have to use an image as the transparent background, you might be able to work around it using a pseudo element:

html

<div class="wrap"> 
   <p>I have 100% opacity</p>  
</div>

css

.wrap, .wrap > * {
  position: relative;
}
.wrap:before {
  content: " ";
  opacity: 0.2;
  background: url("http://placehold.it/100x100/FF0000") repeat;     
  position: absolute;
  width: 100%;
  height: 100%;
}

Hadoop/Hive : Loading data from .csv on a local machine

You can load local CSV file to Hive only if:

  1. You are doing it from one of the Hive cluster nodes.
  2. You installed Hive client on non-cluster node and using hive or beeline for upload.

How do I get an object's unqualified (short) class name?

I found myself in a unique situation where instanceof could not be used (specifically namespaced traits) and I needed the short name in the most efficient way possible so I've done a little benchmark of my own. It includes all the different methods & variations from the answers in this question.

$bench = new \xori\Benchmark(1000, 1000);     # https://github.com/Xorifelse/php-benchmark-closure
$shell = new \my\fancy\namespace\classname(); # Just an empty class named `classname` defined in the `\my\fancy\namespace\` namespace

$bench->register('strrpos', (function(){
    return substr(static::class, strrpos(static::class, '\\') + 1);
})->bindTo($shell));

$bench->register('safe strrpos', (function(){
    return substr(static::class, ($p = strrpos(static::class, '\\')) !== false ? $p + 1 : 0);
})->bindTo($shell));

$bench->register('strrchr', (function(){
    return substr(strrchr(static::class, '\\'), 1);
})->bindTo($shell));

$bench->register('reflection', (function(){
    return (new \ReflectionClass($this))->getShortName();
})->bindTo($shell));

$bench->register('reflection 2', (function($obj){
    return $obj->getShortName();
})->bindTo($shell), new \ReflectionClass($shell));

$bench->register('basename', (function(){
    return basename(str_replace('\\', '/', static::class));
})->bindTo($shell));

$bench->register('explode', (function(){
    $e = explode("\\", static::class);
    return end($e);
})->bindTo($shell));

$bench->register('slice', (function(){
    return join('',array_slice(explode('\\', static::class), -1));
})->bindTo($shell));    

print_r($bench->start());

A list of the of the entire result is here but here are the highlights:

  • If you're going to use reflection anyways, using $obj->getShortName() is the fastest method however; using reflection only to get the short name it is almost the slowest method.
  • 'strrpos' can return a wrong value if the object is not in a namespace so while 'safe strrpos' is a tiny bit slower I would say this is the winner.
  • To make 'basename' compatible between Linux and Windows you need to use str_replace() which makes this method the slowest of them all.

A simplified table of results, speed is measured compared to the slowest method:

+-----------------+--------+
| registered name | speed  |
+-----------------+--------+
| reflection 2    | 70.75% |
| strrpos         | 60.38% |
| safe strrpos    | 57.69% |
| strrchr         | 54.88% |
| explode         | 46.60% |
| slice           | 37.02% |
| reflection      | 16.75% |
| basename        | 0.00%  |
+-----------------+--------+

Decreasing height of bootstrap 3.0 navbar

I think we can write this fewer styles, without changing the existing color. The following worked for me (in Bootstrap 3.2.0)

.navbar-nav > li > a { padding-top: 5px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 5px; padding-bottom: 10px; padding-left: 10px; }

The last one ('navbar-brand') is actually needed only if you have text as your 'brand' name.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Passing additional variables from command line to make

If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards

example :

make unittest=*

I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Multi-statement Table Valued Function vs Inline Table Valued Function

I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.

Stopping Docker containers by image name - Ubuntu

use: docker container stop $(docker container ls -q --filter ancestor=mongo)

    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
    d394144acf3a        mongo               "docker-entrypoint.s…"   15 seconds ago      Up 14 seconds       0.0.0.0:27017->27017/tcp   magical_nobel
    (base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
    d394144acf3a
    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    (base) :~ user$

Best GUI designer for eclipse?

'Jigloo' is a very cool GUI designer. It is not free for commercial use however. It auto-generates code and allows for custom editing of the code it creates.

http://www.cloudgarden.com/jigloo/

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

.rar, .zip files MIME Type

I see many answer reporting for zip and rar the Media Types application/zip and application/x-rar-compressed, respectively.

While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed is a deprecated alias name and instead application/vnd.rar is the official one. So, right Media Types from IANA in 2020 are:

  1. zip: application/zip
  2. rar: application/vnd.rar

Does JavaScript guarantee object property order?

YES (for non-integer keys).

Most Browsers iterate object properties as:

  1. Integer keys in ascending order (and strings like "1" that parse as ints)
  2. String keys, in insertion order (ES2015 guarantees this and all browsers comply)
  3. Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

Some older browsers combine categories #1 and #2, iterating all keys in insertion order. If your keys might parse as integers, it's best not to rely on any specific iteration order.

Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.

Old Language Spec (before ES2015): Iteration order was technically undefined, but all major browsers complied with the ES2015 behavior.

Note that the ES2015 behavior was a good example of the language spec being driven by existing behavior, and not the other way round. To get a deeper sense of that backwards-compatibility mindset, see http://code.google.com/p/v8/issues/detail?id=164, a Chrome bug that covers in detail the design decisions behind Chrome's iteration order behavior. Per one of the (rather opinionated) comments on that bug report:

Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference:

  1. Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4).

  2. Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG:

    hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \
          -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg
    
  3. Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation):

    device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \
             egrep '^/dev/' | sed 1q | awk '{print $1}')
    
  4. Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable.

  5. Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed):

    echo '
       tell application "Finder"
         tell disk "'${title}'"
               open
               set current view of container window to icon view
               set toolbar visible of container window to false
               set statusbar visible of container window to false
               set the bounds of container window to {400, 100, 885, 430}
               set theViewOptions to the icon view options of container window
               set arrangement of theViewOptions to not arranged
               set icon size of theViewOptions to 72
               set background picture of theViewOptions to file ".background:'${backgroundPictureName}'"
               make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
               set position of item "'${applicationName}'" of container window to {100, 100}
               set position of item "Applications" of container window to {375, 100}
               update without registering applications
               delay 5
               close
         end tell
       end tell
    ' | osascript
    
  6. Finialize the DMG by setting permissions properly, compressing and releasing it:

    chmod -Rf go-w /Volumes/"${title}"
    sync
    sync
    hdiutil detach ${device}
    hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}"
    rm -f /pack.temp.dmg 
    

On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.:

..
set position of item "'${applicationName}'" of container window to {100, 100}
set position of item "Applications" of container window to {375, 100}
close
open

File tree view in Notepad++

You can add it from the notepad++ toolbar Plugins > Plugin Manager > Show Plugin Manager. Then select the Explorer plugin and click the Install button.

What is the correct way to represent null XML elements?

Simply omitting the attribute or element works well in less formal data.

If you need more sophisticated information, the GML schemas add the attribute nilReason, eg: in GeoSciML:

  • xsi:nil with a value of "true" is used to indicate that no value is available
  • nilReason may be used to record additional information for missing values; this may be one of the standard GML reasons (missing, inapplicable, withheld, unknown), or text prepended by other:, or may be a URI link to a more detailed explanation.

When you are exchanging data, the role for which XML is commonly used, data sent to one recipient or for a given purpose may have content obscured that would be available to someone else who paid or had different authentication. Knowing the reason why content was missing can be very important.

Scientists also are concerned with why information is missing. For example, if it was dropped for quality reasons, they may want to see the original bad data.

How to delete or add column in SQLITE?

I rewrote the @Udinic answer so that the code generates table creation query automatically. It also doesn't need ConnectionSource. It also has to do this inside a transaction.

public static String getOneTableDbSchema(SQLiteDatabase db, String tableName) {
    Cursor c = db.rawQuery(
            "SELECT * FROM `sqlite_master` WHERE `type` = 'table' AND `name` = '" + tableName + "'", null);
    String result = null;
    if (c.moveToFirst()) {
        result = c.getString(c.getColumnIndex("sql"));
    }
    c.close();
    return result;
}

public List<String> getTableColumns(SQLiteDatabase db, String tableName) {
    ArrayList<String> columns = new ArrayList<>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = db.rawQuery(cmd, null);

    while (cur.moveToNext()) {
        columns.add(cur.getString(cur.getColumnIndex("name")));
    }
    cur.close();

    return columns;
}

private void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) {
    db.beginTransaction();
    try {
        List<String> columnNamesWithoutRemovedOnes = getTableColumns(db, tableName);
        // Remove the columns we don't want anymore from the table's list of columns
        columnNamesWithoutRemovedOnes.removeAll(Arrays.asList(columnsToRemove));

        String newColumnNamesSeparated = TextUtils.join(" , ", columnNamesWithoutRemovedOnes);
        String sql = getOneTableDbSchema(db, tableName);
        // Extract the SQL query that contains only columns
        String oldColumnsSql = sql.substring(sql.indexOf("(")+1, sql.lastIndexOf(")"));

        db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
        db.execSQL("CREATE TABLE `" + tableName + "` (" + getSqlWithoutRemovedColumns(oldColumnsSql, columnsToRemove)+ ");");
        db.execSQL("INSERT INTO " + tableName + "(" + newColumnNamesSeparated + ") SELECT " + newColumnNamesSeparated + " FROM " + tableName + "_old;");
        db.execSQL("DROP TABLE " + tableName + "_old;");
        db.setTransactionSuccessful();
    } catch {
        //Error in between database transaction 
    } finally {
        db.endTransaction();
    }


}

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

    try:
        res = math.exp(420000)
    except OverflowError:
        res = float('inf')
    

Notes

Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

How should I tackle --secure-file-priv in MySQL?

@vhu I did the SHOW VARIABLES LIKE "secure_file_priv"; and it returned C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ so when I plugged that in, it still didn't work.

When I went to the my.ini file directly I discovered that the path is formatted a bit differently:

C:/ProgramData/MySQL/MySQL Server 8.0/Uploads

Then when I ran it with that, it worked. The only difference was the direction of the slashes.

Android runOnUiThread explanation

Instead of creating a thread, and using runOnUIThread, this is a perfect job for ASyncTask:

  • In onPreExecute, create & show the dialog.

  • in doInBackground prepare the data, but don't touch the UI -- store each prepared datum in a field, then call publishProgress.

  • In onProgressUpdate read the datum field & make the appropriate change/addition to the UI.

  • In onPostExecute dismiss the dialog.


If you have other reasons to want a thread, or are adding UI-touching logic to an existing thread, then do a similar technique to what I describe, to run on UI thread only for brief periods, using runOnUIThread for each UI step. In this case, you will store each datum in a local final variable (or in a field of your class), and then use it within a runOnUIThread block.

What is the easiest way to parse an INI file in Java?

Or with standard Java API you can use java.util.Properties:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
    props.load(in);
}

Is it possible to change a UIButtons background color?

Per @EthanB suggestion and @karim making a back filled rectangle, I just created a category for the UIButton to achieve this.

Just drop in the Category code: https://github.com/zmonteca/UIButton-PLColor

Usage:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];

Optional forStates to use:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

How to access a mobile's camera from a web app?

Just to update this, the standard now is:

<input type="file" name="image" accept="image/*" capture="environment">

to access the environment-facing (rear) camera, and

<input type="file" name="image" accept="image/*" capture="user">

for user-facing (front) camera. To access video, substitute "video" for "image" in name.

Tested on iPhone 5c, running iOS 10.3.3, firmware 760, works fine.

https://www.w3.org/TR/html-media-capture/

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

How to use an array list in Java?

object get(int index) is used to return the object stored at the specified index within the invoking collection.

Code Snippet :

import java.util.*;


class main
{
    public static void main(String [] args)
    {
        ArrayList<String> arr = new ArrayList<String>();
        arr.add("Hello!");
        arr.add("Ishe");
        arr.add("Watson?");

        System.out.printf("%s\n",arr.get(2)); 

        for (String s : arr) 
        {
            System.out.printf("%s\n",s);
        } 
    }
}

BACKUP LOG cannot be performed because there is no current database backup

Simply you can use this method:

  1. If you have a database with same name: WIN+R -> services.msc -> SQL SERVER(MSSQLSERVER) -> Stop
  2. Go to your MySQL Data folder path and delete previews database files
  3. Start sql service
  4. Right click on database and select Restore database
  5. in Files tab change Data file folder and Log file folder
  6. Click on OK to restore your database

my problem was solved with this method BY...

"starting Tomcat server 7 at localhost has encountered a prob"

Method 1:

  • type localhost:8080 in your browser to know which process is taking 8080 port
  • uninstall that program

Method 2:

re-install the apache tomcat BUT during installation change the port number. Watch carefully the installation process

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Use:

android:imeActionLabel="Done"
android:singleLine="true" 

Changing specific text's color using NSMutableAttributedString in Swift

Chris' answer was a great help to me, so I used his approach and turned into a func that I can reuse. This let's me assign a color to a substring while giving the rest of the string another color.

static func createAttributedString(fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) -> NSMutableAttributedString
{
    let range = (fullString as NSString).rangeOfString(subString)
    let attributedString = NSMutableAttributedString(string:fullString)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: fullStringColor, range: NSRange(location: 0, length: fullString.characters.count))
    attributedString.addAttribute(NSForegroundColorAttributeName, value: subStringColor, range: range)
    return attributedString
}

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

what is the multicast doing on 224.0.0.251?

I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone

WAMP shows error 'MSVCR100.dll' is missing when install

Step 1. Uninstall WAMP

Step 2. Install the latest Microsoft Visual C++ 2015 Redistributable Update 3

Step 3. Restart System

Step 4. Re-install WAMP

Make sure Skype is not signed in. You don't want to know details if you are a newbie :)

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

Environment variables in Eclipse

You can also start eclipse within a shell.

You export the enronment, before calling eclipse.

Example :

#!/bin/bash
export MY_VAR="ADCA"
export PATH="/home/lala/bin;$PATH"
$ECLIPSE_HOME/eclipse -data $YOUR_WORK_SPACE_PATH

Then you can have multiple instances on eclipse with their own custome environment including workspace.

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

If you want to run a single independent queued operation and you’re not concerned with other concurrent operations, you can use the global concurrent queue:

dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

This will return a concurrent queue with the given priority as outlined in the documentation:

DISPATCH_QUEUE_PRIORITY_HIGH Items dispatched to the queue will run at high priority, i.e. the queue will be scheduled for execution before any default priority or low priority queue.

DISPATCH_QUEUE_PRIORITY_DEFAULT Items dispatched to the queue will run at the default priority, i.e. the queue will be scheduled for execution after all high priority queues have been scheduled, but before any low priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_LOW Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after all default priority and high priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_BACKGROUND Items dispatched to the queue will run at background priority, i.e. the queue will be scheduled for execution after all higher priority queues have been scheduled and the system will run items on this queue on a thread with background status as per setpriority(2) (i.e. disk I/O is throttled and the thread’s scheduling priority is set to lowest value).

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Loop through a comma-separated shell variable

If you set a different field separator, you can directly use a for loop:

IFS=","
for v in $variable
do
   # things with "$v" ...
done

You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:

IFS=, read -ra values <<< "$variable"
for v in "${values[@]}"
do
   # things with "$v"
done

Test

$ variable="abc,def,ghij"
$ IFS=","
$ for v in $variable
> do
> echo "var is $v"
> done
var is abc
var is def
var is ghij

You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.

Examples on the second approach:

$ IFS=, read -ra vals <<< "abc,def,ghij"
$ printf "%s\n" "${vals[@]}"
abc
def
ghij
$ for v in "${vals[@]}"; do echo "$v --"; done
abc --
def --
ghij --

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I tried all previously mentioned answers, but in my case I had to manually specify the include path of the iostream file. As I use MinGW the path was:

C:\MinGW\lib\gcc\mingw32\4.8.1\include\c++

You can add the path in Eclipse under: Project > C/C++ General > Paths and Symbols > Includes > Add. I hope that helps

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

How to echo or print an array in PHP?

You can use print_r, var_dump and var_export funcations of php:

print_r: Convert into human readble form

<?php
echo "<pre>";
 print_r($results); 
echo "</pre>";
?>

var_dump(): will show you the type of the thing as well as what's in it.

var_dump($results);

foreach loop: using for each loop you can iterate each and every value of an array.

foreach($results['data'] as $result) {
    echo $result['type'].'<br>';
}

Command line for looking at specific port

As noted elsewhere: use netstat, with appropriate switches, and then filter the results with find[str]

Most basic:

netstat -an | find ":N"

or

netstat -a -n | find ":N"

To find a foreign port you could use:

netstat -an | findstr ":N[^:]*$"

To find a local port you might use:

netstat -an | findstr ":N.*:[^:]*$"

Where N is the port number you are interested in.

-n ensures all ports will be numerical, i.e. not returned as translated to service names.

-a will ensure you search all connections (TCP, UDP, listening...)

In the find string you must include the colon, as the port qualifier, otherwise the number may match either local or foreign addresses.

You can further narrow narrow the search using other netstat switches as necessary...

Further reading (^0^)

netstat /?

find /?

findstr /?

Display the current time and date in an Android application

String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();

Android SharedPreferences in Fragment

use requiredactivity in fragment kotlin

 val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)

Reactjs setState() with a dynamic key name?

when the given element is a object:

handleNewObj = e => {
        const data = e[Object.keys(e)[0]];
        this.setState({
            anykeyofyourstate: {
                ...this.state.anykeyofyourstate,
                [Object.keys(e)[0]]: data
            }
        });
    };

hope it helps someone

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

How to ignore a property in class if null, using json.net

As can be seen in this link on their site (http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx) I support using [Default()] to specify default values

Taken from the link

   public class Invoice
{
  public string Company { get; set; }
  public decimal Amount { get; set; }

  // false is default value of bool
  public bool Paid { get; set; }
  // null is default value of nullable
  public DateTime? PaidDate { get; set; }

  // customize default values
  [DefaultValue(30)]
  public int FollowUpDays { get; set; }
  [DefaultValue("")]
  public string FollowUpEmailAddress { get; set; }
}


Invoice invoice = new Invoice
{
  Company = "Acme Ltd.",
  Amount = 50.0m,
  Paid = false,
  FollowUpDays = 30,
  FollowUpEmailAddress = string.Empty,
  PaidDate = null
};

string included = JsonConvert.SerializeObject(invoice,
  Formatting.Indented,
  new JsonSerializerSettings { });

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0,
//   "Paid": false,
//   "PaidDate": null,
//   "FollowUpDays": 30,
//   "FollowUpEmailAddress": ""
// }

string ignored = JsonConvert.SerializeObject(invoice,
  Formatting.Indented,
  new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0
// }

How to delete items from a dictionary while iterating over it?

EDIT:

This answer will not work for Python3 and will give a RuntimeError.

RuntimeError: dictionary changed size during iteration.

This happens because mydict.keys() returns an iterator not a list. As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.


A simple test in the console shows you cannot modify a dictionary while iterating over it:

>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k, v in mydict.iteritems():
...    if k == 'two':
...        del mydict[k]
...
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:

>>> for k in mydict.keys():
...    if k == 'two':
...        del mydict[k]
...
>>> mydict
{'four': 4, 'three': 3, 'one': 1}

If you need to delete based on the items value, use the items() method instead:

>>> for k, v in mydict.items():
...     if v == 3:
...         del mydict[k]
...
>>> mydict
{'four': 4, 'one': 1}

How to specify the private SSH-key to use when executing shell command on Git?

If you're like me, you can:

  • Keep your ssh keys organized

  • Keep your git clone commands simple

  • Handle any number of keys for any number of repositories.

  • Reduce your ssh key maintenance.

I keep my keys in my ~/.ssh/keys directory.

I prefer convention over configuration.

I think code is law; the simpler it is, the better.

STEP 1 - Create Alias

Add this alias to your shell: alias git-clone='GIT_SSH=ssh_wrapper git clone'

STEP 2 - Create Script

Add this ssh_wrapper script to your PATH:

#!/bin/bash
# Filename: ssh_wrapper

if [ -z ${SSH_KEY} ]; then
    SSH_KEY='github.com/l3x'  # <= Default key
fi
SSH_KEY="~/.ssh/keys/${SSH_KEY}/id_rsa"
ssh -i "${SSH_KEY}" "$@"

EXAMPLES

Use github.com/l3x key:

KEY=github.com/l3x git-clone https://github.com/l3x/learn-fp-go

The following example also uses the github.com/l3x key (by default):

git-clone https://github.com/l3x/learn-fp-go

Use bitbucket.org/lsheehan key:

KEY=bitbucket.org/lsheehan git-clone [email protected]:dave_andersen/exchange.git

NOTES

Change the default SSH_KEY in the ssh_wrapper script to what you use most of the time. That way, you don't need to use the KEY variable most of the time.

You may think, "Hey! That's a lot going on with an alias, a script and some directory of keys," but for me it's convention. Nearly all my workstations (and servers for that matter) are configured similarly.

My goal here is to simplify the commands that I execute regularly.

My conventions, e.g., Bash scripts, aliases, etc., create a consistent environment and helps me keep things simple.

KISS and names matter.

For more design tips check out Chapter 4 SOLID Design in Go from my book: https://www.amazon.com/Learning-Functional-Programming-Lex-Sheehan-ebook/dp/B0725B8MYW

Hope that helps. - Lex

How to program a fractal?

The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.

How to convert a Map to List in Java?

The issue here is that Map has two values (a key and value), while a List only has one value (an element).

Therefore, the best that can be done is to either get a List of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).

Say we have a Map:

Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");

The keys as a List can be obtained by creating a new ArrayList from a Set returned by the Map.keySet method:

List<String> list = new ArrayList<String>(m.keySet());

While the values as a List can be obtained creating a new ArrayList from a Collection returned by the Map.values method:

List<String> list = new ArrayList<String>(m.values());

The result of getting the List of keys:

Apple
Another
Hello

The result of getting the List of values:

3.14
Element
World

C# DateTime to "YYYYMMDDHHMMSS" format

You've practically written the format yourself.

yourdate.ToString("yyyyMMddHHmmss")

  • MM = two digit month
  • mm = two digit minutes
  • HH = two digit hour, 24 hour clock
  • hh = two digit hour, 12 hour clock

Everything else should be self-explanatory.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How do I add a newline to command output in PowerShell?

Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file:

$OFS = "`r`n`r`n"
"$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall | 
    ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" | 
 out-file addrem.txt

Beware to use the ` and not the '. On my keyboard (US-English Qwerty layout) it's located left of the 1.
(Moved here from the comments - Thanks Koen Zomers)

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

batch script - read line by line

The "call" solution has some problems.

It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
These lines will produce more or less strange problems

one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty

the end

Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "myVar=%%a"
    call :processLine myVar
)
goto :eof

:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof

What is InputStream & Output Stream? Why and when do we use them?

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

How do I convert ticks to minutes?

there are 600 million ticks per minute. ticksperminute

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

How do I convert Long to byte[] and back in java

If you are looking for a fast unrolled version, this should do the trick, assuming a byte array called "b" with a length of 8:

byte[] -> long

long l = ((long) b[7] << 56)
       | ((long) b[6] & 0xff) << 48
       | ((long) b[5] & 0xff) << 40
       | ((long) b[4] & 0xff) << 32
       | ((long) b[3] & 0xff) << 24
       | ((long) b[2] & 0xff) << 16
       | ((long) b[1] & 0xff) << 8
       | ((long) b[0] & 0xff);

long -> byte[] as an exact counterpart to the above

byte[] b = new byte[] {
       (byte) lng,
       (byte) (lng >> 8),
       (byte) (lng >> 16),
       (byte) (lng >> 24),
       (byte) (lng >> 32),
       (byte) (lng >> 40),
       (byte) (lng >> 48),
       (byte) (lng >> 56)};

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

how to find my angular version in my project?

ng --version command will show only the installed angular version in your computer instead of the actual project version.

if you really want to know the project version, Go to your project, use the below command

npm list -local

enter image description here

Parsing query strings on Android

Answering here because this is a popular thread. This is a clean solution in Kotlin that uses the recommended UrlQuerySanitizer api. See the official documentation. I have added a string builder to concatenate and display the params.

    var myURL: String? = null
    // if the url is sent from a different activity where you set it to a value
    if (intent.hasExtra("my_value")) {
        myURL = intent.extras.getString("my_value")
    } else {
        myURL = intent.dataString
    }

    val sanitizer = UrlQuerySanitizer(myURL)
    // We don't want to manually define every expected query *key*, so we set this to true
    sanitizer.allowUnregisteredParamaters = true
    val parameterNamesToValues: List<UrlQuerySanitizer.ParameterValuePair> = sanitizer.parameterList
    val parameterIterator: Iterator<UrlQuerySanitizer.ParameterValuePair> = parameterNamesToValues.iterator()

    // Helper simply so we can display all values on screen
    val stringBuilder = StringBuilder()

    while (parameterIterator.hasNext()) {
        val parameterValuePair: UrlQuerySanitizer.ParameterValuePair = parameterIterator.next()
        val parameterName: String = parameterValuePair.mParameter
        val parameterValue: String = parameterValuePair.mValue

        // Append string to display all key value pairs
        stringBuilder.append("Key: $parameterName\nValue: $parameterValue\n\n")
    }

    // Set a textView's text to display the string
    val paramListString = stringBuilder.toString()
    val textView: TextView = findViewById(R.id.activity_title) as TextView
    textView.text = "Paramlist is \n\n$paramListString"

    // to check if the url has specific keys
    if (sanitizer.hasParameter("type")) {
        val type = sanitizer.getValue("type")
        println("sanitizer has type param $type")
    }

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

Array or List in Java. Which is faster?

I'm guessing the original poster is coming from a C++/STL background which is causing some confusion. In C++ std::list is a doubly linked list.

In Java [java.util.]List is an implementation-free interface (pure abstract class in C++ terms). List can be a doubly linked list - java.util.LinkedList is provided. However, 99 times out of 100 when you want a make a new List, you want to use java.util.ArrayList instead, which is the rough equivalent of C++ std::vector. There are other standard implementations, such as those returned by java.util.Collections.emptyList() and java.util.Arrays.asList().

From a performance standpoint there is a very small hit from having to go through an interface and an extra object, however runtime inlining means this rarely has any significance. Also remember that String are typically an object plus array. So for each entry, you probably have two other objects. In C++ std::vector<std::string>, although copying by value without a pointer as such, the character arrays will form an object for string (and these will not usually be shared).

If this particular code is really performance-sensitive, you could create a single char[] array (or even byte[]) for all the characters of all the strings, and then an array of offsets. IIRC, this is how javac is implemented.

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

Font awesome is not showing icon

I successfully installed Font Awesome using their CDN and javascript include (as described on this page). Then I tried to copy the HTML and CSS to some legacy pages and suddenly I saw empty square boxes instead of the icons.

I saw Daniel's answer (above) and because my legacy CSS file was huge (and years old) I suspected that was the issue. However when I looked in Chrome DevTools it really looked like Font Awesome was loaded:

Screenshot of CSS for Font Awesome Icon

I was expecting to see the font in strikeout if there was an issue... However I had really exhausted all my options so I checked the Computed Styles and saw clearly that the Font Awesome font was definitely not being used. (See the Rendered font at the bottom)

Font Awesome not being used

My legacy CSS file was a mess and I preferred not to touch it, so I cheated by doing this - please don't tell anyone :)

<a class="nav-link fa fa-instagram" style="font-family:FontAwesome;" href="//www.instagram.com/xxxx/" target="_blank"></a>

Also to note, when I upgraded from Font Awesome version 4.7.0 to version 5.4.1 this issue went away! I used this setup guide and this HTML

<a class="nav-link" href="//www.instagram.com/xxxx/" target="_blank"><i class="fab fa-instagram"></i></a>

initializing strings as null vs. empty string

The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.

However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.

If you want to check whether a string (that does exist) is empty, use the empty method instead:

if (myStr.empty()) ...

Convert a positive number to negative in C#

int negInt = 0 - myInt;

Or guaranteed to be negative.

int negInt = -System.Math.Abs(someInt);

NameError: global name 'unicode' is not defined - in Python 3

You can use the six library to support both Python 2 and 3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

What is __init__.py for?

The __init__.py file makes Python treat directories containing it as modules.

Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

How to use pull to refresh in Swift?

Others Answers Are Correct But for More Detail check this Post Pull to Refresh

Enable refreshing in Storyboard

When you’re working with a UITableViewController, the solution is fairly simple: First, Select the table view controller in your storyboard, open the attributes inspector, and enable refreshing:

A UITableViewController comes outfitted with a reference to a UIRefreshControl out of the box. You simply need to wire up a few things to initiate and complete the refresh when the user pulls down.

Override viewDidLoad()

In your override of viewDidLoad(), add a target to handle the refresh as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
        
    self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
}
  1. Since I’ve specified “handleRefresh:” (note the colon!) as the action argument, I need to define a function in this UITableViewController class with the same name. Additionally, the function should take one argument
  2. We’d like this action to be called for the UIControlEvent called ValueChanged
  3. Don't forget to call refreshControl.endRefreshing()

For more information Please go to mention Link and all credit goes to that post

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

Bootstrap modal: close current, open new

if you use mdb use this code

    var visible_modal = $('.modal.show').attr('id'); // modalID or undefined
    if (visible_modal) { // modal is active
        $('#' + visible_modal).modal('hide'); // close modal
    }

Javascript: Easier way to format numbers?

There's the NUMBERFORMATTER jQuery plugin, details below:

https://code.google.com/p/jquery-numberformatter/

From the above link:

This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.

EDIT: Replaced the link with a more direct one.

How to update Xcode from command line

xCode version 11.2.1 is necessary for building app in iPad 13.2.3, When I directly try to upgrade from xcode 11.1 to 11.2.1 through App Store it get struck, So after some research , I found a solution to upgrade by removing the existing xcode from the system

So here I am adding the steps to upgrade after uninstalling existing xcode.

  1. Go to Applications and identify Xcode and drag it to trash.
  2. Empty trash to permenently delete Xcode.
  3. Now go to ~/Library/Developer/ folder and remove the contents completely Use sudo rm -rf ~/Library/Developer/ to avoid any permission issue while deleting
  4. Lastly remove any cache directory associated with xcode in the path ~/Library/Caches/com.apple.dt.Xcode sudo rm -rf ~/Library/Caches/com.apple.dt.Xcode/*
  5. After completing the above steps you can easly install xcode from App Store, which will install the current latest version of xcode

Note: Please take a backup of your existing projects before making the above changes

Error Code: 2013. Lost connection to MySQL server during query

If all the other solutions here fail - check your syslog (/var/log/syslog or similar) to see if your server is running out of memory during the query.

Had this issue when innodb_buffer_pool_size was set too close to physical memory without a swapfile configured. MySQL recommends for a database specific server setting innodb_buffer_pool_size at a max of around 80% of physical memory, I had it set to around 90%, the kernel was killing the mysql process. Moved innodb_buffer_pool_size back down to around 80% and that fixed the issue.

How to round up a number to nearest 10?

For people who want to do it with raw SQL, without using php, java, python etc. SET SQL_SAFE_UPDATES = 0; UPDATE db.table SET value=ceil(value/10)*10 where value not like '%0';

Laravel 5 - redirect to HTTPS

The answers above didn't work for me, but it appears that Deniz Turan rewrote the .htaccess in a way that works with Heroku's load balancer here: https://www.jcore.com/2017/01/29/force-https-on-heroku-using-htaccess/

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

You have entered wrong port number 3360 instead of 3306. You dont need to write database port number if you are using daefault (3306 in case of MySQL)

Unknown Column In Where Clause

If you're trying to perform a query like the following (find all the nodes with at least one attachment) where you've used a SELECT statement to create a new field which doesn't actually exist in the database, and try to use the alias for that result you'll run into the same problem:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes
WHERE attachmentcount > 0;

You'll get an error "Unknown column 'attachmentcount' in WHERE clause".

Solution is actually fairly simple - just replace the alias with the statement which produces the alias, eg:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes 
WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;

You'll still get the alias returned, but now SQL shouldn't bork at the unknown alias.

Get Android Phone Model programmatically

I use the following code to get the full device name. It gets model and manufacturer strings and concatenates them unless model string already contains manufacturer name (on some phones it does):

public String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
        return capitalize(model);
    } else {
        return capitalize(manufacturer) + " " + model;
    }
}


private String capitalize(String s) {
    if (s == null || s.length() == 0) {
        return "";
    }
    char first = s.charAt(0);
    if (Character.isUpperCase(first)) {
        return s;
    } else {
        return Character.toUpperCase(first) + s.substring(1);
    }
} 

 

Here are a few examples of device names I got from the users:

Samsung GT-S5830L
Motorola MB860
Sony Ericsson LT18i
LGE LG-P500
HTC Desire V
HTC Wildfire S A510e

How do I remove all non-ASCII characters with regex and Notepad++?

In Notepad++, if you go to menu Search ? Find characters in range ? Non-ASCII Characters (128-255) you can then step through the document to each non-ASCII character.

Be sure to tick off "Wrap around" if you want to loop in the document for all non-ASCII characters.

screenshot "Find in Range"

How to add element into ArrayList in HashMap

#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next());  //name
al.add(s.next());  //category
al.add(s.nextInt()); //fee
d.put(id, al);
 }

jQuery get the rendered height of an element?

You can use .outerHeight() for this purpose.

It will give you full rendered height of the element. Also, you don't need to set any css-height of the element. For precaution you can keep its height auto so it can be rendered as per content's height.

//if you need height of div excluding margin/padding/border
$('#someDiv').height();

//if you need height of div with padding but without border + margin
$('#someDiv').innerHeight();

// if you need height of div including padding and border
$('#someDiv').outerHeight();

//and at last for including border + margin + padding, can use
$('#someDiv').outerHeight(true);

For a clear view of these function you can go for jQuery's site or a detailed post here.

it will clear the difference between .height() / innerHeight() / outerHeight()

Difference between java.lang.RuntimeException and java.lang.Exception

In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can't do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.

Nuget connection attempt failed "Unable to load the service index for source"

I have stumbled across this issue when trying to run nuget.exe via Jenkins (configured as a service, by default using Local System account). I have edited C:\Windows\System32\config\systemprofile\AppData\Roaming\NuGet\NuGet.Config file which looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="http_proxy" value="http://proxy_hostname_or_ip:3128" />
        <add key="https_proxy" value="http://proxy_hostname_or_ip:3128" />
    </config>

  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>

</configuration> 

In order to test command prompt can be started via PSTools:

psexec -i -s CMD

and actual test run in the newly created cmd windows (runs as Local System):

path_to_nuget\nuget.exe restore "path_to_solution\theSolution.sln"

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three" 

How to split a string by spaces in a Windows batch file?

UPDATE: Well, initially I posted the solution to a more difficult problem, to get a complete split of any string with any delimiter (just changing delims). I read more the accepted solutions than what the OP wanted, sorry. I think this time I comply with the original requirements:

 @echo off
 IF [%1] EQU [] echo get n ["user_string"] & goto :eof
 set token=%1
 set /a "token+=1"
 set string=
 IF [%2] NEQ [] set string=%2
 IF [%2] EQU [] set string="AAA BBB CCC DDD EEE FFF"
 FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G

An other version with a better user interface:

 @echo off
 IF [%1] EQU [] echo USAGE: get ["user_string"] n & goto :eof
 IF [%2] NEQ [] set string=%1 & set token=%2 & goto update_token
 set string="AAA BBB CCC DDD EEE FFF"
 set token=%1
 :update_token
 set /a "token+=1"
 FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G

Output examples:

E:\utils\bat>get
USAGE: get ["user_string"] n
E:\utils\bat>get 5
FFF
E:\utils\bat>get 6
E:\utils\bat>get "Hello World" 1
World

This is a batch file to split the directories of the path:

@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO (
    for /f "tokens=*" %%g in ("%%G") do echo %%g
    set string="%%H"
    )
if %string% NEQ "" goto :loop

2nd version:

@echo off
set string="%PATH%"
:loop 
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO set line="%%G" & echo %line:"=% & set string="%%H"
if %string% NEQ "" goto :loop

3rd version:

@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO CALL :sub "%%G" "%%H"
if %string% NEQ "" goto :loop
goto :eof

:sub
set line=%1
echo %line:"=%
set string=%2

Unable to start Service Intent

1) check if service declaration in manifest is nested in application tag

<application>
    <service android:name="" />
</application>

2) check if your service.java is in the same package or diff package as the activity

<application>
    <!-- service.java exists in diff package -->
    <service android:name="com.package.helper.service" /> 
</application>
<application>
    <!-- service.java exists in same package -->
    <service android:name=".service" /> 
</application>

How to remove index.php from URLs?

How about this in your .htaccess:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Came here looking for a solution to a similar issue, which I just introduced by changing Schannel settings of our IIS server using "IIS Crypto" by Nartac... By disabling the SHA-1 hash, the local SQL Server was not able to be reached anymore, even though I didn't use an encrypted connection (not useful for an ASP.Net site accessing a local SQL Express instance using shared memory).

The 'SHA' hash algorithm needs to be active for SQL Server to connect

Thanks Count Zero for pointing me in the right direction :-)

So, lesson learned: do not disable SHA-1 on your IIS server if you have a local SQL Server instance.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

Set background image on grid in WPF using C#

In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code

<Grid>
  <Grid.Background>
    <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                AlignmentY="Top" AlignmentX="Center"/>
  </Grid.Background>
</Grid>

remove attribute display:none; so the item will be visible

For this particular purpose, $("span").show() should be good enough.

How to disable Django's CSRF validation?

The answer might be inappropriate, but I hope it helps you

class DisableCSRFOnDebug(object):
    def process_request(self, request):
        if settings.DEBUG:
            setattr(request, '_dont_enforce_csrf_checks', True)

Having middleware like this helps to debug requests and to check csrf in production servers.