Programs & Examples On #Sens

System Event Notification Service

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:


  • id
  • book specific info
  • etc


  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Pylint "unresolved import" error in Visual Studio Code

None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.

"python.languageServer": "Jedi"

Google Maps shows "For development purposes only"

As recommended in a comment, I used the "Google Maps Platform API Checker" Chrome add-in to identify and resolve the issue.

Essentially, this add-in directed me to here where I was able to sign in to Google and create a free API key.

Afterwards, I updated my JavaScript and it immediately resolved this issue.

Old JavaScript: ...script src="" ...

Updated Javascript:...script src="*****GOOGLE API KEY******&v=3" ...

The add-in then validated the JS API call. Hope this helps someone resolve the issue quickly!

enter image description here

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.

Update (11/2018):

Clarification needed based on down-votes, very helpful comments and other answers.


  • Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

  • What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:


    function hello(str: string): string {
      return 1;
    function foo(str:string):void{

    This will not compile. Error: Type "1" is not assignable to String

  • if you tried this syntax in a Javascript hello-world.js file:

    function hello(str: string): string {
      return 1;
    function foo(str:string):void{

    The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties

interface ResponseOrders {
  results: Order[];

export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().


In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

#include errors detected in vscode

The answer is here: How to use C/Cpp extension and add includepath to configurations.

Click the light bulb and then edit the JSON file which is opened. Choose the right block corresponding to your platform (there are Mac, Linux, Win32 – ms-vscode.cpptools version: 3). Update paths in includePath (matters if you compile with VS Code) or browse.paths (matters if you navigate with VS Code) or both.

Thanks to @Francesco Borzì, I will append his answer here:

You have to Left click on the bulb next to the squiggled code line.

If a #include file or one of its dependencies cannot be found, you can also click on the red squiggles under the include statements to view suggestions for how to update your configuration.

enter image description here

Specifying onClick event type with Typescript and React.Konva

You're probably out of luck without some hack-y workarounds

You could try

onClick={(event: React.MouseEvent<HTMLElement>) => {
 makeMove(ownMark, ( as any).index)

I'm not sure how strict your linter is - that might shut it up just a little bit

I played around with it for a bit, and couldn't figure it out, but you can also look into writing your own augmented definitions:

edit: please use the implementation in this reply it is the proper way to solve this issue (and also upvote him, while you're at it).

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Add dependencies. for example:- import 'package:audioplayers/audio_cache.dart'; in the above package if we only use this package then it shows error but if we add dependencies in pubspec.yaml such as

      sdk: flutter
    cupertino_icons: ^0.1.2
    audioplayers: ^0.14.1

enter image description here

then click on packages get.

as you see this, I can also insert dependencies so if you insert dependencies along with your package then you are good to go.

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.


  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>

<Target Name="GenerateNetcoreExe"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />


I wrapped it up in a sample here:

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

How to check if a key exists in Json Object and get its value

Please try this one..

JSONObject jsonObject= null;
try {
     jsonObject = new JSONObject("result........");
     String labelDataString=jsonObject.getString("LabelData");
     JSONObject labelDataJson= null;
     labelDataJson= new JSONObject(labelDataString);
       String video=labelDataJson.getString("video");
    } catch (JSONException e) {

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).

Vue template or render function not defined yet I am using neither?

If you used to calle a component like this:

Vue.component('dashboard', require('./components/Dashboard.vue'));

I suppose that problem occurred when you update to laravel mix 5.0 or another libraries, so you have to put .default. As like below:

Vue.component('dashboard', require('./components/Dashboard.vue').default);

I solved the same problem.

Passing data into "router-outlet" child components

Yes, you can set inputs of components displayed via router outlets. Sadly, you have to do it programmatically, as mentioned in other answers. There's a big caveat to that when observables are involved (described below).

Here's how:

(1) Hook up to the router-outlet's activate event in the parent template:

<router-outlet (activate)="onOutletLoaded($event)"></router-outlet>

(2) Switch to the parent's typescript file and set the child component's inputs programmatically each time they are activated:

onOutletLoaded(component) {
    component.node = 'someValue';


However, the above version of onOutletLoaded is simplified for clarity. It only works if you can guarantee all child components have the exact same inputs you are assigning. If you have components with different inputs, use type guards:

onChildLoaded(component: MyComponent1 | MyComponent2) {
  if (component instanceof MyComponent1) {
    component.someInput = 123;
  } else if (component instanceof MyComponent2) {
    component.anotherInput = 456;

Why may this method be preferred over the service method?

Neither this method nor the service method are "the right way" to communicate with child components (both methods step away from pure template binding), so you just have to decide which way feels more appropriate for the project.

This method, however, avoids the tight coupling associated with the "create a service for communication" approach (i.e., the parent needs the service, and the children all need the service, making the children unusable elsewhere). Decoupling is usually preferred.

In many cases this method also feels closer to the "angular way" because you can continue passing data to your child components through @Inputs (thats the decoupling part - this enables re-use elsewhere). It's also a good fit for already existing or third-party components that you don't want to or can't tightly couple with your service.

On the other hand, it may feel less like the angular way when...


The caveat with this method is that since you are passing data in the typescript file, you no longer have the option of using the pipe-async pattern used in templates (e.g. {{ myObservable$ | async }}) to automagically use and pass on your observable data to child components.

Instead, you'll need to set up something to get the current observable values whenever the onChildLoaded function is called. This will likely also require some teardown in the parent component's onDestroy function. This is nothing too unusual, there are often cases where this needs to be done, such as when using an observable that doesn't even get to the template.

React - Display loading screen while DOM is rendering?

I also used @Ori Drori's answer and managed to get it to work. As your React code grows, so will the bundles compiled that the client browser will have to download on first time access. This imposes a user experience issue if you don't handle it well.

What I added to @Ori answer was to add and execute the onload function in the index.html on onload attribute of the body tag, so that the loader disappear after everything has been fully loaded in the browse, see the snippet below:

       .loader:empty {
          position: absolute;
          top: calc(50% - 4em);
          left: calc(50% - 4em);
          width: 6em;
          height: 6em;
          border: 1.1em solid rgba(0, 0, 0, 0.2);
          border-left: 1.1em solid #000000;
          border-radius: 50%;
          animation: load8 1.1s infinite linear;
        @keyframes load8 {
          0% {
           transform: rotate(0deg);
          100% {
           transform: rotate(360deg);
       function onLoad() {
         var loader = document.getElementById("cpay_loader");loader.className = "";}
   <body onload="onLoad();">
     more html here.....

How to check if a file exists in a shell script

If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:

time timeout 3 test -f 
real    0m3.004s <<== timeout is taken into account
user    0m0.001s
sys     0m0.004s
echo $?
124   <= 124 means the timeout has been reached

A "[ -e my_file ]" construct will freeze until the NFS is functional again:

if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi

<no answer from the system, my session is "frozen">

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I faced this issue:

(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.

It was my mistake, I was replacing res object in then(function(res), so changed res to result and now it is working.


module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(res){//issue was here, res overwrite
                    return res.json(res);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");


module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(result){//res replaced with result
                    return res.json(result);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");

Service code:

function update(data){
   var id = new require('mongodb').ObjectID(data._id);
        userData = {
 return collection.findAndModify(
          {_id:id}, // query
          [['_id','asc']],  // sort order
          {$set: userData}, // replacement
          { "new": true }
          ).then(function(doc) {
                    throw new Error('Record not updated.');
                return doc.value;   

module.exports = {

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'

create table example_table (
  id integer,
  enum_field example_enum

  example_table t
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

  example_table t
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));


NSCameraUsageDescription in iOS 10.0 runtime crash?

I had the same problem and could not find a solution. Mark90 is right there are a lot info.plist files and you should edit the correct. Go to Project, under TARGETS select the project (not the tests), in the tab bar select Info and add the permission under "Custom iOS Target Properties".

What is mapDispatchToProps?

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)

Updates were rejected because the tip of your current branch is behind its remote counterpart

This is how I solved my problem

Let's assume the upstream branch is the one that you forked from and origin is your repo and you want to send an MR/PR to the upstream branch.

You already have let's say about 4 commits and you are getting Updates were rejected because the tip of your current branch is behind.

Here is what I did

First, squash all your 4 commits

git rebase -i HEAD~4

You'll get a list of commits with pick written on them. (opened in an editor)


pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
pick c011a77 commit 4


pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
squash c011a77 commit 4

After that, you can save your combined commit


You'll need to stash your commit

Here's how

git reset --soft HEAD~1
git stash

now rebase with your upstream branch

git fetch upstream beta && git rebase upstream/beta

Now pop your stashed commit

git stash pop

commit these changes and push them

git add -A
git commit -m "[foo] - foobar commit"
git push origin fix/#123 -f

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

    "page": 1,
    "results": [ ... ]

So you in fact want to iterate the results field only: = res.json()['results'];

... or even easier: = res.json().results;

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {

    return obj;   

Homebrew refusing to link OpenSSL

As the update to the other answer suggests, the workaround of installing the old openssl101 brew will no longer work. For a right-now workaround, see this comment on dotnet/cli#3964.

The most relevant part of the issue copied here:

I looked into the other option that was suggested for setting the rpath on the library. I think the following is a better solution that will only effect this specific library.

sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib /usr/local/share/dotnet/shared/Microsoft.NETCore.App/1.0.0/System.Security.Cryptography.Native.dylib

and/or if you have NETCore 1.0.1 installed perform the same command for 1.0.1 as well:

sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib /usr/local/share/dotnet/shared/Microsoft.NETCore.App/1.0.1/System.Security.Cryptography.Native.dylib

In effect, rather than telling the operating system to always use the homebrew version of SSL and potentially causing something to break, we're telling dotnet how to find the correct library.

Also importantly, it looks like Microsoft are aware of the issue and and have both a) a somewhat immediate plan to mitigate as well as b) a long-term solution (probaby bundling OpenSSL with dotnet).

Another thing to note: /usr/local/opt/openssl/lib is where the brew is linked by default:

13:22 $ ls -l /usr/local/opt/openssl
lrwxr-xr-x  1 ben  admin  26 May 15 14:22 /usr/local/opt/openssl -> ../Cellar/openssl/1.0.2h_1

If for whatever reason you install the brew and link it in a different location, then that path is the one you should use as an rpath.

Once you've update the rpath of the System.Security.Cryptography.Native.dylib libray, you'll need to restart your interactive session (i.e., close your console and start another one).

How to pass data from child component to its parent in ReactJS?

in React v16.8+ function component, you can use useState() to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:

const { useState , useEffect } = React;_x000D_
function Timer({ setParentCounter }) {_x000D_
  const [counter, setCounter] = React.useState(0);_x000D_
  useEffect(() => {_x000D_
    let countersystem;_x000D_
    countersystem = setTimeout(() => setCounter(counter + 1), 1000);_x000D_
    return () => {_x000D_
  }, [counter]);_x000D_
  return (_x000D_
    <div className="App">_x000D_
        onClick={() => {_x000D_
        Set parent counter value_x000D_
      <hr />_x000D_
      <div>Child Counter: {counter}</div>_x000D_
function App() {_x000D_
  const [parentCounter, setParentCounter] = useState(0);_x000D_
  return (_x000D_
    <div className="App">_x000D_
      Parent Counter: {parentCounter}_x000D_
      <hr />_x000D_
      <Timer setParentCounter={setParentCounter} />_x000D_
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div id="react-root"></div>

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
} Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/ security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security

Issue is that it is failed to decrypt 256 bits of encryption.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

.NET Core vs Mono

Providing an actual answer.

What is the difference between .Net Core and Mono?

.NET Core now officially is the future of .NET. It started for most part with a re-write of the ASP.NET MVC framework and console applications, which of course includes server applications. (Since it's Turing-complete and supports interop with C dlls, you could, if you absolutely wanted to, also write your own desktop applications with it, for example through 3rd-party libraries like Avalonia, which were a bit very basic at the time I first wrote this, which meant you were pretty much limited to web or server stuff.) Over time, many APIs have been added to .NET Core, so much so that after version 3.1, .NET Core will jump to version 5.0, be known as .NET 5.0 without the "Core", and that then will be the future of the .NET Framework. What used to be the full .NET Framework will linger around in maintenance mode as Full .NET Framework 4.8.x for a few decades, until it will die (maybe there are still going to be some upgrades, but I doubt it). In other words, .NET Core is the future of .NET, and Full .NET Framework will go the way of the Dodo/Silverlight/WindowsPhone.

The main point of .NET Core, apart from multi-platform support, is to improve performance, and to enable "native compilation"/self-contained-deployment (so you don't need .NET framework/VM installed on the target machine.
On the one hand, this means support on Linux, and on the other, self-contained deployment is useful in "cloud-computing", since then you can just use whatever version of the dotnet-CORE framework you like, and you don't have to worry about which version(s) of the .NET framework the sysadmin has actually installed.

While the .NET Core runtime supports multiple operating systems and processors, the SDK is a different story. And while the SDK supports multiple OS, ARM support for the SDK is/was still work in progress. .NET Core is supported by Microsoft. Dotnet-Core did not come with WinForms or WPF or anything like that.

  • As of version 3.0, WinForms and WPF is also supported by .NET Core, but only on Windows, and only by C#. Not by VB.NET (VB.NET support planned for v5 in 2020). And there is no Forms Designer in .NET Core: it's being shipped with a Visual Studio update later, at an unspecified time.
  • WebForms are still not supported by .NET Core, and there are no plans to support them, ever (Blazor is the new kid in town for that).
  • .NET Core also comes with System.Runtime, which replaces mscorelib.
  • Oftentimes, .NET Core is mixed up with NetStandard, which is a bit of a wrapper around System.Runtime/mscorelib (and some others), that allows you to write libraries that target .NET Core, Full .NET Framework and Xamarin (iOS/Android), all at the same time.
  • the .NET Core SDK does not/did not work on ARM, at least not last time I checked.

"The Mono Project" is much older than .NET Core.
Mono is Spanish and means Monkey, and as a side-remark, the name has nothing to do with mononucleosis (hint: you could get a list of staff under
Mono was started in 2005 by Miguel de Icaza (the guy that started GNOME - and a few others) as an implementation of the .NET Framework for Linux (Ximian/SuSe/Novell). Mono includes Web-Forms, Winforms, MVC, Olive, and an IDE called MonoDevelop (also knows as Xamarin Studio or Visual Studio Mac). Basically the equivalent of (OpenJDK) JVM and (OpenJDK) JDK/JRE (as opposed to SUN/Oracle JDK). You can use it to get ASP.NET-WebForms + WinForms + ASP.NET-MVC applications to work on Linux.

Mono is supported by Xamarin (the new company name of what used to be Ximian, when they focused on the Mobile market, instead of the Linux market), and not by Microsoft.
(since Xamarin was bought by Microsoft, that's technically [but not culturally] Microsoft.)
You will usually get your C# stuff to compile on mono, but not the VB.NET stuff.
Mono misses some advanced features, like WSE/WCF and WebParts.
Many of the Mono implementations are incomplete (e.g. throw NotImplementedException in ECDSA encryption), buggy (e.g. ODBC/ADO.NET with Firebird), behave differently than on .NET (for example XML-serialization) or otherwise unstable (ASP.NET MVC) and unacceptably slow (Regex). On the upside, the Mono toolchain also works on ARM.

As far as .NET Core is concerned, when they say cross-platform, don't expect that cross-platform means that you could actually just apt-get install .NET Core on ARM-Linux, like you can with ElasticSearch. You'll have to compile the entire framework from source.
That is, if you have that space (e.g. on a Chromebook, which has a 16 to 32 GB total HD).
It also used to have issues of incompatibility with OpenSSL 1.1 and libcurl.
Those have been rectified in the latest version of .NET Core Version 2.2.
So much for cross-platform.

I found a statement on the official site that said, "Code written for it is also portable across application stacks, such as Mono".

As long as that code doesn't rely on WinAPI-calls, Windows-dll-pinvokes, COM-Components, a case-insensitive file system, the default-system-encoding (codepage) and doesn't have directory separator issues, that's correct. However, .NET Core code runs on .NET Core, and not on Mono. So mixing the two will be difficult. And since Mono is quite unstable and slow (for web applications), I wouldn't recommend it anyway. Try image-processing on .NET core, e.g. WebP or moving GIF or multipage-tiff or writing text on an image, you'll be nastily surprised.

As of .NET Core 2.0, there is System.Drawing.Common (NuGet), which contains most of the functionality of System.Drawing. It should be more or less feature-complete in .NET-Core 2.1. However, System.Drawing.Common uses GDI+, and therefore won't work on Azure (System.Drawing libraries are available in Azure Cloud Service [basically just a VM], but not in Azure Web App [basically shared hosting?])
So far, System.Drawing.Common works fine on Linux/Mac, but has issues on iOS/Android - if it works at all, there.
Prior to .NET Core 2.0, that is to say sometime mid-February 2017, you could use SkiaSharp for imaging (example) (you still can).
Post .net-core 2.0, you'll notice that SixLabors ImageSharp is the way to go, since System.Drawing is not necessarely secure, and has a lot of potential or real memory leaks, which is why you shouldn't use GDI in web-applications; Note that SkiaSharp is a lot faster than ImageSharp, because it uses native-libraries (which can also be a drawback). Also, note that while GDI+ works on Linux & Mac, that doesn't mean it works on iOS/Android.

Code not written for .NET (non-Core) is not portable to .NET Core.
Meaning, if you want a non-GPL C# library like PDFSharp to create PDF-documents (very commonplace), you're out of luck (at the moment) (not anymore). Never mind ReportViewer control, which uses Windows-pInvokes (to encrypt, create mcdf documents via COM, and to get font, character, kerning, font embedding information, measure strings and do line-breaking, and for actually drawing tiffs of acceptable quality), and doesn't even run on Mono on Linux
(I'm working on that).

Also, code written in .NET Core is not portable to Mono, because Mono lacks the .NET Core runtime libraries (so far).

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

EF in any version that I tried so far was so goddamn slow (even on such simple things like one table with one left-join), I wouldn't recommend it ever - not on Windows either.
I would particularly not recommend EF if you have a database with unique-constrains, or varbinary/filestream/hierarchyid columns. (Not for schema-update either.)
And also not in a situation where DB-performance is critical (say 10+ to 100+ concurrent users).
Also, running a website/web-application on Linux will sooner or later mean you'll have to debug it.
There is no debugging support for .NET Core on Linux. (Not anymore, but requires JetBrains Rider.)
MonoDevelop does not (yet) support debugging .NET Core projects.
If you have problems, you're on your own. You'll have to use extensive logging.
Be careful, be advised extensive logging will fill your disk in no time, particularly if your program enters an infinite loop or recursion.
This is especially dangerous if your web-app runs as root, because log-in requires logfile-space - if there's no free space left, you won't be able to login anymore.
(Normally, about 5% of diskspace is reserved for user root [aka administrator on Windows], so at least the administrator can still log in if the disk is almost full. But if your applications run as root, that restriction does not apply for their disk usage, and so their logfiles can use 100% of the remaining free space, so not even the administrator can log in any more.)
It's therefore better not to encrypt that disk, that is, if you value your data/system.

Someone told me that he wanted it to be "in Mono", but I don't know what that means.

It either means he doesn't want to use .NET Core, or he just wants to use C# on Linux/Mac. My guess is he just wants to use C# for a Web-App on Linux. .NET Core is the way to go for that, if you absolutely want to do it in C#. Don't go with "Mono proper"; on the surface, it would seem to work at first - but believe me you will regret it because Mono's ASP.NET MVC isn't stable when your server runs long-term (longer than 1 day) - you have now been warned. See also the "did not complete" references when measuring Mono performance on the techempower benchmarks.


I know I want to use the .Net Core 1.0 framework with the technologies I listed above. He also said he wanted to use "fast cgi". I don't know what that means either.

It means he wants to use a high-performance full-featured WebServer like nginx (Engine-X), possibly Apache.
Then he can run mono/dotnetCore with virtual name based hosting (multiple domain names on the same IP) and/or load-balancing. He can also run other websites with other technologies, without requiring a different port-number on the web-server. It means your website runs on a fastcgi-server, and nginx forwards all web-requests for a certain domain via the fastcgi-protocol to that server. It also means your website runs in a fastcgi-pipeline, and you have to be careful what you do, e.g. you can't use HTTP 1.1 when transmitting files.
Otherwise, files will be garbled at the destination.
See also here and here.

To conclude:
.NET Core at present (2016-09-28) is not really portable, nor is is really cross-platform (in particular the debug-tools).
Nor is native-compilation easy, especially for ARM.
And to me, it also does not look like its development is "really finished", yet.
For example, System.Data.DataTable/DataAdaper.Update is missing... (not anymore with .NET Core 2.0)
Together with the System.Data.Common.IDB* interfaces. (not anymore with .NET Core 1.1)
if there ever was one class that is often used, DataTable/DataAdapter would be it...
Also, the Linux-installer (.deb) fails, at least on my machine, and I'm sure I'm not the only one that has that problem.
Debug, maybe with Visual Studio Code, if you can build it on ARM (I managed to do that - do NOT follow Scott Hanselman's blog-post if you do that - there's a howto in the wiki of VS-Code on github), because they don't offer the executable.
Yeoman also fails. (I guess it has something to do with the nodejs version you installed - VS Code requires one version, Yeoman another... but it should run on the same computer. pretty lame
Never mind that it should run on the node version shipped by default on the OS.
Never mind that there should be no dependency on NodeJS in the first place.
The kestell server is also work in progress.
And judging by my experience with the mono-project, I highly doubt they ever tested .NET Core on FastCGI, or that they have any idea what FastCGI-support means for their framework, let alone that they tested it to make sure "everything works". In fact, I just tried making a fastcgi-application with .NET Core and just realized there is no FastCGI library for .NET Core "RTM"...

So when you're going to run .NET Core "RTM" behind nginx, you can only do it by proxying requests to kestrell (that semi-finished nodeJS-derived web-server) - there's no fastcgi support at present in .NET Core "RTM", AFAIK. Since there is no .net core fastcgi library, and no samples, it's also highly unlikely that anybody did any testing on the framework to make sure fastcgi works as expected.

I also question the performance.
In the (preliminary) techempower-benchmark (round 13), aspnetcore-linux ranks on 25% relative to the best performance, while comparable frameworks like Go (golang) rank at 96.9% of peak performance (and that is when returning plaintext without file-system access only). .NET Core does a little better on JSON-serialization, but it does not look compelling either (go reaches 98.5% of peak, .NET core 65%). That said, it can't possibly be worse than "mono proper".

Also, since it's still relatively new, not all of the major libraries have been ported (yet), and I doubt that some of them will ever be ported.
Imaging support is also questionable at best.
For anything encryption, use BouncyCastle instead.

Can you help me make sense of all these terms and if my expectations are realistic?

I hope i helped you making more sense with all these terms.
As far as your expecations go:
Developing a Linux application without knowing anything about Linux is a really stupid idea in the first place, and it's also bound to fail in some horrible way one way or the other. That said, because Linux comes at no licensing costs, it's a good idea in principle, BUT ONLY IF YOU KNOW WHAT YOU DO.
Developing an application for a platform where you can't debug your application on is another really bad idea.
Developing for fastcgi without knowing what consequences there are is yet another really bad idea.

Doing all these things on a "experimental" platform without any knowledge of that platform's specifics and without debugging support is suicide, if your project is more than just a personal homepage. On the other hand, I guess doing it with your personal homepage for learning purposes would probably be a very good experience - then you get to know what the framework and what the non-framework problems are.
You can for example (programmatically) loop-mount a case-insensitive fat32, hfs or JFS for your application, to get around the case-sensitivity issues (loop-mount not recommended in production).

To summarize
At present (2016-09-28), I would stay away from .NET Core (for production usage). Maybe in one to two years, you can take another look, but probably not before.
If you have a new web-project that you develop, start it in .NET Core, not mono.

If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on .NET, Java or Windows, use Golang instead. It's more mature, and its performance is proven (Baidu uses it with 1 million concurrent users), and golang has a significantly lower memory footprint. Also golang is in the repositories, the .deb installs without problems, the sourcecode compiles - without requiring changes - and golang (in the meantime) has debugging support with delve and JetBrains Gogland on Linux (and Windows and Mac). Golang's build process (and runtime) also doesn't depend on NodeJS, which is yet another plus.

As far as mono goes, stay away from it.
It is nothing short of amazing how far mono has come, but unfortunately that's no substitute for its performance/scalability and stability issues for production applications.
Also, mono-development is quite dead, they largely only develop the parts relevant to Android and iOS anymore, because that's where Xamarin makes their money.
Don't expect Web-Development to be a first-class Xamarin/mono citizen.
.NET Core might be worth it, if you start a new project, but for existing large web-forms projects, porting over is largely out of the question, the changes required are huge. If you have a MVC-project, the amount of changes might be manageable, if your original application design was sane, which is mostly not the case for most existing so-called "historically grown" applications.

December 2016 Update:
Native compilation has been removed from .NET Core preview, as it is not yet ready...

Seems like they have improved pretty heavily on the raw text-file benchmark, but on the other hand, it's gotten pretty buggy. Also, it further deteriorated in the JSON benchmarks. Curious also that entity framework shall be faster for updates than Dapper - although both at record slowness. This is very unlikely to be true. Looks like there still are more than just a few bugs to hunt.

Also, there seems to be relief coming on the Linux IDE front.
JetBrains released "Project Rider", an early access preview of a C#/.NET Core IDE for Linux (and Mac and Windows), that can handle Visual Studio Project files. Finally a C# IDE that is usable & that isn't slow as hell.

Conclusion: .NET Core still is pre-release quality software as we march into 2017. Port your libraries, but stay away from it for production usage, until framework quality stabilizes.
And keep an eye on Project Rider.

buggy .net core

2017 Update
Have migrated my (brother's) homepage to .NET Core for now.
So far, the runtime on Linux seems to be stable enough (at least for small projects) - it survived a load test with ease - mono never did.
Also, it looks like I mixed up .NET-Core-native and .NET-Core-self-contained-deployment. Self-contained deployment works, but it is a bit underdocumented, although it's super easy (the build/publish tools are a bit unstable, yet - if you encounter "Positive number required. - Build FAILED." - run the same command again, and it works).

You can run

dotnet restore -r win81-x64
dotnet build -r win81-x64
dotnet publish -f netcoreapp1.1 -c Release -r win81-x64

Note: As per .NET Core 3, you can publish everything minified as a single file:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
dotnet publish -r linux-x64 -c Release /p:PublishSingleFile=true

However, unlike go, it's not a statically linked executable, but a self-extracting zip file, so when deploying, you might run into problems, especially if the temp directory is locked down by group policy, or some other issues. Works fine for a hello-world program, though. And if you don't minify, the executable size will clock in at something around 100 MB.

And you get a self-contained .exe-file (in the publish directory), which you can move to a Windows 8.1 machine without .NET framework installed and let it run. Nice. It's here that dotNET-Core just starts to get interesting. (mind the gaps, SkiaSharp doesn't work on Windows 8.1 / Windows Server 2012 R2, [yet] - the ecosystem has to catch up first - but interestingly, the Skia-dll-load-fail doesn't crash the entire server/application - so everything else works)

(Note: SkiaSharp on Windows 8.1 is missing the appropriate VC runtime files - msvcp140.dll and vcruntime140.dll. Copy them into the publish-directory, and Skia will work on Windows 8.1.)

August 2017 Update
.NET Core 2.0 released.
Be careful - comes with (huge breaking) changes in authentication...
On the upside, it brought the DataTable/DataAdaper/DataSet classes back, and many more.
Realized .NET Core is still missing support for Apache SparkSQL, because Mobius isn't yet ported. That's bad, because that means no SparkSQL support for my IoT Cassandra Cluster, so no joins...
Experimental ARM support (runtime only, not SDK - too bad for devwork on my Chromebook - looking forward to 2.1 or 3.0).
PdfSharp is now experimentally ported to .NET Core.
JetBrains Rider left EAP. You can now use it to develop & debug .NET Core on Linux - though so far only .NET Core 1.1 until the update for .NET Core 2.0 support goes live.

May 2018 Update
.NET Core 2.1 release imminent. Maybe this will fix NTLM-authentication on Linux (NTLM authentication doesn't work on Linux {and possibly Mac} in .NET-Core 2.0 with multiple authenticate headers, such as negotiate, commonly sent with ms-exchange, and they're apparently only fixing it in v2.1, no bugfix release for 2.0).
But I'm not installing preview releases on my machine. So waiting.
v2.1 is also said to greatly reduce compile times. That would be good.

Also, note that on Linux, .NET Core is 64-Bit only !
There is no, and there will be no, x86-32 version of .NET Core on Linux.
And the ARM port is ARM-32 only. No ARM-64, yet.
And on ARM, you (at present) only have the runtime, not the dotnet-SDK.

And one more thing:
Because .NET-Core uses OpenSSL 1.0, .NET Core on Linux doesn't run on Arch Linux, and by derivation not on Manjaro (the most popular Linux distro by far at this point in time), because Arch Linux uses OpenSSL 1.1. So if you're using Arch Linux, you're out of luck (with Gentoo, too).


Latest version of .NET Core 2.2+ supports OpenSSL 1.1. So you can use it on Arch or (k)Ubuntu 19.04+. You might have to use the .NET-Core install script though, because there are no packages, yet.

On the upside, performance has definitely improved: fortunes


.NET Core 3:
.NET-Core v 3.0 is said to bring WinForms and WPF to .NET-Core.
However, while WinForms and WPF will be .NET Core, WinForms and WPF in .NET-Core will run on Windows only, because WinForms/WPF will use the Windows-API.

.NET Core 3.0 is now out (RTM), and there is WinForms and WPF support, but only for C# (on Windows). There is no WinForms-Core-Designer. The designer will, eventually, come with a Visual Studio update, somewhen. WinForms support for VB.NET is not supported, but is planned for .NET 5.0 somewhen in 2020.


echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> /etc/environment

If you've used it on windows, you probably never saw this:

The .NET Core tools collect usage data in order to improve your experience.
The data is anonymous and does not include command-line arguments.
The data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @

I thought I'd mention that I think monodevelop (aka Xamarin Studio, the Mono IDE, or Visual Studio Mac as it is now called on Mac) has evolved quite nicely, and is - in the meantime - largely usable.
However, JetBrains Rider (2018 EAP at this point in time) is definitely a lot nicer and more reliable (and the included decompiler is a life-safer), that is to say, if you develop .NET-Core on Linux or Mac. MonoDevelop does not support Debug-StepThrough on Linux in .NET Core, though, since MS does not license their debugging API dll (except for VisualStudio Mac ... ). However, you can use the Samsung debugger for .NET Core through the .NET Core debugger extension for Samsung Debugger for MonoDevelop

I don't use Mac, so I can't say if what I wrote here applies to FreeBSD-Unix based Mac as well. I am refering to the Linux (Debian/Ubuntu/Mint) version of JetBrains Rider, mono, MonoDevelop/VisualStudioMac/XamarinStudio and .NET-Core. Also, Apple is contemplating a move from Intel-processors to self-manufactured ARM(ARM-64?)-based processors, so much of what applies to Mac right now might not apply to Mac in the future (2020+).

Also, when I write "mono is quite unstable and slow", the unstable relates to WinFroms & WebForms applications, specifically executing web-applications via fastcgi or with XSP (on the 4.x version of mono), as well as XML-serialization-handling peculiarities, and the quite-slow relates to WinForms, and regular expressions in particular (ASP.NET-MVC uses regular expressions for routing as well).

When I write about my experience about mono 2.x, 3.x and 4.x, that also does not necessarely mean these issues haven't been resolved by now, or by the time you are reading this, nor that if they are fixed now, that there can't be a regression later that reintroduces any of these bugs/features. Nor does that mean that if you embed the mono-runtime, you'll get the same results as when you use the (dev) system's mono runtime. It also doesn't mean that embedding the mono-runtime (anywhere) is necessarely free.

All that doesn't necessarely mean mono is ill-suited for iOS or Android, or that it has the same issues there. I don't use mono on Android or IOS, so I'm in no positon to say anything about stability, usability, costs and performance on these platforms. Obviously, if you use .NET on Android, you have some other costs considerations to do as well, such as weighting xamarin-costs vs. costs and time for porting existing code to Java. One hears mono on Android and IOS shall be quite good. Take it with a grain of salt. For one, don't expect the default-system-encoding to be the same on android/ios vs. Windows, and don't expect the android filesystem to be case-insensitive, and don't expect any windows fonts to be present.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load() method:

protected void Page_Load(object sender, EventArgs e)
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

Its work for me in .NET 4.5

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
  name: service-y
  namespace: namespace-a
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  - port: 80

Dynamic classname inside ngClass in angular 2

You can use <i [className]="'fa fa-' + data?.icon"> </i>

Retrofit 2 - URL Query Parameter

If you specify @GET("foobar?a=5"), then any @Query("b") must be appended using &, producing something like foobar?a=5&b=7.

If you specify @GET("foobar"), then the first @Query must be appended using ?, producing something like foobar?b=7.

That's how Retrofit works.

When you specify @GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.

Remove the ?, and you will get the desired result.

Bootstrap 4 card-deck with number of columns based on viewport

@Zim provided a great solution above (well deserved up-vote from me), however, it didn't quite fit what I needed since I was implementing this in Jekyll and wanted my card deck to automatically update every time I added a post to my site. Growing a card deck such as this with each new post is straight forward in Jekyll, the challenge was to correctly place the breakpoints. My solution make use of additional liquid tags and modulo mathematics.

While this question is old, I came across it and found it useful, and maybe someday someone will come along wanting to do this with Jekyll.

<div class = "container">
  <div class = "card-deck">

    {% for post in site.posts %}
      <div class = "card border-0 mt-2">
        <a href = "{{ post.url }}"><img src = "{{ site.baseurl }}{{ post.image }}" class = "mx-auto" alt = "..."></a>
        <div class = "card-body">
          <h5 class = "card-title"><a href = "{{ post.url }}">{{ post.title }}</a></h5>
          <span>Published: {{ | date_to_long_string }} </span>
          <p class = "text-muted">{{ post.excerpt }}</p>
        <div class = "card-footer bg-white border-0"><a href = "{{ post.url }}" class = "btn btn-primary">Read more</a></div>

      <!-- Use modulo to add divs to handle break points -->
      {% assign sm = forloop.index | modulo: 2 %}
      {% assign md = forloop.index | modulo: 3 %}
      {% assign lg = forloop.index | modulo: 4 %}
      {% assign xl = forloop.index | modulo: 5 %}

      {% if sm == 0 %}
        <div class="w-100 d-none d-sm-block d-md-none"><!-- wrap every 2 on sm--></div>
      {% endif %}

      {% if md == 0 %}
        <div class="w-100 d-none d-md-block d-lg-none"><!-- wrap every 3 on md--></div>
      {% endif %}

      {% if lg == 0 %}
        <div class="w-100 d-none d-lg-block d-xl-none"><!-- wrap every 4 on lg--></div>
      {% endif %}

      {% if xl == 0 %}
        <div class="w-100 d-none d-xl-block"><!-- wrap every 5 on xl--></div>
      {% endif %}

    {% endfor %}

This whole code block can be used directly in a website or saved in your Jekyll project _includes folder.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

First of all, it is a waste of an executor slot to wrap the build step in node. Your upstream executor will just be sitting idle for no reason.

Second, from a multibranch project, you can use the environment variable BRANCH_NAME to make logic conditional on the current branch.

Third, the job parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.

Thus what you meant to write is probably

if (env.BRANCH_NAME == 'master') {
    build '../other-repo/master'

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

In my case, i was facing this issue while installing create-react-app in MAC (Mojave OS) with following command :

sudo npm install create-react-app -g

and got errors like this :

npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/src/scheduler'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/src/symbol'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/src/testing'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/src/util'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/src/webSocket'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/symbol'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/testing'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/util'
npm WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-a84420a7/webSocket'

I have read that try to install without sudo :

npm install create-react-app -g

and it actually solved my issue ..!!

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Here is based on my understanding. Hopefully it's helpful. It's supposed to render a list of any components as the example behind. The root tag of each component needs to have a key. It doesn't have to be unique. It cannot be key=0, key='0', etc. It looks the key is useless.

render() {
    return [
        (<div key={0}> div 0</div>),
        (<div key={1}> div 2</div>),
        (<table key={2}><tbody><tr><td> table </td></tr></tbody></table>),
        (<form key={3}> form </form>),

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into

var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Setting up and using Meld as your git difftool and mergetool

How do I set up and use Meld as my git difftool?

git difftool displays the diff using a GUI diff program (i.e. Meld) instead of displaying the diff output in your terminal.

Although you can set the GUI program on the command line using -t <tool> / --tool=<tool> it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
    tool = meld
    prompt = false
[difftool "meld"]
    cmd = meld "$LOCAL" "$REMOTE"

[Note: These settings will not alter the behaviour of git diff which will continue to function as usual.]

You use git difftool in exactly the same way as you use git diff. e.g.

git difftool <COMMIT_HASH> file_name
git difftool <BRANCH_NAME> file_name
git difftool <COMMIT_HASH_1> <COMMIT_HASH_2> file_name

If properly configured a Meld window will open displaying the diff using a GUI interface.

The order of the Meld GUI window panes can be controlled by the order of $LOCAL and $REMOTE in cmd, that is to say which file is shown in the left pane and which in the right pane. If you want them the other way around simply swap them around like this:

    cmd = meld "$REMOTE" "$LOCAL"

Finally the prompt = false line simply stops git from prompting you as to whether you want to launch Meld or not, by default git will issue a prompt.

How do I set up and use Meld as my git mergetool?

git mergetool allows you to use a GUI merge program (i.e. Meld) to resolve the merge conflicts that have occurred during a merge.

Like difftool you can set the GUI program on the command line using -t <tool> / --tool=<tool> but, as before, it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
    tool = meld
[mergetool "meld"]
    # Choose one of these 2 lines (not both!) explained below.
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"

You do NOT use git mergetool to perform an actual merge. Before using git mergetool you perform a merge in the usual way with git. e.g.

git checkout master
git merge branch_name

If there is a merge conflict git will display something like this:

$ git merge branch_name
Auto-merging file_name
CONFLICT (content): Merge conflict in file_name
Automatic merge failed; fix conflicts and then commit the result.

At this point file_name will contain the partially merged file with the merge conflict information (that's the file with all the >>>>>>> and <<<<<<< entries in it).

Mergetool can now be used to resolve the merge conflicts. You start it very easily with:

git mergetool

If properly configured a Meld window will open displaying 3 files. Each file will be contained in a separate pane of its GUI interface.

In the example .gitconfig entry above, 2 lines are suggested as the [mergetool "meld"] cmd line. In fact there are all kinds of ways for advanced users to configure the cmd line, but that is beyond the scope of this answer.

This answer has 2 alternative cmd lines which, between them, will cater for most users, and will be a good starting point for advanced users who wish to take the tool to the next level of complexity.

Firstly here is what the parameters mean:

  • $LOCAL is the file in the current branch (e.g. master).
  • $REMOTE is the file in the branch being merged (e.g. branch_name).
  • $MERGED is the partially merged file with the merge conflict information in it.
  • $BASE is the shared commit ancestor of $LOCAL and $REMOTE, this is to say the file as it was when the branch containing $REMOTE was originally created.

I suggest you use either:

[mergetool "meld"]
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"


[mergetool "meld"]
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"
    # See 'Note On Output File' which explains --output "$MERGED".

The choice is whether to use $MERGED or $BASE in between $LOCAL and $REMOTE.

Either way Meld will display 3 panes with $LOCAL and $REMOTE in the left and right panes and either $MERGED or $BASE in the middle pane.

In BOTH cases the middle pane is the file that you should edit to resolve the merge conflicts. The difference is just in which starting edit position you'd prefer; $MERGED for the file which contains the partially merged file with the merge conflict information or $BASE for the shared commit ancestor of $LOCAL and $REMOTE. [Since both cmd lines can be useful I keep them both in my .gitconfig file. Most of the time I use the $MERGED line and the $BASE line is commented out, but the commenting out can be swapped over if I want to use the $BASE line instead.]

Note On Output File: Do not worry that --output "$MERGED" is used in cmd regardless of whether $MERGED or $BASE was used earlier in the cmd line. The --output option simply tells Meld what filename git wants the conflict resolution file to be saved in. Meld will save your conflict edits in that file regardless of whether you use $MERGED or $BASE as your starting edit point.

After editing the middle pane to resolve the merge conflicts, just save the file and close the Meld window. Git will do the update automatically and the file in the current branch (e.g. master) will now contain whatever you ended up with in the middle pane.

git will have made a backup of the partially merged file with the merge conflict information in it by appending .orig to the original filename. e.g. file_name.orig. After checking that you are happy with the merge and running any tests you may wish to do, the .orig file can be deleted.

At this point you can now do a commit to commit the changes.

If, while you are editing the merge conflicts in Meld, you wish to abandon the use of Meld, then quit Meld without saving the merge resolution file in the middle pane. git will respond with the message file_name seems unchanged and then ask Was the merge successful? [y/n], if you answer n then the merge conflict resolution will be aborted and the file will remain unchanged. Note that if you have saved the file in Meld at any point then you will not receive the warning and prompt from git. [Of course you can just delete the file and replace it with the backup .orig file that git made for you.]

If you have more than 1 file with merge conflicts then git will open a new Meld window for each, one after another until they are all done. They won't all be opened at the same time, but when you finish editing the conflicts in one, and close Meld, git will then open the next one, and so on until all the merge conflicts have been resolved.

It would be sensible to create a dummy project to test the use of git mergetool before using it on a live project. Be sure to use a filename containing a space in your test, in case your OS requires you to escape the quotes in the cmd line, see below.

Escaping quote characters

Some operating systems may need to have the quotes in cmd escaped. Less experienced users should remember that config command lines should be tested with filenames that include spaces, and if the cmd lines don't work with the filenames that include spaces then try escaping the quotes. e.g.

cmd = meld \"$LOCAL\" \"$REMOTE\"

In some cases more complex quote escaping may be needed. The 1st of the Windows path links below contains an example of triple-escaping each quote. It's a bore but sometimes necessary. e.g.

cmd = meld \\\"$LOCAL\\\" \\\"$REMOTE\\\"

Windows paths

Windows users will probably need extra configuration added to the Meld cmd lines. They may need to use the full path to meldc, which is designed to be called on Windows from the command line, or they may need or want to use a wrapper. They should read the StackOverflow pages linked below which are about setting the correct Meld cmd line for Windows. Since I am a Linux user I am unable to test the various Windows cmd lines and have no further information on the subject other than to recommend using my examples with the addition of a full path to Meld or meldc, or adding the Meld program folder to your path.

Ignoring trailing whitespace with Meld

Meld has a number of preferences that can be configured in the GUI.

In the preferences Text Filters tab there are several useful filters to ignore things like comments when performing a diff. Although there are filters to ignore All whitespace and Leading whitespace, there is no ignore Trailing whitespace filter (this has been suggested as an addition in the Meld mailing list but is not available in my version).

Ignoring trailing whitespace is often very useful, especially when collaborating, and can be manually added easily with a simple regular expression in the Meld preferences Text Filters tab.

# Use either of these regexes depending on how comprehensive you want it to be.
[ \t]*$
[ \t\r\f\v]*$

I hope this helps everyone.

Global npm install location on windows?

If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module

$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s

How to use refs in React with Typescript

If you're using React.FC, add the HTMLDivElement interface:

const myRef = React.useRef<HTMLDivElement>(null);

And use it like the following:

return <div ref={myRef} />;

How to change environment's font size?

As of now (March 2018) & version 1.21.0, you can go to Settings, search for 'zoom' and change "editor.mouseWheelZoom": false which is false by default to true. This will allow to zoom in/out on VS Code using control button and mouse - ctrl + scrollUp/scrollDown. For changing the fontSize of the overall working space/screen of VS Code, refer to Alegozalves's answer above.

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

Mockito - NullpointerException when stubbing Method

Corner case:
If you're using Scala and you try to create an any matcher on a value class, you'll get an unhelpful NPE.

So given case class ValueClass(value: Int) extends AnyVal, what you want to do is ValueClass(anyInt) instead of any[ValueClass]

when(mock.someMethod(ValueClass(anyInt))).thenAnswer {
   val v  = ValueClass(invocation.getArguments()(0).asInstanceOf[Int])

This other SO question is more specifically about that, but you'd miss it when you don't know the issue is with value classes.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Similar to @Piotr Lewandowski's answer, but within a forEach:

const config: MyConfig = { ... };

  .forEach((key: keyof MyConfig) => {
    if (config[key]) {
      // ...

Fork() function in C

I think every process you make start executing the line you create so something like this...

pid=fork() at line 6. fork function returns 2 values 
you have 2 pids, first pid=0 for child and pid>0 for parent 
so you can use if to separate


    sleep(int time) to see clearly
    <0 fail 
    =0 child
    >0 parent
int main(int argc, char** argv) {
    pid_t childpid1, childpid2;
    printf("pid = process identification\n");
    printf("ppid = parent process identification\n");
    childpid1 = fork();
    if (childpid1 == -1) {
        printf("Fork error !\n");
    if (childpid1 == 0) {
        printf("child[1] --> pid = %d and  ppid = %d\n",
                getpid(), getppid());
    } else {
        childpid2 = fork();
        if (childpid2 == 0) {
            printf("child[2] --> pid = %d and ppid = %d\n",
                    getpid(), getppid());
        } else {
            printf("parent --> pid = %d\n", getpid());
    return 0;

//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and  ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398

some uni stuff

Declaring static constants in ES6 classes?

I did this.

class Circle
        this.radius = radius;
    static get PI()
        return 3.14159;

The value of PI is protected from being changed since it is a value being returned from a function. You can access it via Circle.PI. Any attempt to assign to it is simply dropped on the floor in a manner similar to an attempt to assign to a string character via [].

How to to send mail using gmail in Laravel?

[email protected]

allow less secure apps to access your account in the Gmail security setting.

How do I define the name of image built with docker-compose

According to 3.9 version of Docker compose, you can use image: myapp:tag to specify name and tag.

version: "3.9"
      context: .
      dockerfile: Dockerfile
    image: webapp:tag


Why should Java 8's Optional not be used in arguments

One more approach, what you can do is

// get your optionals first
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();

// bind values to a function
Supplier<Integer> calculatedValueSupplier = () -> { // your logic here using both optional as state}

Once you have built a function(supplier in this case) you will be able to pass this around as any other variable and would be able to call it using


The idea here being whether you have got optional value or not will be internal detail of your function and will not be in parameter. Thinking functions when thinking about optional as parameter is actually very useful technique that I have found.

As to your question whether you should actually do it or not is based on your preference, but as others said it makes your API ugly to say the least.

Check if a file exists or not in Windows PowerShell?

You can use the Test-Path cmd-let. So something like...

if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
    Write-Host "$file doesn't exist in both locations."

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

For the multi-class case, everything you need can be found from the confusion matrix. For example, if your confusion matrix looks like this:

confusion matrix

Then what you're looking for, per class, can be found like this:


Using pandas/numpy, you can do this for all classes at once like so:

FP = confusion_matrix.sum(axis=0) - np.diag(confusion_matrix)  
FN = confusion_matrix.sum(axis=1) - np.diag(confusion_matrix)
TP = np.diag(confusion_matrix)
TN = confusion_matrix.values.sum() - (FP + FN + TP)

# Sensitivity, hit rate, recall, or true positive rate
# Specificity or true negative rate
# Precision or positive predictive value
# Negative predictive value
# Fall out or false positive rate
# False negative rate
# False discovery rate

# Overall accuracy

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

When do I use path params vs. query params in a RESTful API?

Segmentation is more hierarchal and "pretty" but can be limiting.

For example, if you have a url with three segments, each one passing different parameters to search for a car via make, model and color:

This is a very pretty url and more easily remembered by the end user, but now your kind of stuck with this structure. Say you want to make it so that in the search the user could search for ALL blue cars, or ALL Honda Civics? A query parameter solves this because it give a key value pair. So you could pass:

Now you have a way to reference the value via it's key - either "color" or "make" in your query code.

You could get around this by possibly using more segments to create a kind of key value structure like:

Hope that makes sense..

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.


mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

Can you force a React component to rerender without calling setState?

use hooks or HOC take your pick

Using hooks or the HOC (higher order component) pattern, you can have automatic updates when your stores change. This is a very light-weight approach without a framework.

useStore Hooks way to handle store updates

interface ISimpleStore {
  on: (ev: string, fn: () => void) => void;
  off: (ev: string, fn: () => void) => void;

export default function useStore<T extends ISimpleStore>(store: T) {
  const [storeState, setStoreState] = useState({store});
  useEffect(() => {
    const onChange = () => {
    store.on('change', onChange);
    return () => {'change', onChange);
  }, []);

withStores HOC handle store updates

export default function (...stores: SimpleStore[]) {
  return function (WrappedComponent: React.ComponentType<any>) {
    return class WithStore extends PureComponent<{}, {lastUpdated: number}> {
      constructor(props: React.ComponentProps<any>) {
        this.state = {
        this.stores = stores;

      private stores?: SimpleStore[];

      private onChange = () => {

      componentDidMount = () => {
        this.stores &&
          this.stores.forEach((store) => {
            // each store has a common change event to subscribe to
            store.on('change', this.onChange);

      componentWillUnmount = () => {
        this.stores &&
          this.stores.forEach((store) => {
  'change', this.onChange);

      render() {
        return (

SimpleStore class

import AsyncStorage from '@react-native-community/async-storage';
import ee, {Emitter} from 'event-emitter';

interface SimpleStoreArgs {
  key?: string;
  defaultState?: {[key: string]: any};

export default class SimpleStore {
  constructor({key, defaultState}: SimpleStoreArgs) {
    if (key) {
      this.key = key;
      // hydrate here if you want w/ localState or AsyncStorage
    if (defaultState) {
      this._state = {...defaultState, loaded: false};
    } else {
      this._state = {loaded: true};
  protected key: string = '';
  protected _state: {[key: string]: any} = {};
  protected eventEmitter: Emitter = ee({});
  public setState(newState: {[key: string]: any}) {
    this._state = {...this._state, ...newState};
    if (this.key) {
      // store on client w/ localState or AsyncStorage
  public get state() {
    return this._state;
  public on(ev: string, fn:() => void) {
    this.eventEmitter.on(ev, fn);
  public off(ev: string, fn:() => void) {, fn);
  public get loaded(): boolean {
    return !!this._state.loaded;

How to Use

In the case of hooks:

// use inside function like so
const someState = useStore(myStore);
someState.myProp = 'something';

In the case of HOC:

// inside your code get/set your store and stuff just updates
const val = myStore.myProp;
myOtherStore.myProp = 'something';
// return your wrapped component like so
export default withStores(myStore)(MyComponent);

MAKE SURE To export your stores as a singleton to get the benefit of global change like so:

class MyStore extends SimpleStore {
  public get someProp() {
    return this._state.someProp || '';
  public set someProp(value: string) {
    this.setState({...this._state, someProp: value});
// this is a singleton
const myStore = new MyStore();
export {myStore};

This approach is pretty simple and works for me. I also work in large teams and use Redux and MobX and find those to be good as well but just a lot of boilerplate. I just personally like my own approach because I always hated a lot of code for something that can be simple when you need it to be.

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

Check if returned value is not null and if so assign it, in one line, with one method call

dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();


if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();

How to loop and render elements in React.js without an array of objects to map?

I think this is the easiest way to loop in react js


Spring Boot REST service exception handling

For people that want to response according to http status code, you can use the ErrorController way:

public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());

    public ResponseEntity error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status.equals(HttpStatus.INTERNAL_SERVER_ERROR)){
            return ResponseEntity.status(status).body(ResponseBean.SERVER_ERROR);
        }else if (status.equals(HttpStatus.BAD_REQUEST)){
            return ResponseEntity.status(status).body(ResponseBean.BAD_REQUEST);
        return super.error(request);

The ResponseBean here is my custom pojo for response.

Use of PUT vs PATCH methods in REST API real life scenarios

Let me quote and comment more closely the RFC 7231 section 4.2.2, already cited in earlier comments :

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent.


Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response. For example, if a client sends a PUT request and the underlying connection is closed before any response is received, then the client can establish a new connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.

So, what should be "the same" after a repeated request of an idempotent method? Not the server state, nor the server response, but the intended effect. In particular, the method should be idempotent "from the point of view of the client". Now, I think that this point of view shows that the last example in Dan Lowe's answer, which I don't want to plagiarize here, indeed shows that a PATCH request can be non-idempotent (in a more natural way than the example in Jason Hoetger's answer).

Indeed, let's make the example slightly more precise by making explicit one possible intend for the first client. Let's say that this client goes through the list of users with the project to check their emails and zip codes. He starts with user 1, notices that the zip is right but the email is wrong. He decides to correct this with a PATCH request, which is fully legitimate, and sends only

PATCH /users/1
{"email": "[email protected]"}

since this is the only correction. Now, the request fails because of some network issue and is re-submitted automatically a couple of hours later. In the meanwhile, another client has (erroneously) modified the zip of user 1. Then, sending the same PATCH request a second time does not achieve the intended effect of the client, since we end up with an incorrect zip. Hence the method is not idempotent in the sense of the RFC.

If instead the client uses a PUT request to correct the email, sending to the server all properties of user 1 along with the email, his intended effect will be achieved even if the request has to be re-sent later and user 1 has been modified in the meanwhile --- since the second PUT request will overwrite all changes since the first request.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
        "platform": "iphone"
        "platform": "ipad"
        "platform": "android_phone"
        "platform": "android_tablet"

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;

public void setPlatforms(List platforms){
    this.platforms = platforms;

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;

SSL cert "err_cert_authority_invalid" on mobile chrome only

Just do the following for Version 44.0.2403.155 dev-m

Privacy -->Content settings -->Do not allow any site to run JavaScript

Problem Solved

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

How to include scripts located inside the node_modules folder?

As mentioned by jfriend00 you should not expose your server structure. You could copy your project dependency files to something like public/scripts. You can do this very easily with dep-linker like this:

var DepLinker = require('dep-linker');
// Done

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    return IPAddress
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

try this,

df.loc[df['eri_white']==1,'race_label'] = 'White'
df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
df['race_label'].fillna('Other', inplace=True)


     lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian  \
0      MOST    JEFF      E             0          0             0   
1    CRUISE     TOM      E             0          0             0   
2      DEPP  JOHNNY    NaN             0          0             0   
3     DICAP     LEO    NaN             0          0             0   
4    BRANDO  MARLON      E             0          0             0   
5     HANKS     TOM    NaN             0          0             0   
6    DENIRO  ROBERT      E             0          1             0   
7    PACINO      AL      E             0          0             0   
8  WILLIAMS   ROBIN      E             0          0             1   
9  EASTWOOD   CLINT      E             0          0             0   

   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label  
0             0             0          1       White         White  
1             1             0          0       White      Hispanic  
2             0             0          1     Unknown         White  
3             0             0          1     Unknown         White  
4             0             0          0       White         Other  
5             0             0          1     Unknown         White  
6             0             0          1       White   Two Or More  
7             0             0          1       White         White  
8             0             0          0       White  Haw/Pac Isl.  
9             0             0          1       White         White 

use .loc instead of apply.

it improves vectorization.

.loc works in simple manner, mask rows based on the condition, apply values to the freeze rows.

for more details visit, .loc docs

Performance metrics:

Accepted Answer:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

df = pd.concat([df]*1000)

%timeit df.apply(lambda row: label_race(row), axis=1)

1.15 s ± 46.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

My Proposed Answer:

def label_race(df):
    df.loc[df['eri_white']==1,'race_label'] = 'White'
    df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
    df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
    df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
    df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
    df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
    df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
    df['race_label'].fillna('Other', inplace=True)
df = pd.concat([df]*1000)

%timeit label_race(df)

24.7 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

How to modify WooCommerce cart, checkout pages (main theme portion)

I've found this works well as a conditional within page.php that includes the WooCommerce cart and checkout screens.

!is_page(array('cart', 'checkout'))

Wildcard string comparison in Javascript

I think you meant something like "*" (star) as a wildcard for example:

  • "a*b" => everything that starts with "a" and ends with "b"
  • "a*" => everything that starts with "a"
  • "*b" => everything that ends with "b"
  • "*a*" => everything that has an "a" in it
  • "*a*b*"=> everything that has an "a" in it, followed by anything, followed by a "b", followed by anything

or in your example: "bird*" => everything that starts with bird

I had a similar problem and wrote a function with RegExp:

//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
  return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
  // for this solution to work on any string, no matter what characters it has_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
  // "."  => Find a single character, except newline or line terminator_x000D_
  // ".*" => Matches any string that contains zero or more characters_x000D_
  rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
  // "^"  => Matches any string with the following at the beginning of it_x000D_
  // "$"  => Matches any string with that in front at the end of it_x000D_
  rule = "^" + rule + "$"_x000D_
  //Create a regular expression object for matching string_x000D_
  var regex = new RegExp(rule);_x000D_
  //Returns true if it finds a match, otherwise it returns false_x000D_
  return regex.test(str);_x000D_
    "1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
    "2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
    "3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
    "4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
    "5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
    "6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
    "7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_

If you want to read more about the used functions:

How to check cordova android version of a cordova/phonegap project?

For getting all the info about the cordova package use this command:

npm info cordova

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query


You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

How to check if input file is empty in jQuery

Here is the jQuery version of it:

if ($('#videoUploadFile').get(0).files.length === 0) {
    console.log("No files selected.");

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

osx could be using launchctl to launch mysql. Try this:

sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist

How to validate an e-mail address in swift?

This is the updated version for Swift 2.0 - 2.2

 var isEmail: Bool {
    do {
        let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
        return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
    } catch {
        return false

How to parse unix timestamp to time.Time

You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (

func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)


unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground:

Disable Proximity Sensor during call

I have been researching this for a while, tested and wrote apps.

If you have no option in Settings ? Phone ? Use proximity sensor, then the only choice, seem to be to disable or modify its settings in rooted devices.

Also consider, that if you plug the headset, the screen will remain on :D

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

How to set the action for a UIBarButtonItem in Swift

May this one help a little more

Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-

your Utility File

class GeneralUtility {

    class func customeNavigationBar(viewController: UIViewController,title:String){
        let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));  
      viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];

Then make a SuperviewController class and define the same function on it.

class SuperViewController: UIViewController {

    override func viewDidLoad() {
            // Do any additional setup after loading the view.
    @objc func buttonClicked(sender: UIBarButtonItem) {


and In our base viewController(which inherit your SuperviewController class) override the same function

import UIKit

class HomeViewController: SuperViewController {

    override func viewDidLoad() {

        // Do any additional setup after loading the view.

    override func viewWillAppear(_ animated: Bool) {
        GeneralUtility.customeNavigationBar(viewController: self,title:"Event");

    @objc override func buttonClicked(sender: UIBarButtonItem) {
      print("button clicked")    

Now just inherit the SuperViewController in whichever class you want this barbutton.

Thanks for the read

Swift Beta performance: sorting arrays

I decided to take a look at this for fun, and here are the timings that I get:

Swift 4.0.2           :   0.83s (0.74s with `-Ounchecked`)
C++ (Apple LLVM 8.0.0):   0.74s


// Swift 4.0 code
import Foundation

func doTest() -> Void {
    let arraySize = 10000000
    var randomNumbers = [UInt32]()

    for _ in 0..<arraySize {

    let start = Date()
    let end = Date()

    print("Elapsed time: \(end.timeIntervalSince(start))")



Swift 1.1

xcrun swiftc --version
Swift version 1.1 (swift-600.0.54.20)
Target: x86_64-apple-darwin14.0.0

xcrun swiftc -O SwiftSort.swift
Elapsed time: 1.02204304933548

Swift 1.2

xcrun swiftc --version
Apple Swift version 1.2 (swiftlang-602.0.49.6 clang-602.0.49)
Target: x86_64-apple-darwin14.3.0

xcrun -sdk macosx swiftc -O SwiftSort.swift
Elapsed time: 0.738763988018036

Swift 2.0

xcrun swiftc --version
Apple Swift version 2.0 (swiftlang-700.0.59 clang-700.0.72)
Target: x86_64-apple-darwin15.0.0

xcrun -sdk macosx swiftc -O SwiftSort.swift
Elapsed time: 0.767306983470917

It seems to be the same performance if I compile with -Ounchecked.

Swift 3.0

xcrun swiftc --version
Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9

xcrun -sdk macosx swiftc -O SwiftSort.swift
Elapsed time: 0.939633965492249

xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
Elapsed time: 0.866258025169373

There seems to have been a performance regression from Swift 2.0 to Swift 3.0, and I'm also seeing a difference between -O and -Ounchecked for the first time.

Swift 4.0

xcrun swiftc --version
Apple Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38)
Target: x86_64-apple-macosx10.9

xcrun -sdk macosx swiftc -O SwiftSort.swift
Elapsed time: 0.834299981594086

xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
Elapsed time: 0.742045998573303

Swift 4 improves the performance again, while maintaining a gap between -O and -Ounchecked. -O -whole-module-optimization did not appear to make a difference.


#include <chrono>
#include <iostream>
#include <vector>
#include <cstdint>
#include <stdlib.h>

using namespace std;
using namespace std::chrono;

int main(int argc, const char * argv[]) {
    const auto arraySize = 10000000;
    vector<uint32_t> randomNumbers;

    for (int i = 0; i < arraySize; ++i) {

    const auto start = high_resolution_clock::now();
    sort(begin(randomNumbers), end(randomNumbers));
    const auto end = high_resolution_clock::now();

    cout << randomNumbers[0] << "\n";
    cout << "Elapsed time: " << duration_cast<duration<double>>(end - start).count() << "\n";

    return 0;


Apple Clang 6.0

clang++ --version
Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
Elapsed time: 0.688969

Apple Clang 6.1.0

clang++ --version
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
Elapsed time: 0.670652

Apple Clang 7.0.0

clang++ --version
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin15.0.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
Elapsed time: 0.690152

Apple Clang 8.0.0

clang++ --version
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin15.6.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
Elapsed time: 0.68253

Apple Clang 9.0.0

clang++ --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
Elapsed time: 0.736784


As of the time of this writing, Swift's sort is fast, but not yet as fast as C++'s sort when compiled with -O, with the above compilers & libraries. With -Ounchecked, it appears to be as fast as C++ in Swift 4.0.2 and Apple LLVM 9.0.0.

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "";

private interface API {
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);

public void onCreate(Bundle savedInstanceState) {

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.

The URL called will be

What does an exclamation mark mean in the Swift language?

In Short (!): After you have declare a variable and that you are certain the variable is holding a value.

let assumedString: String! = "Some message..."
let implicitString: String = assumedString

else you would have to do this on every after passing value...

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark

Mipmap drawables for icons

The understanding I have about mipmap is more or less like this:

When an image needs to be drawn, given we have different screen sizes are resolutions, some scaling will have to take part.

If you have an image that is ok for a low end cell phone, when you scale it to the size of a 10" tablet you have to "invent" pixels that don't actually exist. This is done with some interpolation algorithm. The more amount of pixels that have to be invented, the longer the process takes and quality starts to fail. Best quality is obtained with more complex algorithms that take longer (average of surrounding pixles vs copy the nearest pixel for example).

To reduce the number of pixels that have to be invented, with mipmap you provide different sizes/rsolutions of the same image, and the system will choose the nearest image to the resolution that has to be rendered and do the scaling from there. This should reduce the number of invented pixels saving resources to be used in calculating these pixels to provide a good quality image.

I read about this in an article explaining a performance problem in libgdx when scaling images:

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

For those who need the input file to open directly the camera, you just have to declare capture parameter to the input file, like this :

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

How to remove/ignore :hover css style on touch devices

According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with @media not all and (hover: none). It looks weird but it works.

I made a Sass mixin out of this for easier use:

@mixin hover-supported {
    @media not all and (hover: none) {
        &:hover {

Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:

@media (hover: hover) {
    /* Device that can hover (desktops) */
@media (hover: none) {
    /* Device that can not hover with ease */
@media (pointer: coarse) {
    /* Device with limited pointing accuracy (touch) */
@media (pointer: fine) {
    /* Device with accurate pointing (desktop, stylus-based) */
@media (pointer: none) {
    /* Device with no pointing */

Example for specific targets:

@media (hover: none) and (pointer: coarse) {
    /* Smartphones and touchscreens */

@media (hover: hover) and (pointer: fine) {
    /* Desktops with mouse */

I love mixins, this is how I use my hover mixin to only target devices that supports it:

@mixin on-hover {
    @media (hover: hover) and (pointer: fine) {
        &:hover {

button {
    @include on-hover {
        color: blue;

Why can't I use Docker CMD multiple times to run multiple services?

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./ or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:


sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)


tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:


Then paste it at <path to conf>, tweak as needed and you're good to go.

Asking the user for input until they give a valid response

Persistent user input using recursive function:


def askName():
    return input("Write your name: ").strip() or askName()

name = askName()


def askAge():
    try: return int(input("Enter your age: "))
    except ValueError: return askAge()

age = askAge()

and finally, the question requirement:

def askAge():
    try: return int(input("Enter your age: "))
    except ValueError: return askAge()

age = askAge()

responseAge = [
    "You are able to vote in the United States!",
    "You are not able to vote in the United States.",
][int(age < 18)]


python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

Disable developer mode extensions pop up in Chrome

I found something that will load user-packed extensions and works beautifully:

You'll still have to pack it in details for the problem extension, but after that you can turn off developer mode and load the packed CRX through this. You don't have to deal with signing it or anything.

Note: I'm not from their team, I've just been looking for an elegant solution for this for years.

3-dimensional array in numpy

You are right, you are creating a matrix with 2 rows, 3 columns and 4 depth. Numpy prints matrixes different to Matlab:


>>> import numpy as np
>>> np.zeros((2,3,2))
 array([[[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]],

   [[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]]])


>> zeros(2, 3, 2)
 ans(:,:,1) =
     0     0     0
     0     0     0
 ans(:,:,2) =
     0     0     0
     0     0     0

However you are calculating the same matrix. Take a look to Numpy for Matlab users, it will guide you converting Matlab code to Numpy.

For example if you are using OpenCV, you can build an image using numpy taking into account that OpenCV uses BGR representation:

import cv2
import numpy as np

a = np.zeros((100, 100,3))
a[:,:,0] = 255

b = np.zeros((100, 100,3))
b[:,:,1] = 255

c = np.zeros((100, 200,3)) 
c[:,:,2] = 255

img = np.vstack((c, np.hstack((a, b))))

cv2.imshow('image', img)

enter image description here

If you take a look to matrix c you will see it is a 100x200x3 matrix which is exactly what it is shown in the image (in red as we have set the R coordinate to 255 and the other two remain at 0).

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

Example 1:

This is how the and operator works.

x and y => if x is false, then x, else y

So in other words, since mylist1 is not False, the result of the expression is mylist2. (Only empty lists evaluate to False.)

Example 2:

The & operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:

>>> 3 & 1

It's easier to see what's happening using a binary literal (same numbers as above):

>>> 0b0011 & 0b0001

Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.

So, given a couple statements about my car

  1. My car is red
  2. My car has wheels

The logical "and" of these two statements is:

(is my car red?) and (does car have wheels?) => logical true of false value

Both of which are true, for my car at least. So the value of the statement as a whole is logically true.

The bitwise "and" of these two statements is a little more nebulous:

(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number

If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that & is interchangeable with and, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError.

Example 3 and 4:

Numpy implements arithmetic operations for arrays:

Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.

But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.

So to answer your and vs & question: Use and.

The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.

The logical operations (and, or, not), however, are used all the time.

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

Sequelize, convert entity to plain object

If I get you right, you want to add the sensors collection to the node. If you have a mapping between both models you can either use the include functionality explained here or the values getter defined on every instance. You can find the docs for that here.

The latter can be used like this:

  where: {
    nodeid: node.nodeid
}).success(function (sensors) {
  var nodedata = node.values;

  nodedata.sensors ={ return sensor.values });
  // or
  nodedata.sensors ={ return sensor.toJSON() });


There is chance that nodedata.sensors = sensors could work as well.

This IP, site or mobile application is not authorized to use this API key

You create an key with out referer dont enter the referer address

Does JSON syntax allow duplicate keys in an object?

Posting and answer because there is a lot of outdated ideas and confusion about the standards. As of December 2017, there are two competing standards:

RFC 8259 -

ECMA-404 - suggests ECMA-404 is the standard, but this site does not appear to be an authority. While I think it's fair to consider ECMA the authority, what's important here is, the only difference between the standards (regarding unique keys) is that RFC 8259 says the keys should be unique, and the ECMA-404 says they are not required to be unique.


"The names within an object SHOULD be unique."

The word "should" in all caps like that, has a meaning within the RFC world, that is specifically defined in another standard (BCP 14, RFC 2119 - as,

  1. SHOULD This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.


"The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs."

So, no matter how you slice it, it's syntactically valid JSON.

The reason given for the unique key recommendation in RFC 8259 is,

An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

In other words, from the RFC 8259 viewpoint, it's valid but your parser may barf and there's no promise as to which, if any, value will be paired with that key. From the ECMA-404 viewpoint (which I'd personally take as the authority), it's valid, period. To me this means that any parser that refuses to parse it is broken. It should at least parse according to both of these standards. But how it gets turned into your native object of choice is, in any case, unique keys or not, completely dependent on the environment and the situation, and none of that is in the standard to begin with.

How to deploy correctly when using Composer's develop / production switch?

Actually, I would highly recommend AGAINST installing dependencies on the production server.

My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.


  • on shared hosting, you might not be able to get to a command line
  • even if you did, PHP might be restricted there in terms of commands, memory or network access
  • repository CLI tools (Git, Svn) are likely to not be installed, which would fail if your lock file has recorded a dependency to checkout a certain commit instead of downloading that commit as ZIP (you used --prefer-source, or Composer had no other way to get that version)
  • if your production machine is more like a small test server (think Amazon EC2 micro instance) there is probably not even enough memory installed to execute composer install
  • while composer tries to no break things, how do you feel about ending with a partially broken production website because some random dependency could not be loaded during Composers install phase

Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.

What's the correct way to deploy this without installing the -dev dependencies?

The command to use is

composer install --no-dev

This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.

The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.

If you don't mind deploying development software components on a production server, running composer install would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.

Why not inherit from List<T>?

Wow, your post has an entire slew of questions and points. Most of the reasoning you get from Microsoft is exactly on point. Let's start with everything about List<T>

  • List<T> is highly optimized. Its main usage is to be used as a private member of an object.
  • Microsoft did not seal it because sometimes you might want to create a class that has a friendlier name: class MyList<T, TX> : List<CustomObject<T, Something<TX>> { ... }. Now it's as easy as doing var list = new MyList<int, string>();.
  • CA1002: Do not expose generic lists: Basically, even if you plan to use this app as the sole developer, it's worthwhile to develop with good coding practices, so they become instilled into you and second nature. You are still allowed to expose the list as an IList<T> if you need any consumer to have an indexed list. This lets you change the implementation within a class later on.
  • Microsoft made Collection<T> very generic because it is a generic concept... the name says it all; it is just a collection. There are more precise versions such as SortedCollection<T>, ObservableCollection<T>, ReadOnlyCollection<T>, etc. each of which implement IList<T> but not List<T>.
  • Collection<T> allows for members (i.e. Add, Remove, etc.) to be overridden because they are virtual. List<T> does not.
  • The last part of your question is spot on. A Football team is more than just a list of players, so it should be a class that contains that list of players. Think Composition vs Inheritance. A Football team has a list of players (a roster), it isn't a list of players.

If I were writing this code, the class would probably look something like so:

public class FootballTeam
    // Football team rosters are generally 53 total players.
    private readonly List<T> _roster = new List<T>(53);

    public IList<T> Roster
        get { return _roster; }

    // Yes. I used LINQ here. This is so I don't have to worry about
    // _roster.Length vs _roster.Count vs anything else.
    public int PlayerCount
        get { return _roster.Count(); }

    // Any additional members you want to expose/wrap.

Node.js Generate html

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

There are a few methods you can choose from to do what you want.

Method 1: Serving the file directly via HTTP

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

There are plenty frameworks out there for that :

The most basic way you could do what you want is this :

var http = require('http');

http.createServer(function (req, res) {
  var html = buildHtml(req);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': html.length,
    'Expires': new Date().toUTCString()

function buildHtml(req) {
  var header = '';
  var body = '';

  // concatenate header string
  // concatenate body string

  return '<!DOCTYPE html>'
       + '<html><head>' + header + '</head><body>' + body + '</body></html>';

And access this HTML with http://localhost:8080 from your browser.

(Edit: you could also serve them with a small HTTP server.)

Method 2: Generating the file only

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');

var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);

stream.once('open', function(fd) {
  var html = buildHtml();


Note: The buildHtml function is exactly the same as in Method 1.

Method 3: Dumping the file directly into stdout

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();


Note: The buildHtml function is exactly the same as in Method 1 (again)

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file


Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');

var html = htmlBuilder(options);

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

Extra reading, learn about npm. Hope this helps.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I run across this and at the beginning I found it really confusing to be honest and I think this confusion comes from using the word "CMD" because in fact what goes there acts as argument. So after digging a little bit I understood how it works. Basically:

ENTRYPOINT --> what you specify here would be the command to be executed when you container starts. If you omit this definition docker will use /bin/sh -c bash to run your container.

CMD --> these are the arguments appended to the ENTRYPOINT unless the user specifies some custom argument, i.e: docker run ubuntu <custom_cmd> in this case instead of appending what's specified on the image in the CMD section, docker will run ENTRYPOINT <custom_cmd>. In case ENTRYPOINT has not been specified, what goes here will be passed to /bin/sh -c acting in fact as the command to be executed when starting the container.

As everything it's better to explain what's going on by examples. So let's say I create a simple docker image by using the following specification Dockerfile:

From ubuntu
ENTRYPOINT ["sleep"]

Then I build it by running the following:

docker build . -t testimg

This will create a container that everytime you run it sleeps. So If I run it as following:

docker run testimg

I'll get the following:

sleep: missing operand
Try 'sleep --help' for more information.

This happens because the entry point is the "sleep" command which needs an argument. So to fix this I'll just provide the amount to sleep:

docker run testimg 5

This will run correctly and as consequence the container will run, sleeps 5 seconds and exits. As we can see in this example docker just appended what goes after the image name to the entry point binary docker run testimg <my_cmd>. What happens if we want to pass a default value (default argument) to the entry point? in this case we just need to specify it in the CMD section, for example:

From ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]

In this case if the user doesn't pass any argument the container will use the default value (10) and pass it to entry point sleep.

Now let's use just CMD and omit ENTRYPOINT definition:

FROM ubuntu
CMD ["sleep", "5"]

If we rebuild and run this image it will basically sleeps for 5 seconds.

So in summary, you can use ENTRYPOINT in order to make your container acts as an executable. You can use CMD to provide default arguments to your entry point or to run a custom command when starting your container that can be overridden from outside by user.

Converting milliseconds to minutes and seconds with Javascript

Event though ,oment.js does not provide such functionality, if you come here and you are already using moment.js, try this:

function formatDuration(ms) {
  var duration = moment.duration(ms);
  return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");

You will get something like x:xx:xx.

In the case you may want to skip the hour, when the duration is only < 60minutes.

function formatDuration(ms) {
  var duration = moment.duration(ms);
  if (duration.asHours() > 1) {
    return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
  } else {
    return moment.utc(duration.asMilliseconds()).format("mm:ss");

This workaround in moment was introduced in this Issue.

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src=""></script>
<script type="text/javascript" src="./javascript.js"></script>

JSON to pandas DataFrame

billmanH's solution helped me but didn't work until i switched from:

n = data.loc[row,'json_column']


n = data.iloc[[row]]['json_column']

here's the rest of it, converting to a dictionary is helpful for working with json data.

import json

for row in range(len(data)):
    n = data.iloc[[row]]['json_column'].item()
    jsonDict = json.loads(n)
    if ('mykey' in jsonDict):

How does Java resolve a relative path in new File()?

I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.

Simply edit "" and change

url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");


url = new URL("file:./schema/current/AXLAPI.wsdl");

or where ever you want to store it.

You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:[url]=[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

What are best practices for REST nested resources?

Rails provides a solution to this: shallow nesting.

I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.

Are PostgreSQL column names case-sensitive?

if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:

    pg_catalog.pg_stat_all_tables psat,
    pg_catalog.pg_attribute pa
    psat.relid = pa.attrelid

change schema name:


change table names:


change column names:


Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

Exists Angularjs code/naming conventions?

For structuring an app, this is one of the best guides that I've found:

Note that the structure recommended by Google is different than what you'll find in a lot of seed projects, but for large apps it's a lot saner.

Google also has a style guide that makes sense to use only if you also use Closure.

...this answer is incomplete, but I hope that the limited information above will be helpful to someone.

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual command for this to succeed (including them actually caused it to fail)

Controlling execution order of unit tests in Visual Studio

I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.

I write about one of your assumptions:

as there is no way to tear down the static class.

Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way is not true.

If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".

Think and check the AppDomain thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.

You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.

This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.

Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.

Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef or etc. Talking cross-domain is almost like IPC.

However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:

void testmethod()
    TestAppDomainHelper.Run( () =>
        // your test code

or even

void testmethod()
    // your test code

if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

What about casting to Number in Javascript using the Unary (+) Operator

lat: 12.23
lat: +12.23

Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which

python dictionary sorting in descending order based on values

Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

In different terms, your d and your e would be exactly equivalent dictionaries.

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d, but didn't. And d_descending has the order you want for your e.

If you don't really need to use e as a dictionary, but you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");
    var arrSelected = [];

canvas.toDataURL() SecurityError

Try the code below ...

<img crossOrigin="anonymous"
     fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
                bungalow,high end luxury properties,landed properties,gated guarded house.png" 

Dilemma: when to use Fragments vs Activities:

Almost always use fragments. If you know that the app you are building will remain very small, the extra effort of using fragments may not be worth it, so they can be left out. For larger apps, the complexity introduced is offset by the flexibility fragments provide, making it easier to justify having them in the project. Some people are very opposed to the additional complexity involved with fragments and their lifecycles, so they never use them in their projects. An issue with this approach is that there are several APIs in Android that rely on fragments, such as ViewPager and the Jetpack Navigation library. If you need to use these options in your app, then you must use fragments to get their benefits.

Excerpt From: Kristin Marsicano. “Android Programming: The Big Nerd Ranch Guide, 4th Edition.” Apple Books.

Could not resolve placeholder in string value

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

ipynb import another ipynb file

The issue is that a notebooks is not a plain python file. The steps to import the .ipynb file are outlined in the following: Importing notebook

I am pasting the code, so if you need can just do a quick copy and paste. Notice that at the end I have the import primes statement. You'll have to change that of course. The name of my file is primes.ipynb. From this point on you can use the content inside that file as you would do regularly.

Wish there was a simpler method, but this is straight from the docs.
Note: I am using jupyter not ipython.

import io, os, sys, types
from IPython import get_ipython
from nbformat import current
from IPython.core.interactiveshell import InteractiveShell

def find_notebook(fullname, path=None):
    """find a notebook, given its fully qualified name and an optional path

    This turns "" into "foo/bar.ipynb"
    and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
    does not exist.
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        # let import Notebook_Name find "Notebook Name.ipynb"
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path

class NotebookLoader(object):
    """Module Loader for Jupyter Notebooks"""
    def __init__(self, path=None): = InteractiveShell.instance()
        self.path = path

    def load_module(self, fullname):
        """import a notebook as a module"""
        path = find_notebook(fullname, self.path)

        print ("importing Jupyter notebook from %s" % path)

        # load the notebook object
        with, 'r', encoding='utf-8') as f:
            nb =, 'json')

        # create the module and add it to sys.modules
        # if name in sys.modules:
        #    return sys.modules[name]
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = = mod.__dict__

        for cell in nb.worksheets[0].cells:
            if cell.cell_type == 'code' and cell.language == 'python':
                # transform the input to executable Python
                code =
                # run the code in themodule
                exec(code, mod.__dict__)
   = save_user_ns
        return mod

class NotebookFinder(object):
    """Module finder that locates Jupyter Notebooks"""
    def __init__(self):
        self.loaders = {}

    def find_module(self, fullname, path=None):
        nb_path = find_notebook(fullname, path)
        if not nb_path:

        key = path
        if path:
            # lists aren't hashable
            key = os.path.sep.join(path)

        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]


import primes

How can I use onItemSelected in Android?

For Kotlin and bindings the code is:

binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:


I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
"permissions": [


<!DOCTYPE html>
    <button id="test">TEST!</button>
    <script src="test.js"></script>


document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        return document.body.innerHTML;

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String


trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                     "lat": 50.3293284,
                     "lng": 6.9389634
               ]//'inserted Array containing the list of object'

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 


static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);

ng-repeat: access key and value for each object in array of objects

In fact, your data is not well design. You'd better use something like :

$scope.steps = [
    {stepName: "companyName", isComplete: true},
    {stepName: "businessType", isComplete: true},
    {stepName: "physicalAddress", isComplete: true}

Then it is easy to do what you want :

<div ng-repeat="step in steps">
 Step {{step.stepName}} status : {{step.isComplet}}


Entity framework self referencing loop detected

Well the correct answer for the default Json formater based on is to set ReferenceLoopHandling to Ignore.

Just add this to the Application_Start in Global.asax:

HttpConfiguration config = GlobalConfiguration.Configuration;

            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

This is the correct way. It will ignore the reference pointing back to the object.

Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.

Using the JsonIgnore attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.

Converting characters to integers in Java


The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

bootstrap jquery event won't fire

This happens when code might been executed before and it's not showing up so you can add timeout() for it tp fire.

$(document).on('', function (event) {

Best practice multi language website

I've been asking myself related questions over and over again, then got lost in formal languages... but just to help you out a little I'd like to share some findings:

I recommend to give a look at advanced CMS

Typo3 for PHP (I know there is a lot of stuff but thats the one I think is most mature)

Plone in Python

If you find out that the web in 2013 should work different then, start from scratch. That would mean to put together a team of highly skilled/experienced people to build a new CMS. May be you'd like to give a look at polymer for that purpose.

If it comes to coding and multilingual websites / native language support, I think every programmer should have a clue about unicode. If you don't know unicode you'll most certainly mess up your data. Do not go with the thousands of ISO codes. They'll only save you some memory. But you can do literally everything with UTF-8 even store chinese chars. But for that you'd need to store either 2 or 4 byte chars that makes it basically a utf-16 or utf-32.

If it's about URL encoding, again there you shouldn't mix encodings and be aware that at least for the domainname there are rules defined by different lobbies that provide applications like a browser. e.g. a Domain could be very similar like:

? or samesamebutdifferent ;)

Of course you need the filesystem to work with all encodings. Another plus for unicode using utf-8 filesystem.

If its about translations, think about the structure of documents. e.g. a book or an article. You have the docbook specifications to understand about those structures. But in HTML its just about content blocks. So you'd like to have a translation on that level, also on webpage level or domain level. So if a block doesn't exist its just not there, if a webpage doesn't exist you'll get redirected to the upper navigation level. If a domain should be completely different in navigation structure, then.. its a complete different structure to manage. This can already be done with Typo3.

If its about frameworks, the most mature ones I know, to do the general stuff like MVC(buzzword I really hate it! Like "performance" If you want to sell something, use the word performance and featurerich and you sell... what the hell) is Zend. It has proven to be a good thing to bring standards to php chaos coders. But, typo3 also has a Framework besides the CMS. Recently it has been redeveloped and is called flow3 now. The frameworks of course cover database abstraction, templating and concepts for caching, but have individual strengths.

If its about caching... that can be awefully complicated / multilayered. In PHP you'll think about accellerator, opcode, but also html, httpd, mysql, xml, css, js ... any kinds of caches. Of course some parts should be cached and dynamic parts like blog answers shouldn't. Some should be requested over AJAX with generated urls. JSON, hashbangs etc.

Then, you'd like to have any little component on your website to be accessed or managed only by certain users, so conceptually that plays a big role.

Also you'd like to make statistics, maybe have distributed system / a facebook of facebooks etc. any software to be built on top of your over the top cms ... so you need different type of databases inmemory, bigdata, xml, whatsoever.

well, I think thats enough for now. If you haven't heard of either typo3 / plone or mentioned frameworks, you have enough to study. On that path you'll find a lot of solutions for questions you haven't asked yet.

If then you think, lets make a new CMS because its 2013 and php is about to die anyway, then you r welcome to join any other group of developers hopefully not getting lost.

Good luck!

And btw. how about people will not having any websites anymore in the future? and we'll all be on google+? I hope developers become a little more creative and do something usefull(to not be assimilated by the borgle)

//// Edit /// Just a little thought for your existing application:

If you have a php mysql CMS and you wanted to embed multilang support. you could either use your table with an aditional column for any language or insert the translation with an object id and a language id in the same table or create an identical table for any language and insert objects there, then make a select union if you want to have them all displayed. For the database use utf8 general ci and of course in the front/backend use utf8 text/encoding. I have used url path segments for urls in the way you already explaned like you can map the lang ID to your content table. anyway you need to have a map of parameters for your urls so you'd like to define a parameter to be mapped from a pathsegment in your URL that would be e.g.

lookup configuration

pageid| url

1 | /about/employees/../..

1 | /../about/employees../../

map parameters to url pathsegment ""

$parameterlist[lang] = array(0=>"nl",1=>"en"); // default nl if 0
$parameterlist[branch] = array(1=>"IT",2=>"DESIGN"); // default nl if 0
$parameterlist[employertype] = array(1=>"admin",1=>"engineer"); //could be a sql result 

$someparameterlist[] = array("branch"=>$someid);
$someparameterlist[] = array("employertype"=>$someid);
function getURL($someparameterlist){ 
// todo foreach someparameter lookup pathsegment 
return path;

per say, thats been covered already in upper post.

And to not forget, you'd need to "rewrite" the url to your generating php file that would in most cases be index.php

How to change icon on Google map marker

we can change the icon of markers, i did it on right click event. Lets see if it works for you...

// Create a Marker
var marker = new google.maps.Marker({
    position: location,
    map: map,
    title:'Sample Tool Tip'

// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
        marker.setIcon('blank.png'); // set image path here...

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.

In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also:

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.


Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

How do I create a new user in a SQL Azure database?

You can simply create a contained user in SQL DB V12.

Create user containeduser with password = 'Password'

Contained user login is more efficient than login to the database using the login created by master. You can find more details @

Conda: Installing / upgrading directly from github

conda doesn't support this directly because it installs from binaries, whereas git install would be from source. conda build does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine, or alternately, use develop against a git clone.

Compare two different files line by line in python

If you are specifically looking for getting the difference between two files, then this might help:

with open('first_file', 'r') as file1:
    with open('second_file', 'r') as file2:
        difference = set(file1).difference(file2)


with open('diff.txt', 'w') as file_out:
    for line in difference:

addClass and removeClass in jQuery - not removing class

I would recomend to cache the jQuery objects you use more than once. For Instance:

    $(document).on("click", ".clickable", function () {

would be:

    var doc = $(document);
    doc.on('click', '.clickable', function(){
       var currentClickedObject = $(this);

its actually more code, BUT it is muuuuuuch faster because you dont have to "walk" through the whole jQuery library in order to get the $(this) object.

How to set HTML5 required attribute in Javascript?

Short version

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

Long Version

Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object = value;    //bad! Overwrites the HtmlAttribute object
value =;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

You must go through element.getAttribute and element.setAttribute:

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

This is because the attribute actually contains a special HtmlAttribute object:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute;              //returns HtmlAttribute object, not the value of the attribute

By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

Conceptually the correct idea (expressed in a typed language), is:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

This is why:

  • getAttribute(name)
  • setAttribute(name, value)

exist. They do the work on assigning the value to the HtmlAttribute object inside.

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
element.required = false;

What you don't want to do is mistakenly use the .attributes collection:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

Testing Cases

This led to testing around the use of a required attribute, comparing the values returned through the attribute, and the reflected property


with results:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

Trying to access the .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

This explains why you should never talk to the .attributes collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.

How to set required?

What's the correct way to set required on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

Strictly speaking, any other value will "set" the attribute. But the definition of Boolean attributes dictate that it should only be set to the empty string "" to indicate true. The following methods all work to set the required Boolean attribute,

but do not use them:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

We already learned that trying to set the attribute directly is wrong:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

How to clear required?

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

With the invalid ways:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

When using the reflected .required property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

How to check for required?

Check for the presence of the attribute through the .hasAttribute("required") method:

if (edName.hasAttribute("required"))

You can also check it through the Boolean reflected .required property:

if (edName.required)

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

Trying to load local JSON file to show data in a html page using JQuery

I have Used Following Methods But non of them worked:

   // 2 Method Failed

            '' +
            function (response) {
                console.log("> ", response);
// 3 Method Failed

    var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
  console.log( "success" );
  .done(function() {
    console.log( "second success" );
  .fail(function() {
    console.log( "error" );
  .always(function() {
    console.log( "complete" );

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  console.log( "second complete" );

// 4 Method Failed

   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

// 5 Method Failed

   url: '',
   headers: {  'Access-Control-Allow-Origin': 'htt://site allowed to access' },
   dataType: 'jsonp',
   /* etc */
   success: function(jsondata){


What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:

// Worked After local Web Server

        $(document).ready(function () {
            $.getJSON('./json/movies-coming-soon.json', function (data) {
              var movie_name = '';
              var movie_year = '';
                    movie_name += item.title + "  " + item.year + "<br> <br>"





Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.

Arduino error: does not name a type?

My code was out of void setup() or void loop() in Arduino.

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    success:function(data){ f(data,d);  }


Just create the database using createdb CLI tool:

createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

I found this implementation very easy to use. Also has a generous BSD-style license:


I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:

var sha256 = new jsSHA('SHA-256', 'TEXT');
var hash = sha256.getHash("HEX");

Github "Updates were rejected because the remote contains work that you do not have locally."

The issue is because the local is not up-to-date with the master branch that is why we are supposed to pull the code before pushing it to the git

git add .
git commit -m 'Comments to be added'
git pull origin master
git push origin master

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property

JavaScript string encryption and decryption?

crypt.subtle AES-GCM, self-contained, tested:

async function aesGcmEncrypt(plaintext, password)

async function aesGcmDecrypt(ciphertext, password)

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:


Using onBackPressed() in Android Fragments

You can try to override onCreateAnimation, parameter and catch enter==false. This will fire before every back press.

public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {            
            //leaving fragment
            Log.d(TAG,"leaving fragment");
        return super.onCreateAnimation(transit, enter, nextAnim);

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){

Constructors in Go

In Go, a constructor can be implemented using a function that returns a pointer to a modified structure.

type Colors struct {
    R   byte
    G   byte
    B   byte

// Constructor
func NewColors (r, g, b byte) *Colors {
    return &Color{R:r, G:g, B:b}

For weak dependencies and better abstraction, the constructor does not return a pointer to a structure, but an interface that this structure implements.

type Painter interface {
    paintMethod1() byte
    paintMethod2(byte) byte

type Colors struct {
    R byte
    G byte
    B byte

// Constructor return intreface
func NewColors(r, g, b byte) Painter {
    return &Color{R: r, G: g, B: b}

func (c *Colors) paintMethod1() byte {
    return c.R

func (c *Colors) paintMethod2(b byte) byte {
    return c.B = b

Data truncated for column?

However I get an error which doesn't make sense seeing as the column's data type was properly modified?

| Level | Code | Msg | Warn | 12 | Data truncated for column 'incoming_Cid' at row 1

You can often get this message when you are doing something like the following:

REPLACE INTO table2 (SELECT * FROM table1);

Resulted in our case in the following error:

SQL Exception: Data truncated for column 'level' at row 1

The problem turned out to be column misalignment that resulted in a tinyint trying to be stored in a datetime field or vice versa.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

In pom.xml file we need to add


SQL Server : Columns to Rows

Just because I did not see it mentioned.

If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.


Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
Insert Into @YourTable Values 

Select A.[ID]
      ,Item  = B.[Key]
      ,Value = B.[Value]
 From  @YourTable A
 Cross Apply ( Select * 
                From  OpenJson((Select A.* For JSON Path,Without_Array_Wrapper )) 
                Where [Key] not in ('ID','Other','Columns','ToExclude')
             ) B


ID  Item    Value
1   Col1    A
1   Col2    B
2   Col1    R
2   Col2    C
3   Col1    X
3   Col2    D

Making an iframe responsive

I am search more about this topic and finally get a nice answer. You can try like this:

.wrapper {_x000D_
width: 50%;_x000D_
.container {_x000D_
height: 0;_x000D_
width: 100%;_x000D_
padding-bottom: 50%;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
.container iframe {_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: absolute;_x000D_
<div class="wrapper">_x000D_
  <div class="container">_x000D_
    <iframe src="there is path of your iframe"></iframe>_x000D_

How do I commit case-sensitive only filename changes in Git?

This is what I did on OS X:

git mv File file.tmp
git mv file.tmp file

Two steps because otherwise I got a “file exists” error. Perhaps it can be done in one step by adding --cached or such.

How to make String.Contains case insensitive?

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);

Make anchor link go some pixels above where it's linked to

If you use explicit anchor names such as,

<a name="sectionLink"></a>

then in css you can simply set

A[name] {

This will work as long as your HREF anchor tags don't also specify a NAME attribute

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

How can I select rows with most recent timestamp for each key value?

I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.

I have a table of sensor data (1 minute data from about 30 sensors)


and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:


The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:

SELECT idSensor,Description,tvLastUpdate,tvLastValue 
FROM Sensors

I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.

Differences between hard real-time, soft real-time, and firm real-time?

Hard Real-Time

The hard real-time definition considers any missed deadline to be a system failure. This scheduling is used extensively in mission critical systems where failure to conform to timing constraints results in a loss of life or property.


  • Air France Flight 447 crashed into the ocean after a sensor malfunction caused a series of system errors. The pilots stalled the aircraft while responding to outdated instrument readings. All 12 crew and 216 passengers were killed.

  • Mars Pathfinder spacecraft was nearly lost when a priority inversion caused system restarts. A higher priority task was not completed on time due to being blocked by a lower priority task. The problem was corrected and the spacecraft landed successfully.

  • An Inkjet printer has a print head with control software for depositing the correct amount of ink onto a specific part of the paper. If a deadline is missed then the print job is ruined.

Firm Real-Time

The firm real-time definition allows for infrequently missed deadlines. In these applications the system can survive task failures so long as they are adequately spaced, however the value of the task's completion drops to zero or becomes impossible.


  • Manufacturing systems with robot assembly lines where missing a deadline results in improperly assembling a part. As long as ruined parts are infrequent enough to be caught by quality control and not too costly, then production continues.

  • A digital cable set-top box decodes time stamps for when frames must appear on the screen. Since the frames are time order sensitive a missed deadline causes jitter, diminishing quality of service. If the missed frame later becomes available it will only cause more jitter to display it, so it's useless. The viewer can still enjoy the program if jitter doesn't occur too often.

Soft Real-Time

The soft real-time definition allows for frequently missed deadlines, and as long as tasks are timely executed their results continue to have value. Completed tasks may have increasing value up to the deadline and decreasing value past it.


  • Weather stations have many sensors for reading temperature, humidity, wind speed, etc. The readings should be taken and transmitted at regular intervals, however the sensors are not synchronized. Even though a sensor reading may be early or late compared with the others it can still be relevant as long as it is close enough.

  • A video game console runs software for a game engine. There are many resources that must be shared between its tasks. At the same time tasks need to be completed according to the schedule for the game to play correctly. As long as tasks are being completely relatively on time the game will be enjoyable, and if not it may only lag a little.

Siewert: Real-Time Embedded Systems and Components.
Liu & Layland: Scheduling Algorithms for Multiprogramming in a Hard Real-Time Environment.
Marchand & Silly-Chetto: Dynamic Scheduling of Soft Aperiodic Tasks and Periodic Tasks with Skips.

How To Launch Git Bash from DOS Command Line?

I'm not sure exactly what you mean by "full Git Bash environment", but I get the nice prompt if I do

"C:\Program Files\Git\bin\sh.exe" --login

In PowerShell

& 'C:\Program Files\Git\bin\sh.exe' --login

The --login switch makes the shell execute the login shell startup files.

Hashing with SHA1 Algorithm in C#

public string Hash(byte [] temp)
    using (SHA1Managed sha1 = new SHA1Managed())
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);


You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);


return System.Text.Encoding.Unicode.GetString(hash);

Can local storage ever be considered secure?


The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.

For an offline app, you must still design and implement a secure keystore.

Aside: If you are using Node.js, use the builtin crypto API.

Native-Javascript Cryptography (pre-WebCrypto)

I presume the primary concern is someone with physical access to the computer reading the localStorage for your site, and you want cryptography to help prevent that access.

If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.

So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.

There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):

  1. Lack of entropy / random number generation;
  2. Lack of a secure keystore i.e. the private key must be password-protected if stored locally, or stored on the server (which bars offline access);
  3. Lack of secure-erase;
  4. Lack of timing characteristics.

Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.

All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.

If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.

For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.

Insertion sort vs Bubble Sort Algorithms

well bubble sort is better than insertion sort only when someone is looking for top k elements from a large list of number i.e. in bubble sort after k iterations you'll get top k elements. However after k iterations in insertion sort, it only assures that those k elements are sorted.

How do I truly reset every setting in Visual Studio 2012?

1) Run Visual Studio Installer

2) Click More on your Installed version and select Repair

3) Restart

Worked on Visual Studio 2017 Community

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

OnClickListener in Android Studio

This worked for me:

protected void onCreate(Bundle savedInstanceState) {

    btnSave = (Button)findViewById(;

    OnClickListener btnListener = new OnClickListener() {
        public void onClick(android.view.View view) {


Find duplicate values in R

This will give you duplicate rows:


This will give you the number of duplicates:



vocabulary2 <-rbind(vocabulary,vocabulary[1,]) #creates a duplicate at the end
#            id year    sex education vocabulary
#21639 20040001 2004 Female         9          3
#[1] 1 #=1 duplicate


OK, with the additional information, here's what you should do: duplicated has a fromLast option which allows you to get duplicates from the end. If you combine this with the normal duplicated, you get all duplicates. The following example adds duplicates to the original vocabulary object (line 1 is duplicated twice and line 5 is duplicated once). I then use table to get the total number of duplicates per ID.

#Create vocabulary object with duplicates
voc.dups <-rbind(vocabulary,vocabulary[1,],vocabulary[1,],vocabulary[5,])

#List duplicates
dups <-voc.dups[duplicated(voc.dups$id)|duplicated(voc.dups$id, fromLast=TRUE),]
#            id year    sex education vocabulary
#1     20040001 2004 Female         9          3
#5     20040008 2004   Male        14          1
#21639 20040001 2004 Female         9          3
#21640 20040001 2004 Female         9          3
#51000 20040008 2004   Male        14          1

#Count duplicates by id
#20040001 20040008 
#       3        2 

A variable modified inside a while loop is not remembered

echo -e $lines | while read line 

The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

while read line
    if [[ "$line" == "second line" ]]
        echo "Variable \$foo updated to $foo inside if inside while loop"
    echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"

You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

lines=$'first line\nsecond line\nthird line'
while read line; do
done <<< "$lines"

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.

This worked for me:

background-image: url('/assets/image.jpg');

Python string.replace regular expression

You are looking for the re.sub function.

import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced 

will print axample atring

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

JavaScript null check

In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

function test(data) {_x000D_
    if (data != null) {_x000D_
        console.log('Data: ', data);_x000D_
test();          // the data=undefined_x000D_
test(null);      // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
test(0); _x000D_
test(false); _x000D_

Here you have all (src):


enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Rather than disabling a new feature, I opted to follow the instructions of the error. In my global.asax.cs I added:

protected void Application_Start(object sender, EventArgs e)
    string JQueryVer = "1.7.1";
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
        Path = "~/Scripts/jquery-" + JQueryVer + ".min.js",
        DebugPath = "~/Scripts/jquery-" + JQueryVer + ".js",
        CdnPath = "" + JQueryVer + ".min.js",
        CdnDebugPath = "" + JQueryVer + ".js",
        CdnSupportsSecureConnection = true,
        LoadSuccessExpression = "window.jQuery"

This comes from an msdn blog post which highlights some of the advantages of script resource mappings. Of particular interest to me was centralized control over the delivery of the script files based on "debug=true", EnableCDN, etc.

jQuery function to open link in new window

Button click event only.

<script src="//" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
          "HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag


Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;

<div id="map" style="clear:both; height:200px;"></div> 

label or @html.Label MVC 4

If you want to just display some text in your .cshtml page, I do not recommend @Html.Label and also not to use the html label as well. The element represents a caption in a user interface. and you'll see that in the case of @Html.Label, a for attribute is added, referring to the id of a, possibly non-existent, element. The value of this attribute is the value of the model field, in which non-alphanumerics are replaced by underscores. You should use @Html.Display or @Html.DisplayFor, possibly wrapped in some plain html elements line span or p.

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...

Get HTML inside iframe using jQuery

Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):


MAMP mysql server won't start. No mysql processes are running

What worked for me was removing all files (but not directories) in the mysql dir.

Edit #2 As per answers below, you only need to delete the log files: [ib_logfile0, ib_logfile1]

So quit MAMP and then in the terminal:

rm /Applications/MAMP/db/mysql/ib_logfile* #(or wherever your MAMP is installed)

Edit!: A few people have mentioned that you may want to back up these files first in case anything goes wrong, so maybe just use mv instead:

mv /Applications/MAMP/db/mysql/*  /tmp/.

If this doesn't work go back and kill all processes: sudo killall -9 mysqld

This is also duplicated here: mysql server won't start MAMP

How to increase size of DOSBox window?

  • go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.

  • run "DOSBox 0.74 Options.bat"

  • the script starts notepad with configuration file: here change



(the resolution can't be changed if output=surface - that's the default).

  • safe configuration file changes.

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");

There is even a Maven plug-in which generates the sources:

Note: If you generate sources using CXF and IDEA, you might want to look at this:

Using Address Instead Of Longitude And Latitude With Google Maps API

You can parse the geolocation through the addresses. Create an Array with jquery like this:

//follow this structure
var addressesArray = [
  'Address Str.No, Postal Area/city'

//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
  $.getJSON(''+addressesArray[x]+'&sensor=false', null, function (data) {
    var p = data.results[0].geometry.location
    var latlng = new google.maps.LatLng(, p.lng);
    //it will place marker based on the addresses, which they will be translated as geolocations.
    var aMarker= new google.maps.Marker({
      position: latlng,
      map: map

Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.

Reset/remove CSS styles for element only

In my specific scenario i wanted to skip applying common styles to a specific part of the page, better illustrated like this:

<body class='common-styles'>
    <div id='header'>Wants common styles</div>
    <div id='container'>Does NOT want common styles</div>
    <div id='footer'>Wants common styles</div>

After messing with CSS reset which didn't bring much success (mainly because of rules precedence and complex stylesheet hierarchy), brought up ubiquitous jQuery to the rescue, which did the job very quickly and reasonably dirty:

$(function() {

(Now tell how evil it is to use JS to deal with CSS :-) )

phpmailer - The following SMTP Error: Data not accepted

In my case in cpanel i have 'Register mail ids' option where i add my email address and after 30 minutes it works fine with simple php mail function.

Linq filter List<string> where it contains a string value from another List<string>

its even easier:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

Option to ignore case with .contains method?

For Java 8, You can have one more solution like below

List<String> list = new ArrayList<>();
String searchTerm = "dvd";

if(String.join(",", list).toLowerCase().contains(searchTerm)) {
  System.out.println("Element Present!");

sql insert into table with select case values

Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL

INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
       COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport

Demo on SQLFiddle

Java Regex to Validate Full Name allow only Spaces and Letters

Try with this:

public static boolean userNameValidation(String name){

return name.matches("(?i)(^[a-z])((?![? .,'-]$)[ .]?[a-z]){3,24}$");

Auto-center map with multiple markers in Google Maps API v3

i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:

var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
function getCenterPosition(tempdata){_x000D_
 var tempLat = tempdata[0].split("-");_x000D_
 var latitudearray = [];_x000D_
 var longitudearray = [];_x000D_
 var i;_x000D_
 for(i=0; i<tempLat.length;i++){_x000D_
  var coordinates = tempLat[i].split("|");_x000D_
 latitudearray.sort(function (a, b) { return a-b; });_x000D_
 longitudearray.sort(function (a, b) { return a-b; });_x000D_
 var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
 var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
 var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
 var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
 temp = (longidifferenece / 2).toFixed(4) ;_x000D_
 var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
 var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
 var zoomvalue; _x000D_
 if(maxdifference >= 0 && maxdifference <= 0.0037)  //zoom 17_x000D_
 else if(maxdifference > 0.0037 && maxdifference <= 0.0070)  //zoom 16_x000D_
 else if(maxdifference > 0.0070 && maxdifference <= 0.0130)  //zoom 15_x000D_
 else if(maxdifference > 0.0130 && maxdifference <= 0.0290)  //zoom 14_x000D_
 else if(maxdifference > 0.0290 && maxdifference <= 0.0550)  //zoom 13_x000D_
 else if(maxdifference > 0.0550 && maxdifference <= 0.1200)  //zoom 12_x000D_
 else if(maxdifference > 0.1200 && maxdifference <= 0.4640)  //zoom 10_x000D_
 else if(maxdifference > 0.4640 && maxdifference <= 1.8580)  //zoom 8_x000D_
 else if(maxdifference > 1.8580 && maxdifference <= 3.5310)  //zoom 7_x000D_
 else if(maxdifference > 3.5310 && maxdifference <= 7.3367)  //zoom 6_x000D_
 else if(maxdifference > 7.3367 && maxdifference <= 14.222)  //zoom 5_x000D_
 else if(maxdifference > 14.222 && maxdifference <= 28.000)  //zoom 4_x000D_
 else if(maxdifference > 28.000 && maxdifference <= 58.000)  //zoom 3_x000D_
 return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_

Initial bytes incorrect after Java AES/CBC decryption

Optimized version of the accepted answer.

  • no 3rd party libs

  • includes IV into the encrypted message (can be public)

  • password can be of any length


import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {
    public static byte[] getRandomInitialVector() {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
            byte[] initVector = new byte[cipher.getBlockSize()];
            return initVector;
        } catch (Exception ex) {
        return null;

    public static byte[] passwordTo16BitKey(String password) {
        try {
            byte[] srcBytes = password.getBytes("UTF-8");
            byte[] dstBytes = new byte[16];

            if (srcBytes.length == 16) {
                return srcBytes;

            if (srcBytes.length < 16) {
                for (int i = 0; i < dstBytes.length; i++) {
                    dstBytes[i] = (byte) ((srcBytes[i % srcBytes.length]) * (srcBytes[(i + 1) % srcBytes.length]));
            } else if (srcBytes.length > 16) {
                for (int i = 0; i < srcBytes.length; i++) {
                    dstBytes[i % dstBytes.length] += srcBytes[i];

            return dstBytes;
        } catch (UnsupportedEncodingException ex) {

        return null;

    public static String encrypt(String key, String value) {
        return encrypt(passwordTo16BitKey(key), value);

    public static String encrypt(byte[] key, String value) {
        try {
            byte[] initVector = Encryptor.getRandomInitialVector();
            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.getEncoder().encodeToString(encrypted) + " " + Base64.getEncoder().encodeToString(initVector);
        } catch (Exception ex) {

        return null;

    public static String decrypt(String key, String encrypted) {
        return decrypt(passwordTo16BitKey(key), encrypted);

    public static String decrypt(byte[] key, String encrypted) {
        try {
            String[] encryptedParts = encrypted.split(" ");
            byte[] initVector = Base64.getDecoder().decode(encryptedParts[1]);
            if (initVector.length != 16) {
                return null;

            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedParts[0]));

            return new String(original);
        } catch (Exception ex) {

        return null;


String key = "Password of any length.";
String encrypted = Encryptor.encrypt(key, "Hello World");
String decrypted = Encryptor.decrypt(key, encrypted);

Example output:

QngBg+Qc5+F8HQsksgfyXg== yDfYiIHTqOOjc0HRNdr1Ng==
Hello World

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

How do I disable the security certificate check in Python requests

Also can be done from the environment variable:

export CURL_CA_BUNDLE=""

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
    item.SomeProperty = null;

However, the Loop approach is more readable and therefore more maintainable.

Image, saved to sdcard, doesn't appear in Android's Gallery app

Use this after saving the image

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

How to sort an object array by date property?

Your data needs some corrections:

var array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"},{id: 2, date: "Mar 28 2012 08:00:00 AM"}];

After correcting the data, you can use this piece of code:

function sortFunction(a,b){  
    var dateA = new Date(;
    var dateB = new Date(;
    return dateA > dateB ? 1 : -1;  

var array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"},{id: 2, date: "Mar 28 2012 08:00:00 AM"}];

Hover and Active only when not disabled

You can use :enabled pseudo-class, but notice IE<9 does not support it:

    /*your styles*/
    /*your styles*/

How to embed a PDF viewer in a page?

If I'm not mistaken, the OP was asking (although later accepted a .js solution) whether Google's embedded PDF display server will display a PDF on his own website.

So, one and a half years later: yes, it will.

See Also, see, and plug in the URL of the file you want to display.

Edit: Re-reading, OP was asking for solutions that don't use iFrames. I don't think that's possible with Google's viewer.

How can I dynamically add a directive in AngularJS?

The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template. However if your directive takes advantage of templateUrl his answer will not work. Here is what worked for me:

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {}, 
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                }, 0);

How to test the `Mosquitto` server?

If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto server

just visit and enter server connection details.

If you got connected means your server is configured properly.

You can also test publish and subscribe of messages using this mqtt web socket

insert multiple rows into DB2 database

I disagree on the comment posted by Hogan. Those instructions will work for IBM DB2 Mini, but it's not the case of DB2 Z/OS.

Here is an example:

Exception data: org.apache.ibatis.exceptions.PersistenceException:
The error occurred while setting parameters

 (?,          1,          ?,          ?,          ?,          ?),          
 (?,          1,          ?,          ?,          ?,          ?)


So I can confirm that inline comma separated bulk inserts are not working on DB2 Z/OS (maybe you could feed it some props to get it working...)

Is there a Java API that can create rich Word documents?

After a little more research, I came across iText, a PDF and RTF-file creation API. I think I can use the RTF generation to create a Doc-readable file that can then be edited using Doc and re-saved.

Anyone have any experience with iText, used in this fashion?

How to detect Safari, Chrome, IE, Firefox and Opera browser?

You can use try and catch to use the different browser error messages. IE and edge were mixed up, but I used the duck typing from Rob W (based on this project here:

var getBrowser = function() {        
    try {
        var e;
        var f = e.width;
    } catch(e) {
        var err = e.toString();

        if(err.indexOf("not an object") !== -1) {
            return "safari";
        } else if(err.indexOf("Cannot read") !== -1) {
            return "chrome";
        } else if(err.indexOf("e is undefined") !== -1) {
            return "firefox";
        } else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
            if(!(false || !!document.documentMode) && !!window.StyleMedia) {
                return "edge";
            } else {
                return "IE";
        } else if(err.indexOf("cannot convert e into object") !== -1) {
            return "opera";
        } else {
            return undefined;

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
    ' need to initialize obj: '
    Set obj = ...
End If

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        $project: {
            _id: 1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"


The response will be looking like below:

/* 1 */
    "_id" : "address4",
    "bookCounts" : [
            "bookName" : "book3",
            "count" : 1
    "totalBookAtAddress" : 1

/* 2 */
    "_id" : "address90",
    "bookCounts" : [
            "bookName" : "book33",
            "count" : 1
    "totalBookAtAddress" : 1

/* 3 */
    "_id" : "address15",
    "bookCounts" : [
            "bookName" : "book1",
            "count" : 1
    "totalBookAtAddress" : 1

/* 4 */
    "_id" : "address3",
    "bookCounts" : [
            "bookName" : "book9",
            "count" : 1
    "totalBookAtAddress" : 1

/* 5 */
    "_id" : "address5",
    "bookCounts" : [
            "bookName" : "book1",
            "count" : 1
    "totalBookAtAddress" : 1

/* 6 */
    "_id" : "address1",
    "bookCounts" : [
            "bookName" : "book1",
            "count" : 3
            "bookName" : "book5",
            "count" : 1
    "totalBookAtAddress" : 4

/* 7 */
    "_id" : "address2",
    "bookCounts" : [
            "bookName" : "book1",
            "count" : 2
            "bookName" : "book5",
            "count" : 1
    "totalBookAtAddress" : 3

/* 8 */
    "_id" : "address77",
    "bookCounts" : [
            "bookName" : "book11",
            "count" : 1
    "totalBookAtAddress" : 1

/* 9 */
    "_id" : "address9",
    "bookCounts" : [
            "bookName" : "book99",
            "count" : 1
    "totalBookAtAddress" : 1

Converting integer to digit list

Use list on a number converted to string:

In [1]: [int(x) for x in list(str(123))]
Out[2]: [1, 2, 3]

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

Fatal error: Class 'ZipArchive' not found in

I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :

sudo apt-get install php7.2-zip

What's the name for hyphen-separated case?

Adding the correct link here Kebab Case

which is All lowercase with - separating words.

How to center align the cells of a UICollectionView?

In Swift, the following will distribute cells evenly by applying the correct amount of padding on the sides of each cell. Of course, you need to know/set your cell width first.

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        var cellWidth : CGFloat = 110;

        var numberOfCells = floor(self.view.frame.size.width / cellWidth);
        var edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1);

        return UIEdgeInsetsMake(0, edgeInsets, 60.0, edgeInsets);

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Where do I find some good examples for DDD?

Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action. While the book is focused on the presentation layer, the application is modeled using DDD.

Is it possible to put CSS @media rules inline?

Media Queries in style-Attributes are not possible right now. But if you have to set this dynamically via Javascript. You could insert that rule via JS aswell.

document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");

This is as if the style was there in the stylesheet. So be aware of specificity.

Best way to store time (hh:mm) in a database

Try smalldatetime. It may not give you what you want but it will help you in your future needs in date/time manipulations.

How to remove the first character of string in PHP?

The substr() function will probably help you here:

 $str = substr($str, 1);

Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.

How to query a MS-Access Table from MS-Excel (2010) using VBA

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    Set rs = Nothing
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

Current time formatting with Javascript

Using Moment.

I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).


You wanted something that looked like this:

Friday 2:00pm 1 Feb 2013

Well, with Moment all you need you to do is this:

import Moment from "moment";

Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"

And if you wanted to match that exact date and time, all you would need to do is this:

import Moment from "moment";

Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"

There's a myriad of other formatting options that can be found here.


Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:

npm install moment --save


yarn add moment

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

Copy a variable's value into another

I do not understand why the answers are so complex. In Javascript, primitives (strings, numbers, etc) are passed by value, and copied. Objects, including arrays, are passed by reference. In any case, assignment of a new value or object reference to 'a' will not change 'b'. But changing the contents of 'a' will change the contents of 'b'.

var a = 'a'; var b = a; a = 'c'; // b === 'a'

var a = {a:'a'}; var b = a; a = {c:'c'}; // b === {a:'a'} and a = {c:'c'}

var a = {a:'a'}; var b = a; a.a = 'c'; // b.a === 'c' and a.a === 'c'

Paste any of the above lines (one at a time) into node or any browser javascript console. Then type any variable and the console will show it's value.

converting list to json format - quick and easy way

For me, it worked to use Newtonsoft.Json:

using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);

What command shows all of the topics and offsets of partitions in Kafka?

You might want to try kt. It's also quite faster than the bundled kafka-topics.

This is the current most complete info description you can get out of a topic with kt:

kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas

It also outputs as JSON, so you can pipe it to jq for further flexibility.

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

In C++, there is no difference in main() and main(void).

But in C, main() will be called with any number of parameters.


main ( ){
    //Works fine !
    //It won't give the error. The code will compile successfully.
    //(May cause Segmentation fault when run)

main(void) will be called without any parameters. If we try to pass then this end up leading to a compiler error.


main (void) {
     //This throws "error: too many arguments to function ‘main’ "

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
                 props=[('padding', "0em 0em")]),
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
], axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\

enter image description here

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)


1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

How to use CSS to surround a number with a circle?


<h3><span class="numberCircle">1</span> Regiones del Interior</h3>


    .numberCircle { 

    border:2px solid #000000;


SQL Server : How to test if a string has only digit characters

Use Not Like

where some_column NOT LIKE '%[^0-9]%'


declare @str varchar(50)='50'--'asdarew345'

select 1 where @str NOT LIKE '%[^0-9]%'

problem with php mail 'From' header

I realize this is an old thread, but i had the same problem since i moved to bluehost yesterday. It may not have been the selected answer but i support the bluehost article 206 reply.

I created a valid email in control panel and used it as my From address and it worked.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

How to make <a href=""> link look like a button?

for those having problems after adding active and focus give a class or id name to your button and add this to css

for example

//html code

<button id="aboutus">ABOUT US</button>

//css code

#aboutus{background-color: white;border:none;outline-style: none;}

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Create a group object and call methods like below example:

grp = df.groupby(['col1',  'col2',  'col3']) 


What are the differences between char literals '\n' and '\r' in Java?

It actually depends on what is being used to print the result. Usually, the result is the same, just as you say -

Historically carriage return is supposed to do about what the home button does: return the caret to the start of the line.

\n is supposed to give you a new line but not move the caret.

If you think about old printers, you're pretty much thinking how the original authors of the character sets were thinking. It's a different operation moving the paper feeder and moving the caret. These two characters express that difference.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

This is what solves the problem:


from Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

How to include a child object's child object in Entity Framework 5

With EF Core in .NET Core you can use the keyword ThenInclude :

return DatabaseContext.Applications
 .Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);

Include childs from childrens collection :

return DatabaseContext.Applications
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);

What's the function like sum() but for multiplication? product()?


In Python 3.8, the prod function was added to the math module. See:

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8

Note, the use of log() requires that all the inputs are positive.

How to open child forms positioned within MDI parent in VB.NET?

See this page for the solution!

I was able to implement the Child form inside the parent.

In the Example below Form2 should change to the name of your child form. NewMDIChild.MdiParent=me is the main form since the control that opens (shows) the child form is the parent or Me.

NewMDIChild.Show() is your child form since you associated your child form with Dim NewMDIChild As New Form2()

Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
   Dim NewMDIChild As New Form2()
   'Set the Parent Form of the Child window.
   NewMDIChild.MdiParent = Me
   'Display the new form.
End Sub

Simple and it works.

Python os.path.join() on a list

This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]

reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

This has been answered below but answering if you have a list of items that needs to be joined.

Get first day of week in SQL Server

Set DateFirst 1;

    Datepart(wk, TimeByDay) [Week]
                WHEN  Datepart(dw, TimeByDay) = 1 then 0
                WHEN  Datepart(dw, TimeByDay) = 2 then -1
                WHEN  Datepart(dw, TimeByDay) = 3 then -2
                WHEN  Datepart(dw, TimeByDay) = 4 then -3
                WHEN  Datepart(dw, TimeByDay) = 5 then -4
                WHEN  Datepart(dw, TimeByDay) = 6 then -5
                WHEN  Datepart(dw, TimeByDay) = 7 then -6
                , TimeByDay) as StartOfWeek

from TimeByDay_Tbl

This is my logic. Set the first of the week to be Monday then calculate what is the day of the week a give day is, then using DateAdd and Case I calculate what the date would have been on the previous Monday of that week.

Convert String to Date in MS Access Query

cdate(Format([Datum im Format DDMMYYYY],'##/##/####') ) 

converts string without punctuation characters into date

How do I export html table data as .csv file?

Here is a really quick CoffeeScript/jQuery example

csv = []
for row in $('#sometable tr')
  csv.push ("\"#{col.innerText}\"" for col in $(row).find('td,th')).join(',')
output = csv.join("\n")

SQL Server Installation - What is the Installation Media Folder?

I ran into this just now with SQL Server 2014 SP1. The installer gave me the exact same problem and I followed suggestions from other answers to this question, but it got me nowhere.

In the end I figured out that I needed to download and install SQL Server 2014 first, and then apply SP1 to it. (doh)

Youtube API Limitations

A little bit late, but you can request a higher quote here:

How to extract the decimal part from a floating point number in C?

I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part. But, it won't work for all cases (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:

#include <stdio.h>
#include <stdlib.h>

int main(void)
    char s_value[60], s_integral[60], s_fractional[60];
    int i, found = 0, count = 1, integral, fractional;

    scanf("%s", s_value);

    for (i = 0; s_value[i] != '\0'; i++)
        if (!found)
            if (s_value[i] == '.')
                found = 1;
                s_integral[i] = '\0';
            s_integral[i] = s_value[i];
            s_fractional[i - count] = s_value[i];
    s_fractional[i - count] = '\0';

    integral = atoi(s_integral);
    fractional = atoi(s_fractional);
    printf("value = %s, integral = %d, fractional = %d\n",
        s_value, integral, fractional);

    return 0;

How to get logged-in user's name in Access vba?

Public Declare Function GetUserName Lib "advapi32.dll" 
    Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long


Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String

strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))

Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

Find by key deep in a nested array

If you want to get the first element whose id is 1 while object is being searched, you can use this function:

function customFilter(object){
    if(object.hasOwnProperty('id') && object["id"] == 1)
        return object;

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            var o = customFilter(object[Object.keys(object)[i]]);
            if(o != null)
                return o;

    return null;

If you want to get all elements whose id is 1, then (all elements whose id is 1 are stored in result as you see):

function customFilter(object, result){
    if(object.hasOwnProperty('id') && == 1)

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            customFilter(object[Object.keys(object)[i]], result);

Using 'make' on OS X

Have you installed the Apple developer tools? What happens if you type gcc -v ?

It look as if you do not have downloaded the development stuff. You can get it for free (after registration) from

How to trim whitespace from a Bash variable?

#Execute this script with the string argument passed in double quotes !! 
#var2 gives the string without spaces.
#$1 is the string passed in double quotes
var2=`echo $1 | sed 's/ \+//g'`
echo $var2

Execution time of C program

Every solution's are not working in my system.

I can get using

#include <time.h>

double difftime(time_t time1, time_t time0);

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()


If you want to support IE or other older browsers:

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
            Array.prototype.indexOf = function(searchElement /*, fromIndex */)
         "use strict";
         if (this === void 0 || this === null)
           throw new TypeError();
         var t = Object(this);
         var len = t.length >>> 0;
         if (len === 0)
           return -1;
         var n = 0;
         if (arguments.length > 0)
           n = Number(arguments[1]);
           if (n !== n)
             n = 0;
           else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
             n = (n > 0 || -1) * Math.floor(Math.abs(n));
         if (n >= len)
           return -1;
         var k = n >= 0
               ? n
               : Math.max(len - Math.abs(n), 0);
         for (; k < len; k++)
           if (k in t && t[k] === searchElement)
             return k;
         return -1;
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function (obj, fromIndex) {
         if (fromIndex == null) {
             fromIndex = 0;
         } else if (fromIndex < 0) {
             fromIndex = Math.max(0, this.length + fromIndex);
         for (var i = fromIndex, j = this.length; i < j; i++) {
             if (this[i] === obj)
                 return i;
         return -1;
  3. roosteronacid's version:

     Array.prototype.hasObject = (
       !Array.indexOf ? function (o)
         var l = this.length + 1;
         while (l -= 1)
             if (this[l - 1] === o)
                 return true;
         return false;
       } : function (o)
         return (this.indexOf(o) !== -1);

Can we have multiple "WITH AS" in single sql - Oracle SQL

the correct syntax is -

with t1
(select * from tab1
where conditions...
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
select * from t1, t2
where t1.col1=t2.col2;

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:


GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-


206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:


GET /BigBuckBunny_320x180.mp4
Range: bytes=100-


206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*


You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456


Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

How can I find the latitude and longitude from address?

Ud_an's solution with updated API's

Note: LatLng class is part of Google Play Services.


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

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

Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.

public LatLng getLocationFromAddress(Context context,String strAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng p1 = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;

        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude() );

    } catch (IOException ex) {


    return p1;

How to debug Javascript with IE 8

You can get more information about IE8 Developer Toolbar debugging at Debugging JScript or Debugging Script with the Developer Tools.

Hiding a button in Javascript

//Your code to make the box goes here... call it box"foo";
//Your code to remove the box goes here

of course if you are doing a lot of stuff like this, use jQuery

jquery, find next element by class

Given a first selector: SelectorA, you can find the next match of SelectorB as below:

Example with mouseover to change border-with:

$("SelectorA").on("mouseover", function() {
    var i = $(this).find("SelectorB")[0];
    $(i).css({"border" : "1px"});

General use example to change border-with:

var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

Showing line numbers in IPython/Jupyter Notebooks

In Jupyter Lab 2.1.5, it is View -> Show Line Numbers.

enter image description here

Angular2 - Radio Button Binding

Radio input doesn't seem to be supported yet. There should be a radio input value accessor (similar to checkbox's one, where it sets 'checked' attr here) but I didn't find any. So I implemented one; you can check it out here.

git switch branch without discarding local changes

You could use --merge/-m git checkout option: git checkout -m <another-branch>

-m --merge

When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.


SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

Make a UIButton programmatically in Swift

Yeah in simulator. Some times it wont recognise the selector there is a bug it seems. Even i faced not for your code , then i just changed the action name (selector). It works

let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
buttonPuzzle.backgroundColor = UIColor.greenColor()
buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonPuzzle.tag = 22;

An example selector function is here:

func buttonAction(sender:UIButton!) {
    var btnsendtag:UIButton = sender
    if btnsendtag.tag == 22 {            
        //println("Button tapped tag 22")

Stop Chrome Caching My JS Files

You can open an incognito window instead. Switching to an incognito window worked for me when disabling the cache in a normal chrome window still didn't reload a JavaScript file I had changed since the last cache.

Unit Testing C Code

I'm currently using the CuTest unit test framework:

It's ideal for embedded systems as it's very lightweight and simple. I had no problems getting it to work on the target platform as well as on the desktop. In addition to writing the unit tests, all that's required is:

  • a header file included wherever you're calling the CuTest routines
  • a single additional 'C' file to be compiled/linked into the image
  • some simple code added to to main to set up and call the unit tests - I just have this in a special main() function that gets compiled if UNITTEST is defined during the build.

The system needs to support a heap and some stdio functionality (which not all embedded systems have). But the code is simple enough that you could probably work in alternatives to those requirements if your platform doesn't have them.

With some judicious use of extern "C"{} blocks it also supports testing C++ just fine.

shell script to remove a file if it already exist

Something like this would work


if [ -fe FILE ]
    rm FILE

-f checks if it's a regular file

-e checks if the file exist

Introduction to if for more information

EDIT : -e used with -f is redundant, fo using -f alone should work too

How to implement a read only property

With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):

public string Name { get; }

public Customer(string name)  // Constructor
    Name = name;

private void SomeFunction()
    Name = "Something Else";  // Compile-time error

And you can now also initialise properties (with or without a setter) inline:

public string Name { get; } = "Boris";

Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.

Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in @CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

encodeURIComponent doesn't encode -_.!~*'(), causing problem in posting data to php in xml string.

For example:
<xml><text x="100" y="150" value="It's a value with single quote" /> </xml>

General escape with encodeURI

You can see, single quote is not encoded. To resolve issue I created two functions to solve issue in my project, for Encoding URL:

function encodeData(s:String):String{
    return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");

For Decoding URL:

function decodeData(s:String):String{
        return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
    }catch (e:Error) {
    return "";

How do I execute a file in Cygwin?

Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.

A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.

How to validate domain credentials?

I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.

I`ve been looking for something like this for ages... So i hope this helps someone!

using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;

namespace User
    public static class UserValidation
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr handle);
        enum LogonProviders : uint
            Default = 0, // default for platform (use this!)
            WinNT35,     // sends smoke signals to authority
            WinNT40,     // uses NTLM
            WinNT50      // negotiates Kerb or NTLM
        enum LogonTypes : uint
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkCleartext = 8,
            NewCredentials = 9
        public  const int ERROR_PASSWORD_MUST_CHANGE = 1907;
        public  const int ERROR_LOGON_FAILURE = 1326;
        public  const int ERROR_ACCOUNT_RESTRICTION = 1327;
        public  const int ERROR_ACCOUNT_DISABLED = 1331;
        public  const int ERROR_INVALID_LOGON_HOURS = 1328;
        public  const int ERROR_NO_LOGON_SERVERS = 1311;
        public  const int ERROR_INVALID_WORKSTATION = 1329;
        public  const int ERROR_ACCOUNT_LOCKED_OUT = 1909;      //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
        public  const int ERROR_ACCOUNT_EXPIRED = 1793;
        public  const int ERROR_PASSWORD_EXPIRED = 1330;

        public static int CheckUserLogon(string username, string password, string domain_fqdn)
            int errorCode = 0;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
                if (!pc.ValidateCredentials(username, password))
                    IntPtr token = new IntPtr();
                        if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
                            errorCode = Marshal.GetLastWin32Error();
                    catch (Exception)
            return errorCode;

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setDataAndType(photoUri, "image/*");

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

Objective-C ARC: strong vs retain and weak vs assign

As far as I know, strong and retain are synonyms, so they do exactly the same.

Then the weak is almost like assign, but automatically set to nil after the object, it is pointing to, is deallocated.

That means, you can simply replace them.

However, there is one special case I've encountered, where I had to use assign, rather than weak. Let's say we have two properties delegateAssign and delegateWeak. In both is stored our delegate, that is owning us by having the only strong reference. The delegate is deallocating, so our -dealloc method is called too.

// Our delegate is deallocating and there is no other strong ref.
- (void)dealloc {
    [delegateWeak doSomething];
    [delegateAssign doSomething];

The delegate is already in deallocation process, but still not fully deallocated. The problem is that weak references to him are already nullified! Property delegateWeak contains nil, but delegateAssign contains valid object (with all properties already released and nullified, but still valid).

// Our delegate is deallocating and there is no other strong ref.
- (void)dealloc {
    [delegateWeak doSomething]; // Does nothing, already nil.
    [delegateAssign doSomething]; // Successful call.

It is quite special case, but it reveal us how those weak variables work and when they are nullified.

Convert a string into an int

See the NSString Class Reference.

NSString *string = @"5";
int value = [string intValue];

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

How do I check if an element is really visible with JavaScript?

 * Checks display and visibility of elements and it's parents
 * @param  DomElement  el
 * @param  boolean isDeep Watch parents? Default is true
 * @return {Boolean}
 * @author Oleksandr Knyga <[email protected]>
function isVisible(el, isDeep) {
    var elIsVisible = true;

    if("undefined" === typeof isDeep) {
        isDeep = true;

    elIsVisible = elIsVisible && el.offsetWidth > 0 && el.offsetHeight > 0;

    if(isDeep && elIsVisible) {

        while('BODY' != el.tagName && elIsVisible) {
            elIsVisible = elIsVisible && 'hidden' != window.getComputedStyle(el).visibility;
            el = el.parentElement;

    return elIsVisible;

SQL left join vs multiple tables on FROM line?

The SELECT * FROM table1, table2, ... syntax is ok for a couple of tables, but it becomes exponentially (not necessarily a mathematically accurate statement) harder and harder to read as the number of tables increases.

The JOIN syntax is harder to write (at the beginning), but it makes it explicit what criteria affects which tables. This makes it much harder to make a mistake.

Also, if all the joins are INNER, then both versions are equivalent. However, the moment you have an OUTER join anywhere in the statement, things get much more complicated and it's virtually guarantee that what you write won't be querying what you think you wrote.

Mockito How to mock only the call of a method of the superclass

Even if i totally agree with iwein response (

favor composition over inheritance

), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.

So, my suggestion :

 * BaseService is now an asbtract class encapsulating 
 * some common logic callable by child implementations
abstract class BaseService {  
    protected void commonSave() {
        // Put your common work here

    abstract void save();

public ChildService extends BaseService {  
    public void save() {
        // Put your child specific work here
        // ...


And then, in the unit test :

    ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);

    Mockito.doAnswer(new Answer<Void>() {
        public Boolean answer(InvocationOnMock invocation)
                throws Throwable {
            // Put your mocked behavior of BaseService.commonSave() here
            return null;

    Mockito.verify(childSrv, Mockito.times(1)).commonSave();

    // Put any other assertions to check child specific work is done

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>


I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

How do I remove trailing whitespace using a regular expression?

The platform is not specified, but in C# (.NET) it would be:

Regular expression (presumes the multiline option - the example below uses it):

    [ \t]+(\r?$)



For an explanation of "\r?$", see Regular Expression Options, Multiline Mode (MSDN).

Code example

This will remove all trailing spaces and all trailing TABs in all lines:

string inputText = "     Hello, World!  \r\n" +
                   "  Some other line\r\n" +
                   "     The last line  ";
string cleanedUpText = Regex.Replace(inputText,
                                     @"[ \t]+(\r?$)", @"$1",

Tree view of a directory/folder in Windows?

tree /f /a


The Windows command tree /f /a produces a tree of the current folder and all files & folders contained within it in ASCII format.

The output can be redirected to a text file using the > parameter.


For Windows 8.1 or Windows 10, follow these steps:

  1. Navigate into the folder in file explorer.
  2. Press Shift, right-click mouse, and select "Open command window here".
  3. Type tree /f /a > tree.txt and press Enter.
  4. Open the new tree.txt file in your favourite text editor/viewer.

Note: Windows 7, Vista, XP and earlier users can type cmd in the run command box in the start menu for a command window.

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here:

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Git push error: Unable to unlink old (Permission denied)

FWIW - I had a similar problem and I'm not sure if this alleviated it (beyond the permission mod): Closing Eclipse that was using the branch with this problem.

How do I create an .exe for a Java program?

If Java is installed on the target machine, there is no need to create an .exe file. A .jar file should be sufficient.

On Selenium WebDriver how to get Text from Span Tag

If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();

css example:

String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();

IntelliJ does not show project folders

If you have a gradle module with the same name as your projects root folder, the gradle import will replace your toplevel module configuration and change your view completely.

Make sure you have no gradle module with the same name as your root directory.

builtins.TypeError: must be str, not bytes

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list


mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

String format currency

As others have said, you can achieve this through an IFormatProvider. But bear in mind that currency formatting goes well beyond the currency symbol. For example a correctly-formatted price in the US may be "$ 12.50" but in France this would be written "12,50 $" (the decimal point is different as is the position of the currency symbol). You don't want to lose this culture-appropriate formatting just for the sake of changing the currency symbol. And the good news is that you don't have to, as this code demonstrates:

var cultureInfo = Thread.CurrentThread.CurrentCulture;   // You can also hardcode the culture, e.g. var cultureInfo = new CultureInfo("fr-FR"), but then you lose culture-specific formatting such as decimal point (. or ,) or the position of the currency symbol (before or after)
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need

var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".

How do I revert an SVN commit?

If you're using the TortoiseSVN client, it's easily done via the Show Log dialog.

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

You should use Task.Delay instead of Sleep for async programming and then use Task.WhenAll to combine the task results. The tasks would run in parallel.

public class Program
        static void Main(string[] args)
        public static void Go()
        public static async void GoAsync()


            var task1 = Sleep(5000);
            var task2 = Sleep(3000);

            int[] result = await Task.WhenAll(task1, task2);

            Console.WriteLine("Slept for a total of " + result.Sum() + " ms");


        private async static Task<int> Sleep(int ms)
            Console.WriteLine("Sleeping for {0} at {1}", ms, Environment.TickCount);
            await Task.Delay(ms);
            Console.WriteLine("Sleeping for {0} finished at {1}", ms, Environment.TickCount);
            return ms;

Convert generic list to dataset in C#

Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable (e.g. List), you will get very basic one-way binding, but if it implements IBindingList as well (e.g. BindingList, DataView), then you get two-way binding.

(Mac) -bash: __git_ps1: command not found

This one worked for me, and it has colored git output and an indicator in the prompt whether files have changed / been added, right baked into it:


. /usr/local/Cellar/git/
. /usr/local/Cellar/git/

PS1='\[\033[32m\]\u@\h\[\033[00m\]:\[\033[34m\]\w\[\033[31m\]$(__git_ps1)\[\033[00m\]\$ '

Be sure to use the correct path! I used homebrew to install git, use brew list git to get the path to your current installation.

Would be nice not to use a hard coded path, but don't know how to get the path to the current installation.

More infos here:

What are .a and .so files?

They are used in the linking stage. .a files are statically linked, and .so files are sort-of linked, so that the library is needed whenever you run the exe.

You can find where they are stored by looking at any of the lib directories... /usr/lib and /lib have most of them, and there is also the LIBRARY_PATH environment variable.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

The difference is that you can lock and unlock a std::unique_lock. std::lock_guard will be locked only once on construction and unlocked on destruction.

So for use case B you definitely need a std::unique_lock for the condition variable. In case A it depends whether you need to relock the guard.

std::unique_lock has other features that allow it to e.g.: be constructed without locking the mutex immediately but to build the RAII wrapper (see here).

std::lock_guard also provides a convenient RAII wrapper, but cannot lock multiple mutexes safely. It can be used when you need a wrapper for a limited scope, e.g.: a member function:

class MyClass{
    std::mutex my_mutex;
    void member_foo() {
        std::lock_guard<mutex_type> lock(this->my_mutex);            
         block of code which needs mutual exclusion (e.g. open the same 
         file in multiple threads).

        //mutex is automatically released when lock goes out of scope

To clarify a question by chmike, by default std::lock_guard and std::unique_lock are the same. So in the above case, you could replace std::lock_guard with std::unique_lock. However, std::unique_lock might have a tad more overhead.

Note that these days (since, C++17) one should use std::scoped_lock instead of std::lock_guard.

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

Adding one day to a date

Since you already have an answer to what's wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.

Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It's great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.

In your particular case, this can look like the following. First, you need to find out what is it that you're looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:

(new Future(
    new DateTimeParsedFromISO8601('2009-09-30 20:24:00'),
    new OneDay()

For more examples with datetime juggling check out this one.

PHP Error: Function name must be a string

    require_once '../config/config.php';
    require_once '../classes/class.College.php';
    $Response = array();
    $Parms = $_POST;
    $Parms['Id'] = Id;  

        $Parms['function'] = 'DeleteCollege';
        switch ($Parms['function']) {
        case 'InsertCollege': {
            $Response = College::InsertCollege($Parms);
        case 'GetCollegeById': {
            $Response = College::GetCollegeById($Parms['Id']);
        case 'GetAllCollege': {
            $Response = College::GetAllCollege();
        case 'UpdateCollege': {
            $Response = College::UpdateCollege($Parms);
        case 'DeleteCollege': {
            $Response = array('status' => 'R');
    echo json_encode($Response);

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.


preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);

Might not be the best way...

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf

main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile

Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.

It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.

MVC 4 - Return error message from Controller - Show in View

You can add this to your _Layout.cshtml:

@using MyProj.ViewModels;
    @if (TempData["UserMessage"] != null)
        var message = (MessageViewModel)TempData["UserMessage"];
        <div class="alert @message.CssClassName" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>

Then if you want to throw an error message in your controller:

    TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger  alert-dismissible", Title = "Error", Message = "This is an error message" };


public class MessageViewModel
        public string CssClassName { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }

Note: Using Bootstrap 4 classes.

How to send email from Terminal?

echo "this is the body" | mail -s "this is the subject" "to@address"

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

Can you remove elements from a std::list while iterating through it?

I have sumup it, here is the three method with example:

1. using while loop

list<int> lst{4, 1, 2, 3, 5};

auto it = lst.begin();
while (it != lst.end()){
    if((*it % 2) == 1){
        it = lst.erase(it);// erase and go to next
    } else{
        ++it;  // go to next

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

2. using remove_if member funtion in list:

list<int> lst{4, 1, 2, 3, 5};

lst.remove_if([](int a){return a % 2 == 1;});

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

3. using std::remove_if funtion combining with erase member function:

list<int> lst{4, 1, 2, 3, 5};

lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
    return a % 2 == 1;
}), lst.end());

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

4. using for loop , should note update the iterator:

list<int> lst{4, 1, 2, 3, 5};

for(auto it = lst.begin(); it != lst.end();++it){
    if ((*it % 2) == 1){
        it = lst.erase(it);  erase and go to next(erase will return the next iterator)
        --it;  // as it will be add again in for, so we go back one step

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2 

How to emulate GPS location in the Android Emulator?

If the above solutions don't work. Try this:

Inside your android Manifest.xml, add the following two links OUTSIDE of the application tag, but inside your manifest tag of course

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

What is the difference between declarations, providers, and import in NgModule?

Angular Concepts

  • imports makes the exported declarations of other modules available in the current module
  • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
  • providers are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.

A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

For more details about modules see also

  • exports makes the components, directives, and pipes available in modules that add this module to imports. exports can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.

  • entryComponents registers components for offline compilation so that they can be used with ViewContainerRef.createComponent(). Components used in router configurations are added implicitly.

TypeScript (ES2015) imports

import ... from 'foo/bar' (which may resolve to an index.ts) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.

Angular's @NgModule() imports and TypeScript import are entirely different concepts.

See also jDriven - TypeScript and ES6 import syntax

Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.

A div with auto resize when changing window width\height

Use vh attributes. It means viewport height and is a percentage. So height: 90vh would mean 90% of the viewport height. This works in most modern browsers.


div {
  height: 90vh;

You can forego the rest of your silly 100% stuff on the body.

If you have a header you can also do some fun things like take it into account by using the calc function in CSS.


div {
  height: calc(100vh - 50px);

This will give you 100% of the viewport height, minus 50px for your header.

Equivalent to AssemblyInfo in dotnet core/csproj

I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this


did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.

I solved this by adding an entry to the existing ItemGroup

   <Compile Remove="Common\**" />
   <Content Remove="Common\**" />
   <EmbeddedResource Remove="Common\**" />
   <None Remove="Common\**" />
   <!-- new added item -->
   <None Include="Properties\AssemblyInfo.cs" />

Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile action that usually comes with Assembly Info entry in proj files.

C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see The duplicate items were: 'AssemblyInfo.cs'

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

php form action php self

You can use an echo shortcut also instead of typing out "echo blah;" as shown below:

<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;

Get root view from current activity

if you are in a activity, assume there is only one root view,you can get it like this.

ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this

you can then cast it to your real class

or you could using


notice this will include the actionbar view, your view is below the actionbar view

How to copy a dictionary and only edit the copy

You can copy and edit the newly constructed copy in one go by calling the dict constructor with additional keyword arguments:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict(dict1, key2="WHY?!")
>>> dict1
{'key2': 'value2', 'key1': 'value1'}
>>> dict2
{'key2': 'WHY?!', 'key1': 'value1'}

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

I leave a very simple example:

var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
<script src=""></script>_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_

Good luck

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.

To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

Select columns in PySpark dataframe

You can use an array and unpack it inside the select:

cols = ['_2','_4','_5']*cols).show()

How to set a tkinter window to a constant size

Here is the most simple way.

import tkinter as tk

root = tk.Tk()

root.resizable(width=0, height=0)


I don't think there is anything to specify. It's pretty straight forward.

Why can I not switch branches?

Try this if you don't want any of the merges listed in git status:

git reset --merge

This resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

If a file that is different between <commit> and the index has unstaged changes -- reset is aborted.

More about this - & Doc link -

What is the meaning of "$" sign in JavaScript

That is most likely jQuery code (more precisely, JavaScript using the jQuery library).

The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:


How to select a drop-down menu value with Selenium using Python?

As per the HTML provided:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>

To select an <option> element from a menu you have to use the Select Class. Moreover, as you have to interact with the you have to induce WebDriverWait for the element_to_be_clickable().

To select the <option> with text as Mango from the you can use you can use either of the following Locator Strategies:

  • Using ID attribute and select_by_visible_text() method:

    from selenium import webdriver
    from import WebDriverWait
    from import By
    from import expected_conditions as EC
    from import Select
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
  • Using CSS-SELECTOR and select_by_value() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='fruits']"))))
  • Using XPATH and select_by_index() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))

CSS white space at bottom of page despite having both min-height and height tag

(class/ID):after {

Always works for me class or ID can be for a div or even body causing the white space.

How to use GNU Make on Windows?

While make itself is available as a standalone executable ( package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

Error in launching AVD with AMD processor

This resolves it for me:

Go to (C:\users\%USERNAME%\AppData\Local\Android\sdk, generally).

Then go to Extras -> Intel -> Hardware_Accelerated_Execution_Manager and run the file named "intelhaxm-android.exe".

In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled", go to your BIOS settings and enable Hardware Virtualization.

Restart your studio

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

Many ways to do this, you can use DATENAME and check for the actual strings 'Saturday' or 'Sunday'


Or use the day of the week and check for 1 (Sunday) or 7 (Saturday)


Is the sizeof(some pointer) always equal to four?

The reason the size of your pointer is 4 bytes is because you are compiling for a 32-bit architecture. As FryGuy pointed out, on a 64-bit architecture you would see 8.

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
  interval: 1000 * 10

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");


Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

Python Iterate Dictionary by Index

When I need to keep the order, I use a list and a companion dict:

color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
for i in range(0,len(fruit)): # or len(color)

The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:

fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
for i in range(0,len(fruitcolor)): 
for f, c in fruitcolor:

Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.

How do I use regex in a SQLite query?

A SQLite UDF in PHP/PDO for the REGEXP keyword that mimics the behavior in MySQL:

    function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
        if (isset($pattern, $data) === true)
            return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);

        return null;

The u modifier is not implemented in MySQL, but I find it useful to have it by default. Examples:

SELECT * FROM "table" WHERE "name" REGEXP 'sql(ite)*';
SELECT * FROM "table" WHERE regexp('sql(ite)*', "name", '#', 's');

If either $data or $pattern is NULL, the result is NULL - just like in MySQL.

Generating a unique machine id

What about just using the UniqueID of the processor?

Easy way to make a confirmation dialog in Angular?

In order to reuse a single confirmation dialog implementation in a multi-module application, the dialog must be implemented in a separate module. Here's one way of doing this with Material Design and FxFlex, though both of those can be trimmed back or replaced.

First the shared module (./app.module.ts):

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {MatDialogModule, MatSelectModule} from '@angular/material';
import {ConfirmationDlgComponent} from './confirmation-dlg.component';
import {FlexLayoutModule} from '@angular/flex-layout';

   imports: [
   declarations: [
   exports: [
   entryComponents: [ConfirmationDlgComponent]

export class SharedModule {

And the dialog component (./confirmation-dlg.component.ts):

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material';

   selector: 'app-confirmation-dlg',
   template: `
      <div fxLayoutAlign="space-around" class="title colors" mat-dialog-title>{{data.title}}</div>
      <div class="msg" mat-dialog-content>
      <a href="#"></a>
      <mat-dialog-actions fxLayoutAlign="space-around">
         <button mat-button [mat-dialog-close]="false" class="colors">No</button>
         <button mat-button [mat-dialog-close]="true" class="colors">Yes</button>
   styles: [`
      .title {font-size: large;}
      .msg {font-size: medium;}
      .colors {color: white; background-color: #3f51b5;}
      button {flex-basis: 60px;}
export class ConfirmationDlgComponent {
   constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}

Then we can use it in another module:

import {FlexLayoutModule} from '@angular/flex-layout';
import {NgModule} from '@angular/core';
import {GeneralComponent} from './general/general.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {CommonModule} from '@angular/common';
import {MaterialModule} from '../../material.module';

   declarations: [
   imports: [
   providers: []
export class SystemAdminModule {}

The component's click handler uses the dialog:

import {Component} from '@angular/core';
import {ConfirmationDlgComponent} from '../../../shared/confirmation-dlg.component';
import {MatDialog} from '@angular/material';

   selector: 'app-general',
   templateUrl: './general.component.html',
   styleUrls: ['./general.component.css']
export class GeneralComponent {

   constructor(private dialog: MatDialog) {}

   onWhateverClick() {
      const dlg =, {
         data: {title: 'Confirm Whatever', msg: 'Are you sure you want to whatever?'}

      dlg.afterClosed().subscribe((whatever: boolean) => {
         if (whatever) {

   whatever() {
      console.log('Do whatever');

Just using the; as you did won't return you an object whose events you can subscribe to which is why you can't get it to do something. This code creates and opens a dialog whose events we can subscribe to.

If you trim back the css and html this is really a simple component, but writing it yourself gives you control over its design and layout whereas a pre-written component will need to be much more heavyweight to give you that control.

http://localhost/phpMyAdmin/ unable to connect

Try: localhost:8080/phpmyadmin/

Capture Image from Camera and Display in Activity

Please, follow this example with this implementation by using Kotlin and Andoirdx support:

        file = getPhotoFile()
        val uri: Uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
        captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri)

        val camaraActivities: List<ResolveInfo> = applicationContext.getPackageManager().queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)

        for (activity in camaraActivities) {
            applicationContext.grantUriPermission(activity.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

        startActivityForResult(captureImage, REQUEST_PHOTO)

And the activity result:

if (requestCode == REQUEST_PHOTO) {
        val uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
        applicationContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        imageView1.viewTreeObserver.addOnGlobalLayoutListener {
            width = imageView1.width
            height = imageView1.height
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
            val size = Point()
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , size.x , size.y))


You can get more detail in

I hope it helps you!

Unicode character as bullet for list-item in CSS

Today, there is a ::marker option. so,

li::marker {
  content: "\2605";

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I have that problem and my solution is going source folder and run command line: mvn clean install -DskipTests eclipse:eclipse then return eclipse workspace and refresh project. Hope that help!

How to read text files with ANSI encoding and non-English letters?

using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250)))  ////File.Create(path)
            writer.Write("Sample Text");

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("", headers={"content-type":"text"})

Unknown column in 'field list' error on MySQL Update query

Try using different quotes for "y" as the identifier quote character is the backtick (“`”). Otherwise MySQL "thinks" that you point to a column named "y".

See also MySQL 5 Documentation

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

Calculating how many minutes there are between two times

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.

Multiple rows to one comma-separated value in Sql Server

Test Data

INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)


       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t

Result Set

¦ ID ¦     List_Output     ¦
¦  1 ¦  100, 200, 300, 400 ¦

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);

SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1

Result Set

¦ ID ¦     List_Output     ¦
¦  1 ¦  100, 200, 300, 400 ¦

How to find an object in an ArrayList by property

In Java8 you can use streams:

public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) {
    return -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null);

Additionally, in case you have many different objects (not only Carnet) or you want to find it by different properties (not only by cideIsin), you could build an utility class, to ecapsulate this logic in it:

public final class FindUtils {
    public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {

public final class CarnetUtils {
    public static Carnet findByCodeTitre(Collection<Carnet> listCarnet, String codeTitre) {
        return FindUtils.findByProperty(listCarnet, carnet -> codeTitre.equals(carnet.getCodeTitre()));

    public static Carnet findByNomTitre(Collection<Carnet> listCarnet, String nomTitre) {
        return FindUtils.findByProperty(listCarnet, carnet -> nomTitre.equals(carnet.getNomTitre()));

    public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsin) {
        return FindUtils.findByProperty(listCarnet, carnet -> codeIsin.equals(carnet.getCodeIsin()));

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
    local('Green Web'),

There is a more elaborate description of what to do here.

How to save username and password in Git?

Attention: This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.


git config --global credential.helper store


git pull

provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.

If you want to change the password later

git pull

Will fail, because the password is incorrect, git then removes the offending user+password from the ~/.git-credentials file, so now re-run

git pull

to provide a new password so it works as earlier.

Android - default value in editText

You can use text property in your xml file for particular Edittext fields. For example :


like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.

In Another way just you get the particular Edittext field id in activity class and set text to that one.

Another way = programmatically


EditText username=(EditText)findViewById(;


How to clear an EditText on click?

((EditText) findViewById("");
((EditText) findViewById("");

css3 text-shadow in IE9

Yes, but not how you would imagine. According to caniuse (a very good resource) there is no support and no polyfill available for adding text-shadow support to IE9. However, IE has their own proprietary text shadow (detailed here).

Example implementation, taken from their website (works in IE5.5 through IE9):

p.shadow { 
    filter: progid:DXImageTransform.Microsoft.Shadow(color=#0000FF,direction=45);

For cross-browser compatibility and future-proofing of code, remember to also use the CSS3 standard text-shadow property (detailed here). This is especially important considering that IE10 has officially announced their intent to drop support for legacy dx filters. Going forward, IE10+ will only support the CSS3 standard text-shadow.

JSONObject - How to get a value?

If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:

public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
    String finalValue = "";
    if (jObj == null) {
        return "";

    Iterator<String> keyItr = jObj.keys();
    Map<String, String> map = new HashMap<>();

    while(keyItr.hasNext()) {
        String key =;
        map.put(key, jObj.getString(key));

    for (Map.Entry<String, String> e : (map).entrySet()) {
        String key = e.getKey();
        if (key.equalsIgnoreCase(findKey)) {
            return jObj.getString(key);

        // read value
        Object value = jObj.get(key);

        if (value instanceof JSONObject) {
            finalValue = recurseKeys((JSONObject)value, findKey);

    // key is not found
    return finalValue;


JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");

Using Map code from

Converting Symbols, Accent Letters to English Alphabet

There is no easy or general way to do what you want because it is just your subjective opinion that these letters look loke the latin letters you want to convert to. They are actually separate letters with their own distinct names and sounds which just happen to superficially look like a latin letter.

If you want that conversion, you have to create your own translation table based on what latin letters you think the non-latin letters should be converted to.

(If you only want to remove diacritial marks, there are some answers in this thread: How do I remove diacritics (accents) from a string in .NET? However you describe a more general problem)

Difference between abstraction and encapsulation?

Another example:

Suppose I created an immutable Rectangle class like this:

class Rectangle {
  Rectangle(int width, int height) : width_(width), height_(height) {}
  int width() const { return width_; }
  int height() const { return height_; }

  int width_;
  int height_;

Now it's obvious that I've encapsulated width and height (access is somehow restricted), but I've not abstracted anything (okay, maybe I've ignored where the rectangle is located in the coordinates space, but this is a flaw of the example).

Good abstraction usually implies good encapsulation.

An example of good abstraction is a generic database connection class. Its public interface is database-agnostic, and is very simple, yet allows me to do what I want with the connection. And you see? There's also encapsulation there, because the class must have all the low-level handles and calls inside.

Linux: copy and create destination dir if it does not exist

install -D file -m 644 -t /path/to/copy/file/to/is/very/deep/there

Routing HTTP Error 404.0 0x80070002

Having this in Global.asax.cs solved it for me.

protected void Application_Start()

php: catch exception and continue execution, is it possible?

An old question, but one I had in the past when coming away from VBA scipts to php, where you could us "GoTo" to re-enter a loop "On Error" with a "Resume" and away it went still processing the function.
In php, after a bit of trial and error, I now use nested try{} catch{} for critical versus non critical processes, or even for interdependent class calls so I can trace my way back to the start of the error. e.g. if function b is dependant on function a, but function c is a nice to have but should not stop the process, and I still want to know the outcomes of all 3 regardless, here's what I do:

//set up array to capture output of all 3 functions
$resultArr = array(array(), array(), array());

// Loop through the primary array and run the functions 
foreach($x as $key => $val)
        $resultArr[$key][0][] = a($key); 
        $resultArr[$key][1][] = b($val);
        { // If successful, output of c() is captured
            $resultArr[$key][2][] = c($key, $val);
        catch(Exception $ex)
        { // If an error, capture why c() failed
            $resultArr[$key][2][] = $ex->getMessage();
    catch(Exception $ex)
    { // If critical functions a() or b() fail, we catch the reason why
        $criticalError = $ex->getMessage();

Now I can loop through my result array for each key and assess the outcomes. If there is a critical failure for a() or b().
I still have a point of reference on how far it got before a critical failure occurred within the $resultArr and if the exception handler is set correctly, I know if it was a() or b() that failed.
If c() fails, loop keeps going. If c() failed at various points, with a bit of extra post loop logic I can even find out if c() worked or had an error on each iteration by interrogating $resultArr[$key][2].

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

How to use "/" (directory separator) in both Linux and Windows in Python?

Don't build directory and file names your self, use python's included libraries.

In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

Your example would be

p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')

How to add action listener that listens to multiple buttons

I use "e.getActionCommand().contains(CharSecuence s)", since I´m coming from an MVC context, and the Button is declared in the View class, but the actionPerformed call occurs in the controller.

public View() {
    buttonPlus = new Button("+");
    buttonMinus = new Button("-");

public void addController(ActionListener controller) {

My controller class implements ActionListener, and so, when overriding actionPerformed:

public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().contains("+")) {
        //do some action on the model
    } else if (e.getActionCommand().contains("-")) {
       //do some other action on the model

I hope this other answer is also useful.

Align DIV to bottom of the page

Right I think I know what you mean so lets see....


<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>


body {
div {
    outline: 1px solid;
#con {
#content {
   height: 1000px; /* Changed this height */
#footer {

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.


This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.


So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

Python pip install fails: invalid command egg_info

pip install -U setuptools and easy_install was putting egg-info in the wrong directory.

Then I just reinstalled apt-get install python-dev. Let me install the drivers I want after that

Async await in linq select

With current methods available in Linq it looks quite ugly:

var tasks = items.Select(
    async item => new
        Item = item,
        IsValid = await IsValid(item)
var tuples = await Task.WhenAll(tasks);
var validItems = tuples
    .Where(p => p.IsValid)
    .Select(p => p.Item)

Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.

Making a PowerShell POST request if a body param starts with '@'

@Frode F. gave the right answer.

By the Way Invoke-WebRequest also prints you the 200 OK and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod which is lighter.

Also, keep in mind that you need to use | ConvertTo-Json for the body only, not the header:

$body = @{
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

and you can then append a | ConvertTo-HTML at the end of the request for better readability

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

how to concat two columns into one with the existing column name in mysql?

Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.

You can use the SQL statement something like:


BTW, why couldn't you use FullName instead of FirstName? Like this:


Android - save/restore fragment state

I'm not quite sure if this question is still bothering you, since it has been several months. But I would like to share how I dealt with this. Here is the source code:

int FLAG = 0;
private View rootView;
private LinearLayout parentView;

 * The fragment argument representing the section number for this fragment.
private static final String ARG_SECTION_NUMBER = "section_number";

 * Returns a new instance of this fragment for the given section number.
public static Fragment2 newInstance(Bundle bundle) {
    Fragment2 fragment = new Fragment2();
    Bundle args = bundle;
    return fragment;

public Fragment2() {


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
        rootView = inflater.inflate(R.layout.fragment_create_new_album, container, false);
    parentView=new LinearLayout(getActivity());

    return parentView;

/* (non-Javadoc)
 * @see
public void onDestroy() {
    // TODO Auto-generated method stub

/* (non-Javadoc)
 * @see
public void onStart() {
    // TODO Auto-generated method stub

/* (non-Javadoc)
 * @see
public void onStop() {
    // TODO Auto-generated method stub
        Bundle savedInstance=getArguments();
        LinearLayout viewParent;

        viewParent= (LinearLayout) rootView.getParent();


public void onPause() {

public void onResume() {

And here is the MainActivity:

 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;

 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.

public static boolean fragment2InstanceExists=false;
public static Fragment2 fragment2=null;

protected void onCreate(Bundle savedInstanceState) {

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
    mTitle = getTitle();

    // Set up the drawer.
            (DrawerLayout) findViewById(;

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    case 0:
        fragmentTransaction.replace(, Fragment1.newInstance(position+1)).commit();
    case 1:

        Bundle bundle=new Bundle();

        fragmentTransaction.replace(, fragment2).commit();

    case 2:
        fragmentTransaction.replace(, FolderExplorerFragment.newInstance(position+1)).commit();

The parentView is the keypoint. Normally, when onCreateView, we just use return rootView. But now, I add rootView to parentView, and then return parentView. To prevent "The specified child already has a parent. You must call removeView() on the ..." error, we need to call parentView.removeView(rootView), or the method I supplied is useless. I also would like to share how I found it. Firstly, I set up a boolean to indicate if the instance exists. When the instance exists, the rootView will not be inflated again. But then, logcat gave the child already has a parent thing, so I decided to use another parent as a intermediate Parent View. That's how it works.

Hope it's helpful to you.

Determine a user's timezone

Here is a robust JavaScript solution to determine the time zone the browser is in.

>>> var timezone = jstz.determine();

How can I get a list of all values in select box?





Link to fiddle

And I agree with Abraham - you might want to use text instead of value

The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

Pass in an enum as a method parameter

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
    file = new File
       Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions

    return file.Id;

How can I change the default Mysql connection timeout when connecting through python?

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value


Then set it according to your needs.


How to convert string to integer in UNIX

An answer that is not limited to the OP's case

The title of the question leads people here, so I decided to answer that question for everyone else since the OP's described case was so limited.


I finally settled on writing a function.

  1. If you want 0 in case of non-int:
int(){ printf '%d' ${1:-} 2>/dev/null || :; }
  1. If you want [empty_string] in case of non-int:
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
  1. If you want find the first int or [empty_string]:
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
  1. If you want find the first int or 0:
# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }

If you want to get a non-zero status code on non-int, remove the ||: (aka or true) but leave the ;


# Wrapped in parens to call a subprocess and not `set` options in the main bash process
# In other words, you can literally copy-paste this code block into your shell to test
( set -eu;
    tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" )
    test(){ echo; type int; for test in "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }

    int(){ printf '%d' ${1:-} 2>/dev/null||:; };

    int(){ expr 0 + ${1:-} 2>/dev/null||:; }

    int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }

    int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }

    # unexpected inconsistent results from `bc`
    int(){ bc<<<"${1:-}" 2>/dev/null||:; }

Test output

int is a function
int ()
    printf '%d' ${1:-} 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '0' from '6foo'
got '0' from 'bar7'
got '0' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument

int is a function
int ()
    expr 0 + ${1:-} 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '' from 'bar7'
got '' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument

int is a function
int ()
    expr ${1:-} : '[^0-9]*\([0-9]*\)' 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument

int is a function
int ()
    printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null) || :
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument

int is a function
int ()
    bc <<< "${1:-}" 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '0' from 'bar7'
got '' from 'foo8.9bar'
got '0' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument


I got sent down this rabbit hole because the accepted answer is not compatible with set -o nounset (aka set -u)

# This works
$ ( number="3"; string="foo"; echo $((number)) $((string)); )
3 0

# This doesn't
$ ( set -u; number="3"; string="foo"; echo $((number)) $((string)); )
-bash: foo: unbound variable

Moving from one activity to another Activity in Android

button1 in activity2

code written in activity 2

button1.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View v)
            // starting background task to update product               
            Intent fp=new Intent(getApplicationContext(),activity1.class);              

This might help

Where is the syntax for TypeScript comments documented?

TypeScript is a strict syntactical superset of JavaScript hence

  • Single line comments start with //
  • Multi-line comments start with /* and end with */

Is it possible to select the last n items with nth-child?

nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.

MongoDB query with an 'or' condition


{"name": {'$regex' : '.*' + "Ravi" + '.*'}},
"$or": [{
    'added_by':"[email protected]"
}, {
    'added_by':"[email protected]"


How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

RoBorg is correct, but I wanted to add a side note.

In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.

Imagine this page layout:

  IframedPage1.html   (named "foo")
  IframedPage2.html   (named "bar")
    IframedPage3.html (named "baz")

Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.

If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).

Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.

if(window.parent && == 'bar'){
  window.parent.location = self.location;

So far so good. Now comes the bug.

Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.

When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".

The good news, is that checking:

if(self == top){
  //this returns true!

in that new tab does return true, and thus you can test for this odd condition.

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]

Getting execute permission to xp_cmdshell

I want to complete the answer from tchester.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database

(3) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
--       Don't include square brackets around Domain\TestUser.

(5) Grant control server permission to user

USE master;

Getting index value on razor foreach

All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

public int Position {get; set}

In your view model builder you set the position 1 through 4.

BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

<div class="@Model.GridCSS">

Move the switch statement to your view model builder and populate the CSS class there.

How to make Twitter Bootstrap menu dropdown on hover rather than click

Use this code to open the submenu on mousehover (desktop only):

$('ul.nav li.dropdown').hover(function () {
    if ($(window).width() > 767) {
}, function () {
    if ($(window).width() > 767) {

And if you want the first level menu to be clickable, even on mobile add this:

    $('.dropdown-toggle').click(function() {
    if ($(this).next('.dropdown-menu').is(':visible')) {
        window.location = $(this).attr('href');

The submenu (dropdown-menu) will be opened with mousehover on desktop, and with click/touch on mobile and tablet. Once the submenu was open, a second click will let you open the link. Thanks to the if ($(window).width() > 767), the submenu will take the full screen width on mobile.

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
   echo "You did not fill out the required fields.";

How to create a video from images with FFmpeg?

To create frames from video:

ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner

Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss & -t)

Then create video from image/frames eg.:

ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4

How do I cancel a build that is in progress in Visual Studio?

The "pause" command was a function button underneath my right shift key, so the below combination of keys did the trick for me.

Ctrl + Fn + Shift

python date of the previous month

Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)

year = today.year
month = today.month

nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
    nm[1] = 12
    nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
    pm[1] = 12
    pm[0] -= 1

next_month = nm
previous_month = pm

Undo a Git merge that hasn't been pushed yet

Strategy: Create a new branch from where everything was good.

Rationale: Reverting a merge is hard. There are too many solutions, depending on many factors such as whether you've committed or pushed your merge or if there were new commits since your merge. Also you still need to have a relatively deep understanding of git to adapt these solutions to your case. If you blindly follow some instructions, you can end up with an "empty merge" where nothing will be merged, and further merge attempts will make Git tell you "Already up to date".


Let's say you want to merge dev into feature-1.

  1. Find the revision that you want to receive the merge:

    git log --oneline feature-1
    a1b2c3d4 Merge branch 'dev' into 'feature-1' <-- the merge you want to undo
    e5f6g7h8 Fix NPE in the Zero Point Module <-- the one before the merge, you probably want this one
  2. Check it out (go back in time):

    git checkout e5f6g7h8
  3. Create a new branch from there and check it out:

    git checkout -b feature-1

Now you can restart your merge:

  1. Merge: git merge dev

  2. Fix your merge conflicts.

  3. Commit: git commit

  4. When you're satisfied with the results, delete the old branch: git branch --delete feature-1