Programs & Examples On #Demo

Anything related to "demo applications", i.e. programs that are meant to show to some audience the general appearance or purpose of an application, without being actually functional. Usually demos are either severely crippled versions of the application or have reduced functionality.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.


It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="">@meandave2020</a></p>" 

I submitted a pull request to update this.

Why am I getting Unknown error in line 1 of pom.xml?

Add <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> in property tag

problem resolve

How to compare oldValues and newValues on React Hooks useEffect?

For really simple prop comparison you can use useEffect to easily check to see if a prop has updated.

const myComponent = ({ prop }) => {
  useEffect(() => {
    ---Do stuffhere----
  }, [prop])

useEffect will then only run your code if the prop changes.

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    void initState() {
      _presenter = CryptoListPresenter(...);

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    children: <Widget>[
        alignment: Alignment.centerLeft,
        child: Text(
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.normal,
        alignment: Alignment.centerRight,
        child: Text(
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            fontWeight: FontWeight.normal,

Google Recaptcha v3 example demo

We use recaptcha-V3 only to see site traffic quality, and used it as non blocking. Since recaptcha-V3 doesn't require to show on site and can be used as hidden but you have to show recaptcha privacy etc links (as recommended)

Script Tag in Head

<script src="'SITE KEY' async defer></script>

Note: "async defer" make sure its non blocking which is our specific requirement

JS Code:

    ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("SITE KEY").then(function(token) {
                    type: "POST",
                    url: `https://api.${window.appInfo.siteDomain}/v1/recaptcha/score`,
                    data: {
                        "token" : token,
                    success: function(data) {
                        if(data.response.success) {
                            window.recaptchaScore = data.response.score;
                            console.log('user score ' + data.response.score)
                    error: function() {
                        console.log('error while getting google recaptcha score!')


HTML/Css Code:

there is no html code since our requirement is just to get score and don't want to show recaptcha badge.

Backend - Laravel Code:


Route::post('/recaptcha/score', 'Api\\ReCaptcha\\RecaptchaScore@index');


class RecaptchaScore extends Controller
    public function index(Request $request)
        $score = null;

        $response = (new Client())->request('post', '', [
            'form_params' => [
                'response' => $request->get('token'),
                'secret' => 'SECRET HERE',

        $score = json_decode($response->getBody()->getContents(), true);

        if (!$score['success']) {
            Log::warning('Google ReCaptcha Score', [
                'class' => __CLASS__,
                'message' => json_encode($score['error-codes']),

        return [
            'response' => $score,

we get back score and save in variable which we later user when submit form.


How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

      uses-material-design: true
      # add this
        - images/profile.jpg
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using


Not able to change TextField Border Color

enabledBorder: OutlineInputBorder(
  borderRadius: BorderRadius.circular(10.0),
  borderSide: BorderSide(color:

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

You need to set JDK 1.5 to your project and also all dependent project or jar file should also compiled with JDK 1.5

You should not use <Link> outside a <Router>

I kinda come up with this code :

import React from 'react';
import { render } from 'react-dom';

// import componentns
import Main from './components/Main';
import PhotoGrid from './components/PhotoGrid';
import Single from './components/Single';

// import react router
import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'

class MainComponent extends React.Component {
  render() {
    return (
        <BrowserRouter history={browserHistory}>
          <Route path="/" component={Main} >
            <IndexRoute component={PhotoGrid}></IndexRoute>
            <Route path="/view/:postId" component={Single}></Route>

render(<MainComponent />, document.getElementById('root'));

I think the error was because you were rendering the Main component, and the Main component didn't know anything about Router, so you have to render its father component.

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Although most of these previous answers will work, I suggest you explore the provider or BloC architectures, both of which have been recommended by Google.

In short, the latter will create a stream that reports to widgets in the widget tree whenever a change in the state happens and it updates all relevant views regardless of where it is updated from.

Here is a good overview you can read to learn more about the subject:

Changing directory in Google colab (breaking out of the python interpreter)

Use os.chdir. Here's a full example:


!mkdir abc
!echo "file" > abc/123.txt

import os

# Now the directory 'abc' is the current working directory.
# and will show 123.txt.

'mat-form-field' is not a known element - Angular 5 & Material2

When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

Please import below:

import { MatInputModule } from '@angular/material';

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

it seems when target sdk is pie (api level 28.0) and windowIsTranslucent is true

<item name="android:windowIsTranslucent">true</item>

and you try to access orientation. problem comes with android oreo 8.0 (api level 26) there are two ways to solve this

  1. remove the orientation
  2. or set windowIsTranslucent to false

if you are setting orientation in manifest like this


or in activity class like this


remove form both places.

and observed when u set windowIsTranslucent to true, it takes orientation from parent activity.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

This worked for me!


//Add this....Keep both version same

compileOptions {                                                          
    sourceCompatibility JavaVersion.VERSION_1_8 
    targetCompatibility JavaVersion.VERSION_1_8

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

How to work with progress indicator in flutter?

isloading? progressIos:Container()

progressIos(int i) {
    return Container(
        color: i == 1
            ? AppColors.liteBlack
            : i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
        child: Center(child: CupertinoActivityIndicator()));

Kubernetes Pod fails with CrashLoopBackOff

I had similar situation. I found that one of my config maps was duplicated. I had two configmaps for the same namespace. One had the correct namespace reference, the other was pointing to the wrong namespace.

I deleted and recreated the configmap with the correct file (or fixed file). I am only using one, and that seemed to make the particular cluster happier.

So I would check the files for any typos or duplicate items that could be causing conflict.

Load local images in React.js

In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';

Before React V17.0.1 we can use require(../) and it is working fine.

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
          } finally {
            junit 'nosetests.xml'
    stage ('Speak') {
        echo "Hello, CONDITIONAL"

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

The website was running fine then suddenly it started to display this same error 404 message (The origin server did not find a current representation for the target resource or is not willing to disclose that one exists), Perhaps because of switching servers back and forward from Tomcat 9 to 8 and 7

In my case, i only had to update the project which was causing this error then restart the specific tomcat version. You may also need to Maven Clean and Maven Install after the "Maven Update Project"

Select Maven Update ProjectUpdate and Refresh Workspace

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.

To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */

jsFiddle demo

1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Your password does not satisfy the current policy requirements

You have to change MySQL password policy to LOW.

login as root

mysql -u root -p

change policy

SET GLOBAL validate_password_policy=LOW;


SET GLOBAL validate_password_policy=0;



restart MySQL service

sudo service mysql restart

You have to change the MySQL password policy to Low = 0 / Medium = 1 / High = 2.

SET GLOBAL validate_password_policy=0;
SET GLOBAL validate_password_policy=1;    
SET GLOBAL validate_password_policy=2;

CORS: credentials mode is 'include'

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>


Then inside of Configure:

app.UseMvc(routes =>
        // Routing code here

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

Node.js ES6 classes with require

In class file you can either use:

module.exports = class ClassNameHere {
 print() {
  console.log('In print function');

or you can use this syntax

class ClassNameHere{
  console.log('In print function');

module.exports = ClassNameHere;

On the other hand to use this class in any other file you need to do these steps. First require that file using this syntax: const anyVariableNameHere = require('filePathHere');

Then create an object const classObject = new anyVariableNameHere();

After this you can use classObject to access the actual class variables

Datatables Select All Checkbox

You can use Checkboxes extension for jQuery Datatables.

var table = $('#example').DataTable({
   'ajax': '',
   'columnDefs': [
         'targets': 0,
         'checkboxes': {
            'selectRow': true
   'select': {
      'style': 'multi'
   'order': [[1, 'asc']]

See this example for code and demonstration.

See Checkboxes project page for more examples and documentation.

Google API authentication: Not valid origin for the client

Credentials do not work if API is not enabled. In my case the next steps were needed:

  1. Go to
  2. Enter 'People'
  3. From the result choose 'Google People API'
  4. Click 'Enable'

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
<link rel="stylesheet" href="" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      Line 2_x000D_
      Line 3_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_

Bootstrap 4 Center Vertical and Horizontal Alignment

This is working in IE 11 with Bootstrap 4.3. While the other answers were not working in IE11 in my case.

 <div class="row mx-auto justify-content-center align-items-center flex-column ">
    <div class="col-6">Something </div>

Can't bind to 'routerLink' since it isn't a known property

This problem is because you did not import the module

import {RouterModule} from '@angular/router';

And you must declare this modulce in the import section


Plotting images side by side using matplotlib

You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)

For more info have a look here:

For complex layouts, you should consider using gridspec:

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

My pod kept crashing and I was unable to find the cause. Luckily there is a space where kubernetes saves all the events that occurred before my pod crashed.
(#List Events sorted by timestamp)

To see these events run the command:

kubectl get events --sort-by=.metadata.creationTimestamp

make sure to add a --namespace mynamespace argument to the command if needed

The events shown in the output of the command showed my why my pod kept crashing.

How to declare a Fixed length Array in TypeScript

Actually, You can achieve this with current typescript:

type Grow<T, A extends Array<T>> = ((x: T, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type GrowToSize<T, A extends Array<T>, N extends number> = { 0: A, 1: GrowToSize<T, Grow<T, A>, N> }[A['length'] extends N ? 0 : 1];

export type FixedArray<T, N extends number> = GrowToSize<T, [], N>;


// OK
const fixedArr3: FixedArray<string, 3> = ['a', 'b', 'c'];

// Error:
// Type '[string, string, string]' is not assignable to type '[string, string]'.
//   Types of property 'length' are incompatible.
//     Type '3' is not assignable to type '2'.ts(2322)
const fixedArr2: FixedArray<string, 2> = ['a', 'b', 'c'];

// Error:
// Property '3' is missing in type '[string, string, string]' but required in type 
// '[string, string, string, string]'.ts(2741)
const fixedArr4: FixedArray<string, 4> = ['a', 'b', 'c'];

EDIT (after a long time)

This should handle bigger sizes (as basically it grows array exponentially until we get to closest power of two):

type Shift<A extends Array<any>> = ((...args: A) => void) extends ((...args: [A[0], ...infer R]) => void) ? R : never;

type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExpRev<[...A, ...P[0]], N, P>,
  1: GrowExpRev<A, N, Shift<P>>
}[[...A, ...P[0]][N] extends undefined ? 0 : 1];

type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExp<[...A, ...A], N, [A, ...P]>,
  1: GrowExpRev<A, N, P>
}[[...A, ...A][N] extends undefined ? 0 : 1];

export type FixedSizeArray<T, N extends number> = N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T, T], N, [[T]]>;

Checking version of angular-cli that's installed?


ng v


ng --version

tell you the current angular cli version number

enter image description here

How do I mount a host directory as a volume in docker compose

Checkout their documentation

From the looks of it you could do the following on your docker-compose.yml

    - ./:/app

Where ./ is the host directory, and /app is the target directory for the containers.

Previous documentation source now leads to version history, you'll have to select the version of compose you're using and look for the reference.

For the lazy – v3 / v2 / v1

Side note: Syntax remains the same for all versions as of this edit

Git merge with force overwrite

This merge approach will add one commit on top of master which pastes in whatever is in feature, without complaining about conflicts or other crap.

enter image description here

Before you touch anything

git stash
git status # if anything shows up here, move it to your desktop

Now prepare master

git checkout master
git pull # if there is a problem in this step, it is outside the scope of this answer

Get feature all dressed up

git checkout feature
git merge --strategy=ours master

Go for the kill

git checkout master
git merge --no-ff feature

nodemon command is not recognized in terminal for node js server

Just had the same problem after creating a new user profile on my development machine.

The problem was that I wasn't running the console (command prompt\powershell ISE) as admin.

Running as admin solved this problem for me.

File Upload In Angular?

This is useful tutorial, how to upload file using the ng2-file-upload and WITHOUT ng2-file-upload.

For me it helps a lot.

At the moment, tutorial contains a couple of mistakes:

1- Client should have same upload url as a server, so in app.component.ts change line

const URL = 'http://localhost:8000/api/upload';


const URL = 'http://localhost:3000';

2- Server send response as 'text/html', so in app.component.ts change

.post(URL, formData).map((res:Response) => res.json()).subscribe(
  //map the success function and alert the response
  (success) => {
  (error) => alert(error))


.post(URL, formData)  
.subscribe((success) => alert('success'), (error) => alert(error));

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

If you use JDK 1.8.0_201 or latest try it with older JDK.

I have same issue with JDK1.8.0_201, however it works with JDK1.8.0_101 without any code change.

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" +}

This will use the string literal #demo and concatenate it to the value of This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:


This will basically substitute the value of, concatenating it to #demo. It is equivalent to doing: "#demo" +

Error: Unexpected value 'undefined' imported by the module

I had this error because I had an index.ts file in the root of my app that was exporting my app.component.ts. So I thought I could do the following:

import { AppComponent } from './';

This worked and gave me no red squiggly lines and even intellisense brings up AppComponent when you start typing it. But come to find out it was causing this error. After I changed it to:

import { AppComponent } from './app.component';

The error went away.

@viewChild not working - cannot read property nativeElement of undefined

The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.

Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.

@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;

Now, the interesting part is the static value, which by definition says

  • static - True to resolve query results before change detection runs

Now for rendering a map, I used the following ,

@ViewChild('map', { static: true }) mapElement: any;
  map: google.maps.Map;

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size


plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

When to use React "componentDidUpdate" method?

I have used componentDidUpdate() in highchart.

Here is a simple example of this component.

import React, { PropTypes, Component } from 'react';
window.Highcharts = require('highcharts');

export default class Chartline extends React.Component {
  constructor(props) {
    this.state = {
      chart: ''

  public componentDidUpdate() {
    // console.log(this.props.candidate, 'this.props.candidate')
    if (this.props.category) {
      const category = this.props.category ? this.props.category : {};
      console.log('category', category);
      window.Highcharts.chart('jobcontainer_' + category._id, {
        title: {
          text: ''
        plotOptions: {
          series: {
            cursor: 'pointer'
        chart: {
          defaultSeriesType: 'spline'
        xAxis: {
          // categories: candidate.dateArr,
          categories: ['Day1', 'Day2', 'Day3', 'Day4', 'Day5', 'Day6', 'Day7'],
          showEmpty: true
        labels: {
          style: {
            color: 'white',
            fontSize: '25px',
            fontFamily: 'SF UI Text'
        series: [
            name: 'Low',
            color: '#9B260A',
            data: category.lowcount
            name: 'High',
            color: '#0E5AAB',
            data: category.highcount
            name: 'Average',
            color: '#12B499',
            data: category.averagecount
  public render() {
    const category = this.props.category ? this.props.category : {};
    console.log('render category', category);
    return <div id={'jobcontainer_' + category._id} style={{ maxWidth: '400px', height: '180px' }} />;

React Native fetch() Network Request Failed

if you use docker for the REST api, a working case for me was to replace hostname: http://demo.test/api with the machine ip address: http://x.x.x.x/api . You can get the IP from checking what ipv4 you have on your wireless network. You should have also the wifi from phone on.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page

A small notebook to illustrate this: demo

The code itself:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="" type="text/css" rel="stylesheet" />
       <script src=""></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"

Angular 2 Date Input not binding to date value

Angular 2 , 4 and 5 :

the simplest way : plunker

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

For me adding AppRoutingModule to my imports solved the problem.

    imports: [
        path: 'new-cmp',
        component: NewCmpComponent

How to dynamically add and remove form fields in Angular 2

addAccordian(type, data) { console.log(type, data);

let form = this.form;

if (!form.controls[type]) {
  let ownerAccordian = new FormArray([]);
  const group = new FormGroup({});
    this.applicationService.createControlWithGroup(data, group)
  form.controls[type] = ownerAccordian;
} else {
  const group = new FormGroup({});
    this.applicationService.createControlWithGroup(data, group)


Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. Set align-self to center.

align-self: center;

See documentation here: align-self

How to unset (remove) a collection element after fetching it?

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

If you have the key already you can just use PHP unset.

I prefer this, because it clearly modifies the collection in place, and is easy to remember.

foreach ($collection as $key => $value) {

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the package and your LoginBean class is in the package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Allow Access-Control-Allow-Origin header using HTML5 fetch API

This worked for me :

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues:

Start Proxy:

lcp --proxyUrl

 Proxy Active 

 Proxy Url:
 Proxy Partial: proxy
 PORT: 8010

Then in your client code, new API endpoint:


End result will be a request to without the CORS issues!

Connection refused on docker container

Command EXPOSE in your Dockerfile lets you bind container's port to some port on the host machine but it doesn't do anything else. When running container, to bind ports specify -p option.

So let's say you expose port 5000. After building the image when you run the container, run docker run -p 5000:5000 name. This binds container's port 5000 to your laptop/computers port 5000 and that portforwarding lets container to receive outside requests.

This should do it.

How can moment.js be imported with typescript?

I've just noticed that the answer that I upvoted and commented on is ambiguous. So the following is exactly what worked for me. I'm currently on Moment 2.26.0 and TS 3.8.3:

In code:

import moment from 'moment';

In TS config:

  "compilerOptions": {
    "esModuleInterop": true,

I am building for both CommonJS and EMS so this config is imported into other config files.

The insight comes from this answer which relates to using Express. I figured it was worth adding here though, to help anyone who searches in relation to Moment.js, rather than something more general.

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any( | any(Den != 1), 0, 1))

Vue is not defined

try to fix type="JavaScript" to type="text/javascript" in you vue.js srcipt tag, or just remove it. Modern browsers will take script tag as javascript as default.

Could not autowire field:RestTemplate in Spring boot application

Depending on what technologies you're using and what versions will influence how you define a RestTemplate in your @Configuration class.

Spring >= 4 without Spring Boot

Simply define an @Bean:

public RestTemplate restTemplate() {
    return new RestTemplate();

Spring Boot <= 1.3

No need to define one, Spring Boot automatically defines one for you.

Spring Boot >= 1.4

Spring Boot no longer automatically defines a RestTemplate but instead defines a RestTemplateBuilder allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder as an argument in your @Bean method to create a RestTemplate:

public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here

Using it in your class

private RestTemplate restTemplate;

Reference Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

You can alternatively download winutils.exe from GITHub:

replace hadoop-2.7.1 with the version you want and place the file in D:\hadoop\bin

If you do not have access rights to the environment variable settings on your machine, simply add the below line to your code:

System.setProperty("hadoop.home.dir", "D:\\hadoop");

access key and value of object using *ngFor


In 6.1.0-beta.1 KeyValuePipe was introduced

<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
  {{ item.key }} - {{ item.value }}

Plunker Example

Previous version

Another approach is to create NgForIn directive that will be used like:

<div *ngFor="let key in obj">
   <b>{{ key }}</b>: {{ obj[key] }}

Plunker Example


  selector: '[ngFor][ngForIn]'
export class NgForIn<T> extends NgForOf<T> implements OnChanges {

  @Input() ngForIn: any;

  ngOnChanges(changes: NgForInChanges): void {
    if (changes.ngForIn) {
      this.ngForOf = Object.keys(this.ngForIn) as Array<any>;

      const change = changes.ngForIn;
      const currentValue = Object.keys(change.currentValue);
      const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
      changes.ngForOf =  new SimpleChange(previousValue, currentValue, change.firstChange);


nodemon not working: -bash: nodemon: command not found

I tried the following, and none worked:

npm uninstall nodemon

sudo npm uninstall -g nodemon

What did work was:

sudo npm install -g --force nodemon

ngFor with index as value in attribute

Just an update to this, Thierry's answer is still correct, but there has been an update to Angular2 with regards to:

<ul *ngFor="let item of items; let i = index" []="i">

The #i = index should now be let i = index


The *ngFor should be on the element you're wanting to foreach, so for this example it should be:

  <li *ngFor="let item of items; let i = index" []="i">{{item}}</li>


Angular 5

  <li *ngFor="let item of items; index as i" []="i">{{item}}</li>


Angular 7/8

<ul *ngFor="let item of items; index as i">
  <li []="i">{{item}}</li>

How to use code to open a modal in Angular 2?

The Way i used to do it without lots of coding is.. I have the hidden button with the id="employeeRegistered"

On my .ts file I import ElementRef from '@angular/core'

Then after I process everything on my (click) method do as follow:


then the modal displays as expected..

Google Maps JavaScript API RefererNotAllowedMapError

I struggled to make this work as well, but here are some pointers:

  • The URLs set as referrers include http, e.g.*
  • Google Maps JavaScript API was enabled
  • Billing was set-up on this account

Once all of this above was resolved, the maps displayed as expected.

How to center content in a bootstrap column?


<!-- unsupported by HTML5 -->
<div class="col-xs-1" align="center">

instead of

<div class="col-xs-1 center-block">

You can also use bootstrap 3 css:

<!-- recommended method -->
<div class="col-xs-1 text-center">

Bootstrap 4 now has flex classes that will center the content:

<div class="d-flex justify-content-center">
   <div>some content</div>

Note that by default it will be x-axis unless flex-direction is column

android: data binding error: cannot find symbol class


Your layout name is in snake_case.


Then your binding class name will be in CamelCase.

Also build project after creating layout. Sometimes it is not generated automatically.

Get current value when change select option - Angular2

For me, passing ($ as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2

<select (change)="onItemChange($event.value)">
    <option *ngFor="#value of values" [value]="value.key">

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):


<?php $years = range(1900, strftime("%Y", time())); ?>


  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>

As an added benefit, this works has a browser compatibility of a 100% ;-)

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

I had the same error, but in Ubuntu 14.04 inside Windows 10 (Bash on Ubuntu on Windows). All I did to overcome the error was to update the Creators update, which then allowed me to install 16.04 version of Ubuntu bash and then after installing newest version of node (by this steps) I installed also the newest version of npm and then the nodemon started to work properly.

IIS Config Error - This configuration section cannot be used at this path

Heres what worked for me, had a similar problem on my new laptop which had windows 10.

  • Search for "Turn windows features on or off"
  • Check "Internet Information Services"
  • Check "World Wide Web Services"
  • Check "Application Development Features"
  • Enable all items under this

try again, now it should work.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.

How to execute the start script with Nodemon

In package json:

"scripts": {
  "start": "node index",
  "dev": "nodemon index"

"devDependencies": {
  "nodemon": "^2.0.2"

And in the terminal for developing:

npm run dev

And for starting the server regular:

npm start

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  

revised demo


Spring Boot application can't resolve the org.springframework.boot package

I have encountered the same problem while my first Spring boot application.

In tutorial i could see following dependency to start sample application

  • Spring Boot 1.4.2.RELEASE
  • Maven 3
  • java 8

I have done the same, my Spring STS is recognizing all class but when i am annotating my main class with @SpringBootApplication it's not recognizing this class whereas i could see jar was available in the class path.

I have following to resolve issues

  • Replaced my Spring Boot 1.4.2.RELEASE to 1.5.3.RELEASE
  • Right click on project and -> Maven-> Download Resources
  • right click on project -> Maven-> Update project

After that it worked.


Change the Bootstrap Modal effect

.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
  padding:10px 20px;

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
        <div class="form-group">
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>

    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal

      <a class="btn btn-black " href="" target="_blank">View FullPage</a>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          <div class="modal-body">
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    $('#myModal').on('', function (e) {
      var anim = $('#entrance').val();
    $('#myModal').on('', function (e) {
      var anim = $('#exit').val();

.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
  padding:10px 20px;

How do I plot only a table in Matplotlib?

This is another option to write a pandas dataframe directly into a matplotlib table:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

ax.table(cellText=df.values, colLabels=df.columns, loc='center')


enter image description here

Deploying Maven project throws invalid LOC header (bad signature)

Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency

dependencies {
    checkstyle project(":module")

this error could happen, if module doesn't contain group and version, so in the module/build.gradle just need to be specified

plugins {
    id 'java-library'

group = "com.example"
version = "master-SNAPSHOT"

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause


RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

In my case I've had more then 5000 items in the list. My problem was that when scrolling the recycler view, sometimes the "onBindViewHolder" get called while "myCustomAddItems" method is altering the list.

My solution was to add "synchronized (syncObject){}" to all the methods that alter the data list. This way at any point at time only one method can read this list.

Unexpected token < in first line of HTML

I had the same issue. I published the angular/core application on iis.

To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

Server unable to read htaccess file, denying access to be safe

I had same problem on Fedora, and found that problem was selinux. to test that it is problem run command: sudo setenforce 0

Otherwise or change in file /etc/sysconfig/selinux


or add rules to selinux to allow http access

How can I run multiple npm scripts in parallel?

You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you'll need to manually stop it after all tests are finished.

This is an example for protractor testing through npm:

scripts: {
  "webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
  "protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
  "http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
  "test": "npm-run-all -p -r webdriver-start http-server protractor"

-p = Run commands in parallel.

-r = Kill all commands when one of them finishes with an exit code of zero.

Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.

Swift's guard keyword

From Apple documentation:

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.


guard condition else {


1. By using guard statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.

2. It was designed specifically for exiting a method or function early.

if you use if let below is the code how it looks.

  let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            if let  statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
                if let data = data {

                    //Process Data Here.
                    print("Data: \(data)")

                } else {
                    print("No data was returned by the request!")
            } else {
                print("Your request returned a status code other than 2XX!")
        } else {
            print("Error Info: \(error.debugDescription)")

Using guard you can transfer control out of a scope if one or more conditions aren't met.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            /* GUARD: was there an error? */
            guard (error == nil) else {
                print("There was an error with your request: \(error)")

            /* GUARD: Did we get a successful 2XX response? */
            guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2XX!")

            /* GUARD: was there any data returned? */
            guard let data = data else {
                print("No data was returned by the request!")

            //Process Data Here.
            print("Data: \(data)")


1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement

Why calling react setState method doesn't mutate the state immediately?

You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {
    await this.setState({value:});

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:


If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically.

Disable a link in Bootstrap

If what you're trying to do is disable an a link, there is no option to do this. I think you can find an answer that will work for you in this question here.

One option here is to use

<a href="/" onclick="return false;">123n</a>

Disabled href tag

Can't Autowire @Repository annotated interface in Spring Boot

It seems your @ComponentScan annotation is not set properly. Try :

@ComponentScan(basePackages = {""})

Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under package.

Also, you don't need both


The @SpringBootApplication annotation includes @EnableAutoConfiguration by default.

How to write a unit test for a Spring Boot Controller endpoint

Let assume i am having a RestController with GET/POST/PUT/DELETE operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.

@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {

    private AppService service;

    public MyAppResponse<AppEntity> get() throws Exception {

        MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
        service.getApp().stream().forEach(x -> response.addData(x));    
        return response;

    public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
        //Validation code       

        return ResponseEntity.ok(HttpStatus.OK);

    public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {

        //Validation code

        return ResponseEntity.ok(HttpStatus.OK);

    public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {


        return ResponseEntity.ok(HttpStatus.OK);


@SpringBootTest(classes = Main.class)
public abstract class BaseTest {
   protected MockMvc mvc;
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);

public class AppControllerTest extends BaseTest {

    private IIdmsService service;

    private static final String URI = "/myapi/myApp";

   public void setUp() {

   public void testGet() throws Exception {
       AppEntity entity = new AppEntity();
      List<AppEntity> dataList = new ArrayList<AppEntity>();
      AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
      entity.setCreated_at("2020-02-21 17:01:38.717863");
      entity.setCreated_by(“Abhinav Kr”);
      entity.setModified_at("2020-02-24 17:01:38.717863");



      RequestBuilder requestBuilder =  MockMvcRequestBuilders.get(URI)

        MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        String expectedJson = this.mapToJson(dataResponse);
        String outputInJson = mvcResult.getResponse().getContentAsString();

        assertEquals(HttpStatus.OK.value(), response.getStatus());
        assertEquals(expectedJson, outputInJson);

   public void testCreate() throws Exception {

       AppRequest request = new AppRequest();
       request.createdBy = 1;
       request.AppFullName = “My App”;
       request.appTimezone = “India”;

       String inputInJson = this.mapToJson(request);
       Mockito.verify(service, Mockito.times(1)).createApp(request);

       RequestBuilder requestBuilder =

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());


   public void testUpdate() throws Exception {

       AppRequest request = new AppRequest(); = 1;
       request.modifiedBy = 1;
        request.AppFullName = “My App”;
       request.appTimezone = “Bharat”;

       String inputInJson = this.mapToJson(request);
       Mockito.verify(service, Mockito.times(1)).updateApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.put(URI)

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());


   public void testDelete() throws Exception {

       AppRequest request = new AppRequest(); = 1;

       String inputInJson = this.mapToJson(request);
       Mockito.verify(service, Mockito.times(1)).deleteApp(;

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.delete(URI)

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());



How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

Add two numbers and display result in textbox with Javascript


function sum()
    var value1= parseInt(document.getElementById("txtfirst").value);
    var value2=parseInt(document.getElementById("txtsecond").value);
    var sum=value1+value2;


nodemon not found in npm

Had the same problem otherwise was just working fine a day ago. Very simple fix first check if nodemon exists on your system globally or not

To check

npm list -g --depth=0

If you don't see then install it npm install -g nodemon (g stands for globally)
If you see it still doesn't work then you need to configure environment variable I use Windows OS. On Windows navigate to

Control panel>System>Advanced System Settings>Environment Variables>double-click on PATH

Now check if you have this PATH C:\Users\yourUsername\AppData\Roaming\npm
If not, you will see some existing paths, just append to it separating with semicolon. That's it! Worked for me. For me node was installed in C:..\Roaming\npm and for you if the PATH is different, you will put in whatever applcable.

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:

Bootstrap modal opening on page load

I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.

With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.

<script type="text/javascript">

How can I validate google reCAPTCHA v2 using javascript/jQuery?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <script src=''></script>
    <script type="text/javascript">
        function get_action() {
            var v = grecaptcha.getResponse();
            console.log("Resp" + v);
            if (v == '') {
                document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
                return false;
            else {
                document.getElementById('captcha').innerHTML = "Captcha completed";
                return true;
    <form id="form1" runat="server" onsubmit="return get_action();">
    <div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
   <%-- <input type="submit" value="Button" />--%>
   <asp:Button ID="Button1" runat="server"
       Text="Button" />
    <div id="captcha"></div>

It will work as expected.

How to give spacing between buttons using bootstrap

The original code is mostly there, but you need btn-groups around each button. In Bootstrap 3 you can use a btn-toolbar and a btn-group to get the job done; I haven't done BS4 but it has similar constructs.

<div class="btn-toolbar" role="toolbar">
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 1</button>
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 2</button>

Google reCAPTCHA: How to get user response and validate in the server side?

The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.

But that does not keep your site safe from HTTP client request forgery.

Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.

In human speech it would be like,

  • Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as a proof of that.
  • Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
  • Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
  • Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.

Validating the response is really easy. Just make a GET Request to

And replace the response_string with the value that you earlier got by the g-recaptcha-response field.

You will get a JSON Response with a success field.

More information here:

Edit: It's actually a POST, as per documentation here.

Error inflating class

In my case, a problem was in calling inflater.inflate(R.layout.some_layout, null). Null as ViewGroup parameter was the problem.

How to clear or stop timeInterval in angularjs?

var interval = $interval(function() {
  console.log('say hello');
}, 1000);


How to use goto statement correctly

As already pointed out by all the answers goto - a reserved word in Java and is not used in the language.

restart: is called an identifier followed by a colon.

Here are a few things you need to take care of if you wish to achieve similar behavior -

outer:                  // Should be placed exactly before the loop
loopingConstructOne  {  // We can have statements before the outer but not inbetween the label and the loop          
    loopingConstructTwo {
        continue;       // This goes to the top of loopingConstructTwo and continue.
        break;          // This breaks out of loopingConstructTwo.
        continue outer; // This goes to the outer label and reenters loopingConstructOne.
        break outer;    // This breaks out of the loopingConstructOne.
        continue inner; // This will behave similar to continue.
        break inner;    // This will behave similar to break.

I'm not sure of whether should I say similar as I already have.

How can I backup a Docker-container with its data-volumes?

If you like entering arcane operators from the command line, you’ll love these manual container backup techniques. Keep in mind, there’s a faster and more efficient way to backup containers that’s just as effective. I've written instructions here:

Step 1: Add a Docker Host to Any Cloud As explained in a tutorial on the Morpheus support site, you can add a Docker host to the cloud of your choice in a matter of seconds. Start by choosing Infrastructure on the main Morpheus navigation bar. Select Hosts at the top of the Infrastructure window, and click the “+Container Hosts” button at the top right.

To back up a Docker host to a cloud via Morpheus, navigate to the Infrastructure screen and open the “+Container Hosts” menu.

Choose a container host type on the menu, select a group, and then enter data in the five fields: Name, Description, Visibility, Select a Cloud and Enter Tags (optional). Click Next, and then configure the host options by choosing a service plan. Note that the Volume, Memory, and CPU count fields will be visible only if the plan you select has custom options enabled.

Here is where you add and size volumes, set memory size and CPU count, and choose a network. You can also configure the OS username and password, the domain name, and the hostname, which by default is the container name you entered previously. Click Next, and then add any Automation Workflows (optional).Finally, review your settings and click Complete to save them.

Step 2: Add Docker Registry Integration to Public or Private Clouds Adam Hicks describes in another Morpheus tutorial how simple it is to integrate with a private Docker Registry. (No added configuration is required to use Morpheus to provision images with Docker’s public hub using the public Docker API.)

Select Integrations under the Admin tab of the main navigation bar, and then choose the “+New Integration” button on the right side of the screen. In the Integration window that appears, select Docker Repository in the Type drop-down menu, enter a name and add the private registry API endpoint. Supply a username and password for the registry you’re using, and click the Save Changes button.

Integrate a Docker Registry with a private cloud via the Morpheus “New Integration” dialog box.

To provision the integration you just created, choose Docker under Type in the Create Instance dialog, select the registry in the Docker Registry drop-down menu under the Configure tab, and then continue provisioning as you would any Docker container.

Step 3: Manage Backups Once you’ve added the Docker host and integrated the registry, a backup will be configured and performed automatically for each instance you provision. Morpheus support provides instructions for viewing backups, creating an instance backup, and creating a server backup.

How to jquery alert confirm box "yes" & "no"

See following snippet :

$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
<script src=""></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Check if your HTML page includes:

  1. angular.min script
  2. app.js
  3. controller JavaScript page

The order the files are included is important. It was my solution to this problem.

Hope this helps.

Classpath resource not found when running as jar

Jersey needs to be unpacked jars.


CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Just add the following rules to the parent element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Here's a sample demo (Resize window to see the image align)

Browser support for Flexbox nowadays is quite good.

For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:


That encoder will add the BOM.

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr:

Pip Install not installing into correct directory?

From the comments to the original question, it seems that you have multiple versions of python installed and that pip just goes to the wrong version.

First, to know which version of python you're using, just type which python. You should either see:

which python

if you're going to the right version of python, or:

which python

If you're going to the 'wrong' version. To make pip go to the right version, you first have to change the path:

 export PATH=/Library/Frameworks/Python.framework/Versions/2.7/bin/python:${PATH}

typing 'which python' would now get you to the right result. Next, install pip (if it's not already installed for this installation of python). Finally, use it. you should be fine now.

Custom UITableViewCell from nib in Swift

Swift 4

Register Nib

override func viewDidLoad() {
    tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")

In TableView DataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
          return cell

How to save python screen output to a text file

I found a quick way for this:

log = open("log.txt", 'a')

def oprint(message):
    global log

code ...


Whenever you want to print something just use oprint rather than print.

Note1: In case you want to put the function oprint in a module then import it, use:

import builtins

builtins.log = open("log.txt", 'a')

Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)

Why is it that "No HTTP resource was found that matches the request URI" here?

Your problems have nothing to do with POST/GET but only with how you specify parameters in RouteAttribute. To ensure this, I added support for both verbs in my samples.

Let's go back to two very simple working examples.

[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsOne(string anyString)
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);


[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsTwo(string anyString = "default")
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);

The first sample says that the "anyString" is a path segment parameter (part of the URL).

First sample example URL is:

  • localhost:xxx/api/deliveryItems/dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"

The second sample says that the "anyString" is a query string parameter (optional here since a default value has been provided, but you can make it non-optional by simply removing the default value).

Second sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"
  • localhost:xxx/api/deliveryItems
    • returns "default"

Of course, you can make it even more complex, like with this third sample:

[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsThree(string anyString, string anotherString = "anotherDefault")
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString + "||" + anotherString);

Third sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||anotherDefault"
  • localhost:xxx/api/deliveryItems
    • returns "No HTTP resource was found that matches the request URI ..." (parameter anyString is mandatory)
  • localhost:xxx/api/deliveryItems?anotherString=bluberb&anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||bluberb"
    • note that the parameters have been reversed, which does not matter, this is not possible with "URL-style" of first example

When should you use path segment or query parameters? Some advice has already been given here: REST API Best practices: Where to put parameters?

notifyDataSetChanged not working on RecyclerView

Although it is a bit strange, but the notifyDataSetChanged does not really work without setting new values to adapter. So, you should do:

array = getNewItems();                    
((MyAdapter) mAdapter).setValues(array);  // pass the new list to adapter !!!

This has worked for me.

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.


OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

AngularJS - get element attributes values

function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_

Get selected item value from Bootstrap DropDown with specific ID

Try this code

<input type="TextBox" ID="yearBox" border="0" disabled>

$('#yearSelected li').on('click', function(){

<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
          <ul class="dropdown-menu">
              <ul class="menu" id="yearSelected">
                <li><a href="#">2014-2015</a></li>
                <li><a href="#">2015-2016</a></li>
                <li><a href="#">2016-2017</a></li>
                <li><a href="#">2017-2018</a></li>


its work for me

ReactJS SyntheticEvent stopPropagation() only works with React events?

Update: You can now <Elem onClick={ proxy => proxy.stopPropagation() } />

How to include *.so library in Android Studio?

This is my build.gradle file, Please note the line

jniLibs.srcDirs = ['libs']

This will include libs's *.so file to apk.

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
        jniLibs.srcDirs = ['libs']

    // Move the tests to tests/java, tests/res, etc...

    // Move the build types to build-types/<type>
    // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
    // This moves them out of them default location under src/<type>/... which would
    // conflict with src/ being used by the main source set.
    // Adding new build types or product flavors should be accompanied
    // by a similar customization.

Why cannot change checkbox color whatever I do?

One line of CSS is enough using hue-rotate filter. You can change their sizes with transform: scale() as well.

.checkbox { filter: hue-rotate(0deg) }


.c1 { filter: hue-rotate(0deg)   }
.c2 { filter: hue-rotate(30deg)  }
.c3 { filter: hue-rotate(60deg)  }
.c4 { filter: hue-rotate(90deg)  }
.c5 { filter: hue-rotate(120deg) }
.c6 { filter: hue-rotate(150deg) }
.c7 { filter: hue-rotate(180deg) }
.c8 { filter: hue-rotate(210deg) }
.c9 { filter: hue-rotate(240deg) }

input[type=checkbox] {
  transform: scale(2);
  margin: 10px;
  cursor: pointer;

/* Prevent cursor being `text` between checkboxes */
body { cursor: default }
<input type="checkbox" class="c1" />
<input type="checkbox" class="c2" />
<input type="checkbox" class="c3" />
<input type="checkbox" class="c4" />
<input type="checkbox" class="c5" />
<input type="checkbox" class="c6" />
<input type="checkbox" class="c7" />
<input type="checkbox" class="c8" />
<input type="checkbox" class="c9" />

Angular bootstrap datepicker date format does not format ng-model value

You may use formatters after picking value inside your datepicker directive. For example

angular.module('foo').directive('bar', function() {
    return {
        require: '?ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.push(function(value) {
                if (value) {
                    // format and return date here

                return undefined;


The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Spring Boot - Cannot determine embedded database driver class for database type NONE

Already enough of answers were posted. However, I'm posting what mistake i did and how i corrected it.

In my case, i had packaged my project as pom instead of jar



Changed to:


It may helpful for someone with the same mistake.

Instantiate and Present a viewController in Swift

guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

Code from the same link

<script type="text/javascript" src=""></script>
<script src="" type="text/javascript"></script>
<link href=""
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        $("#btnShow").click(function () {
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>


Where 'div' is your animated object.

I hope you find this useful.


How to enable CORS in AngularJs

we can enable CORS in the frontend by using the ngResourse module. But most importantly, we should have this piece of code while making the ajax request in the controller,

$scope.weatherAPI = $resource(YOUR API,
     {callback: "JSON_CALLBACK"}, {get: {method: 'JSONP'}});
 $scope.weatherResult = $scope.weatherAPI.get(YOUR REQUEST DATA, if any);

Also, you must add ngResourse CDN in the script part and add as a dependency in the app module.

<script src=""></script>

Then use "ngResourse" in the app module dependency section

var routerApp = angular.module("routerApp", ["ui.router", 'ngResource']);

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from : markdown table with colspan

Works in Jupyter Markdown.


As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
| Span <td colspan=3>triple  <td colspan=2>double


One    | Two | Three | Four    | Five  | Six
Span <td colspan=3>triple  <td colspan=2>double

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file =[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file =;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {

    reader.onerror = (event) => {


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

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

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

Or else the easiest you could do is use sessions.

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

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

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


This is the jsfiddle for it

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It appears that you are using the default route which is defined as this:

    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

The key part of that route is the {id} piece. If you look at your action method, your parameter is k instead of id. You need to change your action method to this so that it matches the route parameter:

// change int k to int id
public ActionResult DetailsData(int id)

If you wanted to leave your parameter as k, then you would change the URL to be:


You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):

  <add name="EmployeeContext"
       connectionString="Server=.;Database=mytry;integrated security=True;"
       providerName="System.Data.SqlClient" />

How to get an IFrame to be responsive in iOS Safari?

For me CSS solutions didn't work. But setting the width programmatically does the job. On iframe load set the width programmatically:


AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.


Export HTML table to pdf using jspdf

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

For people having the same error with a similar code:

    var app = angular.module("myApp", []); 
    app.controller('myController', function(){


Removing the $(function(){ ... }); solved the error.

how to change text box value with jQuery?

you simply do like this hope will help you


  $("#cd").click(function () {   



here you can see the demo

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;

            width: 150px;
            height: 150px;
            border-radius: 50%;

            display: block;

<script src=""></script>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>

<script type="text/javascript">

$('button').click(function() {


Bootstrap Modal Backdrop Remaining

If after modal hide, faded background is remained and does not let you click any where you can forcefully remove those by using below piece of code.

First hide (all) your modal div elements.


Secondly remove 'modal-open' class from body and '.modal-backdrop' at the end of the page.


Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);

Try it out... It works (at least on Chrome)!

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

.state('public', {
    abstract: true,
    module: 'public'
.state('public.login', {
    url: '/login',
    module: 'public'
.state('tool', {
    abstract: true,
    module: 'private'
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module +, route.config);

  this.$get = function () {
    return {
      config: this.config

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Cross-browser custom styling for file upload button

I'm posting this because (to my surprise) there was no other place I could find that recommended this.

There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label> tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].

The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:

label.myLabel input[type="file"] {_x000D_
    top: -1000px;_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
    border: 2px solid #AAA;_x000D_
    border-radius: 4px;_x000D_
    padding: 2px 5px;_x000D_
    margin: 2px;_x000D_
    background: #DDD;_x000D_
    display: inline-block;_x000D_
.myLabel:hover {_x000D_
    background: #CCC;_x000D_
.myLabel:active {_x000D_
    background: #CCF;_x000D_
.myLabel :invalid + span {_x000D_
    color: #A44;_x000D_
.myLabel :valid + span {_x000D_
    color: #4A4;_x000D_
<label class="myLabel">_x000D_
    <input type="file" required/>_x000D_
    <span>My Label</span>_x000D_

I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden or display:none file-input). I've tested in emulated IE7 and up, and it worked perfectly.

  1. You can't use <button>s inside <label> tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.
  2. If the for attribute is defined, its value is used to trigger the input with the same id as the for attribute on the <label>.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....

Run again your problem will be solved

How do I exclude all instances of a transitive dependency when using Gradle?

Ah, the following works and does what I want:

configurations {
  runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"

It seems that an Exclude Rule only has two attributes - group and module. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:

dependencies {
  compile ('') {
    exclude group: "org.slf4j", name: "slf4j-log4j12"


No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule

So even though you can specify a dependency with a group: and name: you can't specify an exclusion with a name:!?!

Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:


This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

Export to xls using angularjs

When I needed something alike, ng-csv and other solutions here didn't completely help. My data was in $scope and there were no tables showing it. So, I built a directive to export given data to Excel using Sheet.js (xslsx.js) and FileSaver.js.

Here is my solution packed.

For example, the data is:

$scope.jsonToExport = [
      "col1data": "1",
      "col2data": "Fight Club",
      "col3data": "Brad Pitt"
      "col1data": "2",
      "col2data": "Matrix Series",
      "col3data": "Keanu Reeves"
      "col1data": "3",
      "col2data": "V for Vendetta",
      "col3data": "Hugo Weaving"

I had to prepare data as array of arrays for my directive in my controller:

$scope.exportData = [];
// Headers:
$scope.exportData.push(["#", "Movie", "Actor"]);
// Data:
angular.forEach($scope.jsonToExport, function(value, key) {
  $scope.exportData.push([value.col1data, value.col2data, value.col3data]);

Finally, add directive to my template. It shows a button. (See the fiddle).

<div excel-export export-data="exportData" file-name="{{fileName}}"></div>

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.


<!DOCTYPE html>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_

nginx: how to create an alias url route?

server {
  root /path/to/root;
  location / {
    # bla bla
  location /demo {
    alias /path/to/root/production/folder/here;

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to make Bootstrap carousel slider use mobile left/right swipe


I came up with this solution when I was pretty new to web design. Now that I am older and wiser, the answer Liam gave seems to be a better option. See the next top answer; it is a more productive solution.

I worked on a project recently and this example worked perfectly. I am giving you the link below.

First you have to add jQuery mobile:

This adds the touch functionality, and then you just have to make events such as swipe:

$(document).ready(function() {
   $("#myCarousel").swiperight(function() {
   $("#myCarousel").swipeleft(function() {

The link is below, where you can find the tutorial I used:

How can I create a marquee effect?

With a small change of the markup, here's my approach (I've just inserted a span inside the paragraph):

.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;

.marquee span:hover {
  animation-play-state: paused

@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }

/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01; 
    /* instead of animation: none, so an animationend event is 
     * still available, if previously attached.
    width: auto;
    padding-left: 0;
<p class="marquee">
       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that 
       does not stray. – (Dante Alighieri, <i>Divine Comedy</i>. 

No hardcoded values — dependent on paragraph width — have been inserted.

The animation applies the CSS3 transform property (use prefixes where needed) so it performs well.

If you need to insert a delay just once at the beginning then also set an animation-delay. If you need instead to insert a small delay at every loop then try to play with an higher padding-left (e.g. 150%)

Bootstrap button - remove outline on Chrome OS X

Search and replace

outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;

Replace to

outline: 0;

How to use FormData for AJAX file upload?

$('#form-withdraw').submit(function(event) {

    //prevent the form from submitting by default

    var formData = new FormData($(this)[0]);

        url: 'function/ajax/topup.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          if(returndata == 'success')
              title: "Great",
              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
              type: "success",
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "OK",
              closeOnConfirm: false
              window.location.href = '/transaction.php';

          else if(returndata == 'Offline')
              sweetAlert("Offline", "Please use other payment method", "error");


how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

How to get JQuery.trigger('click'); to initiate a mouse click

jQuery's .trigger('click'); will only cause an event to trigger on this event, it will not trigger the default browser action as well.

You can simulate the same functionality with the following JavaScript:

jQuery('#foo').on('click', function(){
    var bar = jQuery('#bar');
    var href = bar.attr('href');
    if(bar.attr("target") === "_blank")
        window.location = href;

React.js: Wrapping one component into another

Using children

const Wrapper = ({children}) => (

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
    <App name={name}/>

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>

const appElement = (


This is simple and fine for many usecases, and I'd recommend this for most consumer apps.

render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,

Note you don't necessarily need to use children, it is a matter of taste/API.

  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.

Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
          <div><WrappedComponent {...this.props}/></div>
  return Wrapper;

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

fail to change placeholder color with Bootstrap 3

Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:

.form-control::-moz-placeholder {
  color: #999999;
  opacity: 1;
.form-control:-ms-input-placeholder {
  color: #999999;
.form-control::-webkit-input-placeholder {
  color: #999999;

Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:

form .form-control::-moz-placeholder {
  color: #fff;
  opacity: 1;
form .form-control:-ms-input-placeholder {
  color: #fff;
form .form-control::-webkit-input-placeholder {
  color: #fff;

Voila that will override bootstrap's CSS.

How to install CocoaPods?

Are you behind a proxy? If so, pass the proxy as an argument sudo gem install --http-proxy http://user:[email protected]:80 cocoapods `

Remove Blank option from Select Option with AngularJS

Another method to resolve is by making use of: $first in ng-repeat


<select ng-model="feed.config">
    <option ng-repeat="template in configs" ng-selected="$first">{{}}</option>


ngSelected :

$first :


Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If at any point you return Promise.reject('something') you will be thrown in the catch block to the promise.

  .then((result) => {
    if (!result) {
      return Promise.reject('No result');
  .catch((err) => {

If the first promise does not return any result you will only get 'No result' in the console.

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want:


 private Map<String, Object> injectionMap = new HashMap<>();

 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);

 public void afterEach() throws Exception {

android.content.res.Resources$NotFoundException: String resource ID #0x0

When you try to set text in Edittext or textview you should pass only String format.




AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

HTTP Error 500.19 and error code : 0x80070021

I also was getting the same problem but after brain storming with IIS and google for many hours. I found out the solution. This error is because some settings are disabled in IIS applicationHost.config.

Below are the steps to solution:

  1. Go to C:\Windows\System32\inetsrv\config\applicationHost.config and open in notepad
  2. Change the following key value present in

    • <section name="handlers" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"

    • <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"

It worked for me.

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
    @Html.Partial("_partialView", planVM)

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Bootstrap 3 select input form inline

Thanks to G_money and other suggestions for this excellent solution to input-text with inline dropdown... here's another great solution.

<form class="form-inline" role="form" id="yourformID-form" action="" method="post">
    <div class="input-group">
        <span class="input-group-addon"><i class="fa fa-male"></i></span>

        <div class="form-group">
            <input size="50" maxlength="50" class="form-control" name="q" type="text">          

        <div class="form-group">
            <select class="form-control" name="category">
                <option value=""></option>
                <option value="0">select1</option>
                <option value="1">select2</option>
                <option value="2">select3</option>

This works with Bootstrap 3: allowing input-text inline with a select dropdown. Here's what it looks like below...

enter image description here

"The public type <<classname>> must be defined in its own file" error in Eclipse

I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use


or define auto-size:


How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

how to get value of selected item in autocomplete

When autocomplete changes a value, it fires a autocompletechange event, not the change event

$(document).ready(function () {
    $('#tags').on('autocompletechange change', function () {
        $('#tagsname').html('You selected: ' + this.value);

Demo: Fiddle

Another solution is to use select event, because the change event is triggered only when the input is blurred

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);

Demo: Fiddle

Console.log not working at all

In my case, all console messages were not showing because I had left a string in the "filter" textbox.

Remove the filter it by clicking the X as shown:

enter image description here

Use of document.getElementById in JavaScript

the line


says 'the variable I called 'age' has the value of the element with id 'age'. In this case the input field.

The line

voteable=(age<18)?"Too young":"Old enough";

says in a variable I called 'voteable' I store the value following the rule :

"If age is under 18 then show 'Too young' else show 'Old enough'"

The last line tell to put the value of 'voteable' in the element with id 'demo' (in this case the 'p' element)

How do I change selected value of select2 dropdown with JqGrid?

This should be even easier.

$("#e1").select2("val", ["View" ,"Modify"]);

But make sure the values which you pass are already present in the HTMl

Android: how to hide ActionBar on certain activities

If you were using Theme.AppCompat.Light, a better equivalent would be Theme.AppCompat.Light.NoActionBar.

I found that using Theme.AppCompat.NoTitleBar caused my button text to be invisible so I am using Theme.AppCompat.Light.NoActionBar.

<activity android:name=".Activity"
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />

Difference between Role and GrantedAuthority in Spring Security

Think of a GrantedAuthority as being a "permission" or a "right". Those "permissions" are (normally) expressed as strings (with the getAuthority() method). Those strings let you identify the permissions and let your voters decide if they grant access to something.

You can grant different GrantedAuthoritys (permissions) to users by putting them into the security context. You normally do that by implementing your own UserDetailsService that returns a UserDetails implementation that returns the needed GrantedAuthorities.

Roles (as they are used in many examples) are just "permissions" with a naming convention that says that a role is a GrantedAuthority that starts with the prefix ROLE_. There's nothing more. A role is just a GrantedAuthority - a "permission" - a "right". You see a lot of places in spring security where the role with its ROLE_ prefix is handled specially as e.g. in the RoleVoter, where the ROLE_ prefix is used as a default. This allows you to provide the role names withtout the ROLE_ prefix. Prior to Spring security 4, this special handling of "roles" has not been followed very consistently and authorities and roles were often treated the same (as you e.g. can see in the implementation of the hasAuthority() method in SecurityExpressionRoot - which simply calls hasRole()). With Spring Security 4, the treatment of roles is more consistent and code that deals with "roles" (like the RoleVoter, the hasRole expression etc.) always adds the ROLE_ prefix for you. So hasAuthority('ROLE_ADMIN') means the the same as hasRole('ADMIN') because the ROLE_ prefix gets added automatically. See the spring security 3 to 4 migration guide for futher information.

But still: a role is just an authority with a special ROLE_ prefix. So in Spring security 3 @PreAuthorize("hasRole('ROLE_XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')") and in Spring security 4 @PreAuthorize("hasRole('XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')").

Regarding your use case:

Users have roles and roles can perform certain operations.

You could end up in GrantedAuthorities for the roles a user belongs to and the operations a role can perform. The GrantedAuthorities for the roles have the prefix ROLE_ and the operations have the prefix OP_. An example for operation authorities could be OP_DELETE_ACCOUNT, OP_CREATE_USER, OP_RUN_BATCH_JOBetc. Roles can be ROLE_ADMIN, ROLE_USER, ROLE_OWNER etc.

You could end up having your entities implement GrantedAuthority like in this (pseudo-code) example:

class Role implements GrantedAuthority {
    private String id;

    private final List<Operation> allowedOperations = new ArrayList<>();

    public String getAuthority() {
        return id;

    public Collection<GrantedAuthority> getAllowedOperations() {
        return allowedOperations;

class User {
    private String id;

    private final List<Role> roles = new ArrayList<>();

    public Collection<Role> getRoles() {
        return roles;

class Operation implements GrantedAuthority {
    private String id;

    public String getAuthority() {
        return id;

The ids of the roles and operations you create in your database would be the GrantedAuthority representation, e.g. ROLE_ADMIN, OP_DELETE_ACCOUNT etc. When a user is authenticated, make sure that all GrantedAuthorities of all its roles and the corresponding operations are returned from the UserDetails.getAuthorities() method.

Example: The admin role with id ROLE_ADMIN has the operations OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB assigned to it. The user role with id ROLE_USER has the operation OP_READ_ACCOUNT.

If an admin logs in the resulting security context will have the GrantedAuthorities: ROLE_ADMIN, OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB

If a user logs it, it will have: ROLE_USER, OP_READ_ACCOUNT

The UserDetailsService would take care to collect all roles and all operations of those roles and make them available by the method getAuthorities() in the returned UserDetails instance.

How to send and retrieve parameters using $state.go toParams and $stateParams?

I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.

I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:

Below is the controller from which you call the next view using $state.go()

.controller('searchBoxController', function ($scope, $state) {
        $scope.doSearch = function(){
            var searchInputRaw = $scope.searchQueryInput;
            $state.go('app.searchResults', { searchQuery: searchInput });

Below is the state that would be called when the $state.go() gets executed:

                url: '/searchResults',
                    'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
                    'searchQuery': ''

And finally, the controller associated with the app.searchResults state:

.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
        $scope.searchQueryInput = $stateParams.searchQuery;

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

  FROM (SELECT msisdn
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

How to change colour of blue highlight on select box dropdown

Add this in your CSS code and change the red background-color with a color of your choice:

.dropdown-menu>.active>a {color:black; background-color:red;}
.dropdown-menu>.active>a:focus {color:black; background-color:red;}
.dropdown-menu>.active>a:hover {color:black; background-color:red;}

Show hide divs on click in HTML and CSS without jQuery

Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.

.collapse > p{
cursor: pointer;
display: block;

outline: none;

.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;

.collapse:focus div{
display: block; 
height: 100%;
width: 100%;
overflow: auto;

<div class="collapse" tabindex="1">
<p>Question 1</p>
  <p>Visit <a href="">Stack Overflow</a></p>
<div class="collapse" tabindex="2">
<p>Question 2</p>
  <p>Visit <a href="">Stack Overflow</a></p>

How to fix a header on scroll

custom scroll Header Fixed in shopify:

  var sticky = $('.site-header'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');

css: {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 9;

How to retrieve unique count of a field using Kibana + Elastic Search

Now Kibana 4 allows you to use aggregations. Apart from building a panel like the one that was explained in this answer for Kibana 3, now we can see the number of unique IPs in different periods, that was (IMO) what the OP wanted at the first place.

To build a dashboard like this you should go to Visualize -> Select your Index -> Select a Vertical Bar chart and then in the visualize panel:

  • In the Y axis we want the unique count of IPs (select the field where you stored the IP) and in the X axis we want a date histogram with our timefield.

Building a visualization

  • After pressing the Apply button, we should have a graph that shows the unique count of IP distributed on time. We can change the time interval on the X axis to see the unique IPs hourly/daily...

Final plot

Just take into account that the unique counts are approximate. For more information check also this answer.

Smooth scroll to div id jQuery

Here I tried this, that work great for me.

$('a[href*="#"]').on('click', function (e) {

    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');


 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>

How to show a running progress bar while page is loading

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
  } else {

Java List.contains(Object with field value equal to x)

Despite JAVA 8 SDK there is a lot of collection tools libraries can help you to work with, for instance:

Predicate condition = new Predicate() {
   boolean evaluate(Object obj) {
        return ((Sample)obj).myField.equals("myVal");
List result = list, condition );

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Websocket and WebRTC can be used together, Websocket as a signal channel of WebRTC, and webrtc is a video/audio/text channel, also WebRTC can be in UDP also in TURN relay, TURN relay support TCP HTTP also HTTPS. Many projects use Websocket and WebRTC together.

Wait for async task to finish

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

function sync_call(input) {
    var value;

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

Warning: Permanently added the RSA host key for IP address

If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from to The warning message looks like this:

Warning: Permanently added the RSA host key for IP address '$IP' to the list of

Adding value to input field with jQuery

You can do it as below.

$(this).prev('input').val("hello world");

Live Demo

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

The file is being read as a bunch of strs, but it should be unicodes. Python tries to implicitly convert, but fails. Change:

job_titles = [line.strip() for line in title_file.readlines()]

to explicitly decode the strs to unicode (here assuming UTF-8):

job_titles = [line.decode('utf-8').strip() for line in title_file.readlines()]

It could also be solved by importing the codecs module and using rather than the built-in open.

Integrate ZXing in Android Studio

Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        compile group: '', name: 'core', version: '3.2.1'
        compile group: '', name: 'android-core', version: '3.2.0'


You can always find latest version core and android core from below links:

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation ''
    implementation ''

Java Multithreading concept and join() method

when ob1 is created then the constructor is called where "t.start()" is written but still run() method is not executed rather main() method is executed further. So why is this happening?

here your threads and main thread has equal priority.Execution of equal priority thread totally depends on the Thread schedular.You can't expect which to execute first.

join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

Here your calling below statements from main thread.


So main thread waits for ob1.t,ob2.t,ob3.t threads to die(look into Thread#join doc).So all three threads executes successfully and main thread completes after that

How do I convert a C# List<string[]> to a Javascript array?

Here's how you accomplish that:

<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');

html form - make inputs appear on the same line

You can wrap the following in a DIV:

<div class="your-class">

  <label for="First_Name">First Name:</label>
  <input name="first_name" id="First_Name" type="text" />
  <label for="Name">Last Name:</label>
  <input name="last_name" id="Last_Name" type="text" /> 


Give each input float:left in your CSS:

.your-class input{

example only

You might have to adjust margins.

Remember to apply clear:left or both to whatever comes after ".your-class"

How to make responsive table


A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }


<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it

ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this can help you (leverages from the same data as kangax).

Bootstrap 3.0 Popovers and tooltips

You just need to enable the tooltip:

$('some id or class that you add to the above a tag').popover({
    trigger: "hover" 

Ways to iterate over a list in Java

Right, many alternatives are listed. The easiest and cleanest would be just using the enhanced for statement as below. The Expression is of some type that is iterable.

for ( FormalParameter : Expression ) Statement

For example, to iterate through, List<String> ids, we can simply so,

for (String str : ids) {
    // Do something

How to create a HTML Cancel button that redirects to a URL

<button onclick=\"window.location='{$_SERVER['PHP_SELF']}';return false;\">Reset</button>

Not enough rep to Vote Up for Kostyan. Here's my final solution (needed a reset button).

Thanks again to Kostyan for answering the question as asked without suggesting a "workaround" (time-consuming) method to "construct a button" with styles.

This is a Button (which the viewer expects to see) and it works exactly as requested. And it mingles with the other buttons on the page. Without complexity.

I did remove the "type=cancel" which apparently was useless. So even less code. :)

How to remove elements/nodes from angular.js array

My solution was quite straight forward

app.controller('TaskController', function($scope) {
 $scope.items = tasks;

    $scope.addTask = function(task) {
        task.created =;

    $scope.removeItem = function(item) {
        // item is the index value which is obtained using $index in ng-repeat
        $scope.items.splice(item, 1);

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
        if (key != null)
            Object o = key.GetValue("Version");
            if (o != null)
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
catch (Exception ex)  //just for's always best to handle specific exceptions
    //react appropriately

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

Bootstrap 3 grid with no gap

The more powerful (and 100% fluid) Bootstrap 3 grid now comes in 3 sizes. Tiny (for smartphones .col-), Small (for tablets .col-sm-) and Large (for laptops/desktops .col-lg-*). The 3 grid sizes enable you to control grid behavior on different devices (desktop, tablet, smartphone, etc..).

Unlike 2.x, Bootstrap 3 does not provide a fixed (pixel-based) grid. While a fixed-width layout can still be acheived using a simple custom wrapper, there is now only one percentage-based (fluid) grid. The .container and .row classes are now fluid by default, so don't use .row-fluid or .container-fluid anymore in your 3.x markup.


Removing "bullets" from unordered list <ul>

In my case

li {
  list-style-type : none;

It doesn't show the bullet but leaved some space for the bullet.

I use

li {
  list-style-type : '';

It works perfectly.

How do I get the current time only in JavaScript

var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        $scope.time = strTime;

        month = '' + (date.getMonth() + 1),
        day = '' + date.getDate(1),
        year = date.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        var tomorrow = [year, month, day].join('-');
        $scope.tomorrow = tomorrow;

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

Clear screen in shell

using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:

First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)

def cls(): print ("\n" * 50)

then just call it as many times as you want or need


How to 'bulk update' with Django?

Consider using django-bulk-update found here on GitHub.

Install: pip install django-bulk-update

Implement: (code taken directly from projects ReadMe file)

from bulk_update.helper import bulk_update

random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()

for person in people:
    r = random.randrange(4) = random_names[r]

bulk_update(people)  # updates all columns using the default db

Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.

MongoDB query with an 'or' condition

Using a $where query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.

An empty Regex or MaxKey (if you language supports it) are both good choices.

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +--
¦   +-- db.sql
+-- scripts
¦   +-- 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

How do I use sudo to redirect output to a location I don't have permission to write to?

A trick I figured out myself was

sudo ls -hal /root/ | sudo dd of=/root/test.out

Android custom Row Item for ListView

you can follow BaseAdapter and create your custome Xml file and bind it with you BaseAdpter and populate it with Listview see here need to change xml file as Require.

How do you set a JavaScript onclick event to a class with css

Asking about "a class" in the question title, the answer is getElementsByClassName:

  var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
  for (var i = 0; i < hrefs.length; i++) {
   hrefs.item(i).addEventListener('click', function(e){
    e.preventDefault(); /*use if you want to prevent the original link following action*/

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
{% endif %}


You can do it by using the ROW NUMBER BY PARTITION Feature also. A great example can be found here:

I am using the Orders table of the Northwind database... Now let us retrieve the Last 5 orders placed by Employee 5:

    FROM Orders
) as ordlist

WHERE ordlist.EmployeeID = 5
AND ordlist.OrderedDate <= 5

Get cart item name, quantity all details woocommerce

Try this :

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";

To get Product Image and Regular & Sale Price:

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";

Eclipse shows errors but I can't find them

I came across the same issue while working on a selenium project(maven). The Project folder and pom.xml were showing red cross symbol. This was coming as i had the test datasheet open. I could remove the error by just closing the datasheet and the never faced the issue again

fe_sendauth: no password supplied

After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes.

From the command line: pg_ctl reload

From within a db (as superuser): select pg_reload_conf();

From PGAdmin: right-click db name, select "Reload Configuration"

Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers, etc -- those require a cluster restart.

Difference between Python's Generators and Iterators

Everybody has a really nice and verbose answer with examples and I really appreciate it. I just wanted to give a short few lines answer for people who are still not quite clear conceptually:

If you create your own iterator, it is a little bit involved - you have to create a class and at least implement the iter and the next methods. But what if you don't want to go through this hassle and want to quickly create an iterator. Fortunately, Python provides a short-cut way to defining an iterator. All you need to do is define a function with at least 1 call to yield and now when you call that function it will return "something" which will act like an iterator (you can call next method and use it in a for loop). This something has a name in Python called Generator

Hope that clarifies a bit.

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

Markdown and including multiple files

The @import syntax is supported in vscode-markdown-preview-enhanced

which probably means its part of the the underlying tool mume

and other tools built on mume

How to convert View Model into JSON object in ASP.NET MVC?

I found it to be pretty nice to do it like this (usage in the view):

    @Html.HiddenJsonFor(m => m.TrackingTypes)

Here is the according helper method Extension class:

public static class DataHelpers
    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);

    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
        return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));

    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        var name = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        var tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttribute("name", name);
        tagBuilder.MergeAttribute("type", "hidden");

        var json = JsonConvert.SerializeObject(metadata.Model);

        tagBuilder.MergeAttribute("value", json);

        return MvcHtmlString.Create(tagBuilder.ToString());

It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)

How to delete an item in a list if it exists?

except ValueError:
    print "new_tag_list has no empty string"

Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?

How to find Oracle Service Name

Connect to the database with the "system" user, and execute the following command:

show parameter service_name 

Efficient iteration with index in Scala

Indeed, calling zipWithIndex on a collection will traverse it and also create a new collection for the pairs. To avoid this, you can just call zipWithIndex on the iterator for the collection. This will just return a new iterator that keeps track of the index while iterating, so without creating an extra collection or additional traversing.

This is how scala.collection.Iterator.zipWithIndex is currently implemented in 2.10.3:

  def zipWithIndex: Iterator[(A, Int)] = new AbstractIterator[(A, Int)] {
    var idx = 0
    def hasNext = self.hasNext
    def next = {
      val ret = (, idx)
      idx += 1

This should even be a bit more efficient than creating a view on the collection.

error: cast from 'void*' to 'int' loses precision

Casting a pointer to void* and back is valid use of reinterpret_cast<>. So you could do this:

pthread_create(&thread, NULL, myFcn, new int(5)); // implicit cast to void* from int*

Then in myFcn:

void* myFcn(void* arg)
    int*  data = reinterpret_cast<int*>(arg);
    int   x    = *data;
    delete data;

Note: As sbi points out this would require a change on the OP call to create the thread.

What I am trying to emphasis that conversion from int to pointer and back again can be frough with problems as you move from platform to platform. BUT converting a pointer to void* and back again is well supported (everywhere).

Thus as a result it may be less error prone to generate a pointer dynamcially and use that. Remembering to delete the pointer after use so that we don't leak.

Regular expression to get a string between two strings in Javascript

Regular expression to get a string between two strings in JavaScript

The most complete solution that will work in the vast majority of cases is using a capturing group with a lazy dot matching pattern. However, a dot . in JavaScript regex does not match line break characters, so, what will work in 100% cases is a [^] or [\s\S]/[\d\D]/[\w\W] constructs.

ECMAScript 2018 and newer compatible solution

In JavaScript environments supporting ECMAScript 2018, s modifier allows . to match any char including line break chars, and the regex engine supports lookbehinds of variable length. So, you may use a regex like

var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any
// Or
var result = s.match(/(?<=cow\s*).*?(?=\s*milk)/gs); // Same but whitespaces are optional

In both cases, the current position is checked for cow with any 1/0 or more whitespaces after cow, then any 0+ chars as few as possible are matched and consumed (=added to the match value), and then milk is checked for (with any 1/0 or more whitespaces before this substring).

Scenario 1: Single-line input

This and all other scenarios below are supported by all JavaScript environments. See usage examples at the bottom of the answer.

cow (.*?) milk

cow is found first, then a space, then any 0+ chars other than line break chars, as few as possible as *? is a lazy quantifier, are captured into Group 1 and then a space with milk must follow (and those are matched and consumed, too).

Scenario 2: Multiline input

cow ([\s\S]*?) milk

Here, cow and a space are matched first, then any 0+ chars as few as possible are matched and captured into Group 1, and then a space with milk are matched.

Scenario 3: Overlapping matches

If you have a string like >>>15 text>>>67 text2>>> and you need to get 2 matches in-between >>>+number+whitespace and >>>, you can't use />>>\d+\s(.*?)>>>/g as this will only find 1 match due to the fact the >>> before 67 is already consumed upon finding the first match. You may use a positive lookahead to check for the text presence without actually "gobbling" it (i.e. appending to the match):


See the online regex demo yielding text1 and text2 as Group 1 contents found.

Also see How to get all possible overlapping matches for a string.

Performance considerations

Lazy dot matching pattern (.*?) inside regex patterns may slow down script execution if very long input is given. In many cases, unroll-the-loop technique helps to a greater extent. Trying to grab all between cow and milk from "Their\ncow\ngives\nmore\nmilk", we see that we just need to match all lines that do not start with milk, thus, instead of cow\n([\s\S]*?)\nmilk we can use:


See the regex demo (if there can be \r\n, use /cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm). With this small test string, the performance gain is negligible, but with very large text, you will feel the difference (especially if the lines are long and line breaks are not very numerous).

Sample regex usage in JavaScript:

//Single/First match expected: use no global modifier and access match[1]
console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]);
// Multiple matches: get multiple matches with a global modifier and
// trim the results if length of leading/trailing delimiters is known
var s = "My cow always gives milk, thier cow also gives milk";
console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);}));
//or use RegExp#exec inside a loop to collect all the Group 1 contents
var result = [], m, rx = /cow (.*?) milk/g;
while ((m=rx.exec(s)) !== null) {

Using the modern String#matchAll method

const s = "My cow always gives milk, thier cow also gives milk";
const matches = s.matchAll(/cow (.*?) milk/g);
console.log(Array.from(matches, x => x[1]));

image.onload event and browser cache

I found that you can just do this in Chrome:

  $('.onload-fadein').each(function (k, v) {
    v.onload = function () {
        $(this).animate({opacity: 1}, 2000);
    v.src = v.src;

Setting the .src to itself will trigger the onload event.

Spring Boot: Is it possible to use external files in arbitrary directories with a fat jar?

It's all explained here in the docs:

Which explains that this is the order of precedence:

  • A /config subdir of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

It also points out that you can define additional properties files for overrides like so:

java -jar myproject.jar 

If you use spring.config.location, then all the default locations for are also included. This means that you can set up default values in and override as required for a particular environment.

Loop through columns and add string lengths as new columns

You can use lapply to pass each column to str_length, then cbind it to your original data.frame...


out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1

Calling Member Functions within Main C++

Declare an instance of MyClass, and then call the member function on that instance:

MyClass m;


Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

Learn about CORS, try is work fine


Not show a message error and continue page white, u need see error is try

enjoin us ;-)

Create normal zip file programmatically

Here's some code I wrote after using the above posts. Thanks for all your help.

This code accepts a list of file paths and creates a zip file out of them.

public class Zip
    private string _filePath;
    public string FilePath { get { return _filePath; } }

    /// <summary>
    /// Zips a set of files
    /// </summary>
    /// <param name="filesToZip">A list of filepaths</param>
    /// <param name="sZipFileName">The file name of the new zip (do not include the file extension, nor the full path - just the name)</param>
    /// <param name="deleteExistingZip">Whether you want to delete the existing zip file</param>
    /// <remarks>
    /// Limitation - all files must be in the same location. 
    /// Limitation - must have read/write/edit access to folder where first file is located.
    /// Will throw exception if the zip file already exists and you do not specify deleteExistingZip
    /// </remarks>
    public Zip(List<string> filesToZip, string sZipFileName, bool deleteExistingZip = true)
        if (filesToZip.Count > 0)
            if (File.Exists(filesToZip[0]))

                // Get the first file in the list so we can get the root directory
                string strRootDirectory = Path.GetDirectoryName(filesToZip[0]);

                // Set up a temporary directory to save the files to (that we will eventually zip up)
                DirectoryInfo dirTemp = Directory.CreateDirectory(strRootDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmss"));

                // Copy all files to the temporary directory
                foreach (string strFilePath in filesToZip)
                    if (!File.Exists(strFilePath))
                        throw new Exception(string.Format("File {0} does not exist", strFilePath));
                    string strDestinationFilePath = Path.Combine(dirTemp.FullName, Path.GetFileName(strFilePath));
                    File.Copy(strFilePath, strDestinationFilePath);

                // Create the zip file using the temporary directory
                if (!sZipFileName.EndsWith(".zip")) { sZipFileName += ".zip"; }
                string strZipPath = Path.Combine(strRootDirectory, sZipFileName);
                if (deleteExistingZip == true && File.Exists(strZipPath)) { File.Delete(strZipPath); }
                ZipFile.CreateFromDirectory(dirTemp.FullName, strZipPath, CompressionLevel.Fastest, false);

                // Delete the temporary directory

                _filePath = strZipPath;                    
                throw new Exception(string.Format("File {0} does not exist", filesToZip[0]));
            throw new Exception("You must specify at least one file to zip.");

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   private List<Country> countries; 

   //getter - setter

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null

select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)

select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )

select, t2.qid,, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

right click context menu for datagridview

Simply drag a ContextMenu or ContextMenuStrip component into your form and visually design it, then assign it to the ContextMenu or ContextMenuStrip property of your desired control.

What killed my process and why?

A tool like systemtap (or a tracer) can monitor kernel signal-transmission logic and report. e.g.,

# stap .../sigmon.stp -x 31994 SIGKILL
   SPID     SNAME            RPID  RNAME            SIGNUM SIGNAME
   5609     bash             31994 find             9      SIGKILL

The filtering if block in that script can be adjusted to taste, or eliminated to trace systemwide signal traffic. Causes can be further isolated by collecting backtraces (add a print_backtrace() and/or print_ubacktrace() to the probe, for kernel- and userspace- respectively).

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns --dns"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

Extract specific columns from delimited file using Awk

Others have answered your earlier question. For this:

As an addendum, is there any way to extract directly with the header names rather than with column numbers?

I haven't tried it, but you could store each header's index in a hash and then use that hash to get its index later on.

    hash[$i] = i;

Then later on, use it:

j = hash["header1"];
print $j;

How to solve a pair of nonlinear equations using Python?

I got Broyden's method to work for coupled non-linear equations (generally involving polynomials and exponentials) in IDL, but I haven't tried it in Python:


scipy.optimize.broyden1(F, xin, iter=None, alpha=None, reduction_method='restart', max_rank=None, verbose=False, maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, tol_norm=None, line_search='armijo', callback=None, **kw)[source]

Find a root of a function, using Broyden’s first Jacobian approximation.

This method is also known as “Broyden’s good method”.

Why would a " Connection timed out" exception occur when URL is up?

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when( will actually call, which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)


You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

Proper way to get page content

I've answered my own question. Call apply_filter and there you go.

$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 
echo $content;  

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>


How to call Oracle MD5 hash function?

In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.

select standard_hash('foo', 'MD5') from dual;

The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:

select rawtohex(
    DBMS_CRYPTO.Hash (
        UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
    ) from dual;



Add a lower function call if needed. More on DBMS_CRYPTO.

Writing files in Node.js

Here is the sample of how to read file csv from local and write csv file to local.

var csvjson = require('csvjson'),
    fs = require('fs'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient,
    mongoDSN = 'mongodb://localhost:27017/test',

function uploadcsvModule(){
    var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
    var importOptions = {
        delimiter : ',', // optional 
        quote     : '"' // optional 
    },ExportOptions = {
        delimiter   : ",",
        wrap        : false
    var myobj = csvjson.toSchemaObject(data, importOptions)
    var exportArr = [], importArr = [];
        if(d.orderId==undefined || d.orderId=='') {
        } else {
    var csv = csvjson.toCSV(exportArr, ExportOptions);
    MongoClient.connect(mongoDSN, function(error, db) {
        collection = db.collection("orders")
        collection.insertMany(importArr, function(err,result){
            fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});


how to add jquery in laravel project

To add jquery to laravel you first have to add the Scaffolded javascript file, app.js

This can easily be done adding this tag.

<script src="{{ asset('js/app.js') }}"></script>

There are two main procesess depending on the version but at the end of both you will have to execute:

npm run dev

That adds all the dependencies to the app.js file. But if you want this process to be done automatically for you, you can also run:

npm run watch

Wich will keep watching for changes and add them.

Version 5.*

jQuery is already included in this version of laravel as a dev dependency.

You just have to run:

npm install

This first command will install the dependencies. jquery will be added.

Version 6.* and 7*

jQuery has been taken out of laravel that means you need to import it manually.

I'll import it here as a development dependency:

npm i -D jquery

Then add it to the bootstrap.js file in resources/js/bootstrap.js You may notice that axios and lodash are imported there as well so in the same way we can import jquery.

Just add wherever you want there:

//In resources/js/bootstrap.js
window.$ = require('jquery');

If you follow this process in the 5.* version it won't affect laravel but it will install a more updated version of jquery.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

Yes.. It is possible using css

<a class="disable-me" href="page.html">page link</a>

.disable-me {
    pointer-events: none;

How do I replace NA values with zeros in an R dataframe?

Another example using imputeTS package:

na.replace(yourDataframe, 0)

Any way to replace characters on Swift String?

Swift 3, Swift 4, Swift 5 Solution

let exampleString = "Example string"

//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")

//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 


System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";

How do I install command line MySQL client on mac?

Using MacPorts you can install the client with:

sudo port install mysql57

You also need to select the installed version as your mysql

sudo port select mysql mysql57

The server is only installed if you append -server to the package name (e.g. mysql57-server)

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

private String fileName;

public String getFileName()
    return fileName;

public void setFileName(String fileName)
    this.fileName = fileName;

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

Retrieving Data from SQL Using pyodbc

You are so close!

import pyodbc
cursor = cnxn.cursor()

for row in cursor.fetchall():
    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).

Environment variable substitution in sed

echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

Errors: Data path ".builders['app-shell']" should have required property 'class'

On my side it was package




was not the same version, Updating build-ng-packagr to same version as build-angular fixed my problem.

jQuery $.cookie is not a function

The old version of jQuery Cookie has been deprecated, so if you're getting the error:

$.cookie is not a function

you should upgrade to the new version.

The API for the new version is also different - rather than using


you should use


Split array into two parts without for loop in java


This does what you want without you having to create a new array as it returns a new array.

int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);

How can I rename a project folder from within Visual Studio?

  1. Rename the project in the solution and the project folder

  2. Delete the project from the solution

  3. Add the existing project to the solution (your renamed project)

It works for me. TFS will also track the new project.

How to set time to a date object in java

If you don't have access to java 8 and the API java.time, here is my simple function to copy the time of one date to another date using the old java.util.Calendar (inspire by Jigar Joshi) :

 * Copy only the time of one date to the date of another date.
public static Date copyTimeToDate(Date date, Date time) {
    Calendar t = Calendar.getInstance();

    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, t.get(Calendar.HOUR_OF_DAY));
    c.set(Calendar.MINUTE, t.get(Calendar.MINUTE));
    c.set(Calendar.SECOND, t.get(Calendar.SECOND));
    c.set(Calendar.MILLISECOND, t.get(Calendar.MILLISECOND));
    return c.getTime();

Vim multiline editing like in sublimetext?

Those are some good out-of-the box solutions given above, but we can also try some plugins which provide multiple cursors like Sublime.

I think this one looks promising:

It seemed abandoned for a while, but has had some contributions in 2014.

It is quite powerful, although it took me a little while to get used to the flow (which is quite Sublime-like but still modal like Vim).

In my experience if you have a lot of other plugins installed, you may meet some conflicts!

There are some others attempts at this feature:

Please feel free to edit if you notice any of these undergoing improvement.

isset() and empty() - what to use

Empty returns true if the var is not set. But isset returns true even if the var is not empty.

Setting max width for body using Bootstrap

In responsive.less, you can comment out the line that imports responsive-1200px-min.less.

// Large desktops

@import "responsive-1200px-min.less";

Like so:

// Large desktops

// @import "responsive-1200px-min.less";

How to set DialogFragment's width and height?

When I need to make the DialogFragment a bit wider I'm setting minWidth:

    ... />

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]


To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.


Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)


Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

PHP - Merging two arrays into one array (also Remove Duplicates)

The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case


If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead

array_keys(array_merge($a1, $a2))

Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps

static linking only some libraries

You could also use ld option -Bdynamic

gcc <objectfiles> -static -lstatic1 -lstatic2 -Wl,-Bdynamic -ldynamic1 -ldynamic2

All libraries after it (including system ones linked by gcc automatically) will be linked dynamically.

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';


<a href="<?=$folder_path?>">Link text</a>;


<a href="<?php echo $folder_path ?>">Link text</a>;

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Many people here are using keycode property which is not easy to remember. If you do not have a locale issues then you can simply use key which is actually the input that user types.

See this Fiddle

  console.log("Entered Key is " + e.key);_x000D_
  switch (e.key)_x000D_
         case "1":_x000D_
         case "2":_x000D_
         case "3":_x000D_
         case "4":_x000D_
         case "5":_x000D_
         case "6":_x000D_
         case "7":_x000D_
         case "8":_x000D_
         case "9":_x000D_
         case "0":_x000D_
         case "Backspace":_x000D_
             return true;_x000D_
         case ".":_x000D_
             if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box._x000D_
                 return true;_x000D_
                 return false;_x000D_
             return false;_x000D_
<script src=""></script>_x000D_
Enter Value_x000D_
<input id="txt" type="text" />

issue then see the following simple code.

Please note that this example also contains validation for decimal entry.

As per this question it is not required so you can simply remove the case "." to remove entry of decimal.

How to change the foreign key referential action? (behavior)

Old question but adding answer so that one can get help

Its two step process:

Suppose, a table1 has a foreign key with column name fk_table2_id, with constraint name fk_name and table2 is referred table with key t2 (something like below in my diagram).

   table1 [ fk_table2_id ] --> table2 [t2]

First step, DROP old CONSTRAINT: (reference)

ALTER TABLE `table1` 
DROP FOREIGN KEY `fk_name`;  

notice constraint is deleted, column is not deleted

Second step, ADD new CONSTRAINT:

ALTER TABLE `table1`  
    FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;  

adding constraint, column is already there


I have a UserDetails table refers to Users table:

mysql> SHOW CREATE TABLE UserDetails;
 `User_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`Detail_id`),
  KEY `FK_User_id` (`User_id`),
  CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)

First step:

mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)  

Second step:

mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id` 
    -> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)  


mysql> SHOW CREATE TABLE UserDetails;
`User_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`Detail_id`),
  KEY `FK_User_id` (`User_id`),
                                       `Users` (`User_id`) ON DELETE CASCADE

How to save S3 object to a file using boto3

boto3 now has a nicer interface than the client:

resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)

This by itself isn't tremendously better than the client in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.

Resources generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.

How do I convert a dictionary to a JSON String in C#?

This is Similar to what Meritt has posted earlier. just posting the complete code

    string sJSON;
    Dictionary<string, string> aa1 = new Dictionary<string, string>();
    aa1.Add("one", "1"); aa1.Add("two", "2"); aa1.Add("three", "3");
    Console.Write("JSON form of Person object: ");

    sJSON = WriteFromObject(aa1);

    Dictionary<string, string> aaret = new Dictionary<string, string>();
    aaret = ReadToObject<Dictionary<string, string>>(sJSON);

    public static string WriteFromObject(object obj)
        byte[] json;
            //Create a stream to serialize the object to.  
        using (MemoryStream ms = new MemoryStream())
            // Serializer the object to the stream.  
            DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
            ser.WriteObject(ms, obj);
            json = ms.ToArray();
        return Encoding.UTF8.GetString(json, 0, json.Length);


    // Deserialize a JSON stream to object.  
    public static T ReadToObject<T>(string json) where T : class, new()
        T deserializedObject = new T();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))

            DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedObject.GetType());
            deserializedObject = ser.ReadObject(ms) as T;
        return deserializedObject;

Setting onSubmit in React.js

<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>

it work fine for me

Android ClassNotFoundException: Didn't find class on path

I was having the same issue today. And tried all the above solutions already given but nothing worked for me. Then I spent sometime and I found out the reason. I thought it could save some other developers time I am sharing here as well. The problem was with wrong package name. I was using MVP architecture, and I kept my activities in view package. And I copied the Main class from my other project. This was the catch. In the xml, Main Activity was referring to different Package that was just outer side. The package was not including my view directory (MVP hierarchy level). Then I checked back in manifest as well. The same problem I found there as well. So I provided full path(package name) of my activity(untill MVP' view directory/package there I kept my all activities). This solved my problem. Hope that helps others as well.

UnsatisfiedDependencyException: Error creating bean with name

Try adding @EntityScan(basePackages = "insert package name here") on top of your main class.

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);  }

How do I get the max ID with Linq to Entity?

Note that none of these answers will work if the key is a varchar since it is tempting to use MAX in a varchar column that is filled with "ints".

In a database if a column e.g. "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.

So in your local database everything will work fine since while developing you will never get above 100 test records, then, at some moment during production you get a weird support ticket. Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....

(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...)

So use:

Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();

"psql: could not connect to server: Connection refused" Error when connecting to remote database

See the port and make a port change in postgresql.conf. My installation of postgres 9.4 uses port 5431 or 5434 instead of 5432. If it say the port is in use so change the port. And check if you give password in psql installation so give the password in file and save it.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I guess you have some conflict with other package. For me it was six. So you need to use a command like this:

pip install google-api-python-client --upgrade --ignore-installed six


pip install --ignore-installed six

ImportError: DLL load failed: %1 is not a valid Win32 application

Or you have to rebuild the cv2 module for win 64bit.

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.


<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>


protected void Page_Load(object sender, EventArgs e)
    // or use Page.DataBind() to bind everything

public Dictionary<int, string> Statuses
        // do database/webservice lookup here to populate Dictionary

Removing html5 required attribute with jQuery

Even though the ID selector is the simplest, you can also use the name selector as below:


For more see:

How to parse a String containing XML in Java and retrieve the value of the root node?

Using JDOM:

String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
    org.jdom.Document doc = StringReader(xml));
    String message = doc.getRootElement().getText();
} catch (JDOMException e) {
    // handle JDOMException
} catch (IOException e) {
    // handle IOException

Using the Xerces DOMParser:

String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
    parser.parse(new InputSource(new;
    Document doc = parser.getDocument();
    String message = doc.getDocumentElement().getTextContent();
} catch (SAXException e) {
    // handle SAXException 
} catch (IOException e) {
    // handle IOException 

Using the JAXP interfaces:

String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
    db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    try {
        Document doc = db.parse(is);
        String message = doc.getDocumentElement().getTextContent();
    } catch (SAXException e) {
        // handle SAXException
    } catch (IOException e) {
        // handle IOException
} catch (ParserConfigurationException e1) {
    // handle ParserConfigurationException

Remove URL parameters without refreshing page

Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:


Query comparing dates in SQL

Instead of '2013-04-12' whose meaning depends on the local culture, use '20130412' which is recognized as the culture invariant format.

If you want to compare with December 4th, you should write '20131204'. If you want to compare with April 12th, you should write '20130412'.

The article Write International Transact-SQL Statements from SQL Server's documentation explains how to write statements that are culture invariant:

Applications that use other APIs, or Transact-SQL scripts, stored procedures, and triggers, should use the unseparated numeric strings. For example, yyyymmdd as 19980924.


Since you are using ADO, the best option is to parameterize the query and pass the date value as a date parameter. This way you avoid the format issue entirely and gain the performance benefits of parameterized queries as well.


To use the the the ISO 8601 format in a literal, all elements must be specified. To quote from the ISO 8601 section of datetime's documentation

To use the ISO 8601 format, you must specify each element in the format. This also includes the T, the colons (:), and the period (.) that are shown in the format.

... the fraction of second component is optional. The time component is specified in the 24-hour format.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Edit: it seems nginx now supports error_log stderr; as mentioned in Anon's answer.

You can send the logs to /dev/stdout. In nginx.conf:

daemon off;
error_log /dev/stdout info;

http {
  access_log /dev/stdout;

edit: May need to run ln -sf /proc/self/fd /dev/ if using running certain docker containers, then use /dev/fd/1 or /dev/fd/2

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

Fastest method to escape HTML tags as HTML entities?

You could try passing a callback function to perform the replacement:

var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);

Here is a performance test: to compare with calling the replace function repeatedly, and using the DOM method proposed by Dmitrij.

Your way seems to be faster...

Why do you need it, though?

Index all *except* one item in python

I'm going to provide a functional (immutable) way of doing it.

  1. The standard and easy way of doing it is to use slicing:

    index_to_remove = 3
    data = [*range(5)]
    new_data = data[:index_to_remove] + data[index_to_remove + 1:]
    print(f"data: {data}, new_data: {new_data}")


    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
  2. Use list comprehension:

    data = [*range(5)]
    new_data = [v for i, v in enumerate(data) if i != index_to_remove]
    print(f"data: {data}, new_data: {new_data}") 


    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
  3. Use filter function:

    index_to_remove = 3
    data = [*range(5)]
    new_data = [*filter(lambda i: i != index_to_remove, data)]


    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
  4. Using masking. Masking is provided by itertools.compress function in the standard library:

    from itertools import compress
    index_to_remove = 3
    data = [*range(5)]
    mask = [1] * len(data)
    mask[index_to_remove] = 0
    new_data = [*compress(data, mask)]
    print(f"data: {data}, mask: {mask}, new_data: {new_data}")


    data: [0, 1, 2, 3, 4], mask: [1, 1, 1, 0, 1], new_data: [0, 1, 2, 4]
  5. Use itertools.filterfalse function from Python standard library

    from itertools import filterfalse
    index_to_remove = 3
    data = [*range(5)]
    new_data = [*filterfalse(lambda i: i == index_to_remove, data)]
    print(f"data: {data}, new_data: {new_data}")


    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

how to use font awesome in own css?

you can do so by using the :before or :after pseudo. read more about it here

change your code to this

.lb-prev:hover {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
   text-decoration: none;

.lb-prev:before {
    font-family: FontAwesome;
    content: "\f053";
    font-size: 30px;

do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.


Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)


What is the difference between a data flow diagram and a flow chart?

A DFD shows how the data moves through a system, a flowchart is closer to the operations that system does.

In the classic make a cup of tea example, a DFD would show where the water, tea, milk, sugar were going, whereas the flowchart shows the process.

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +--
|    ¦   
|    +-- test
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

            <entryPoint>["java", "-jar", "/${}.jar"]</entryPoint>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

How to perform grep operation on all files in a directory?

To search in all sub-directories, but only in specific file types, use grep with --include.

For example, searching recursively in current directory, for text in *.yml and *.yaml :

grep "text to search" -r . --include=*.{yml,yaml}

Select top 1 result using JPA

Use a native SQL query by specifying a @NamedNativeQuery annotation on the entity class, or by using the EntityManager.createNativeQuery method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<script src=""></script>
<img ng-src="{{img_url}}">
<button ng-click="img_url = ''">Click</button>

Here is a jsFiddle of a working example:

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"

var returnedData = $.grep(data.items, function (element, index) {
    return == 1;

alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

Convert string to int if string is a number

Cast to long or cast to int, be aware of the following.

These functions are one of the view functions in Excel VBA that are depending on the system regional settings. So if you use a comma in your double like in some countries in Europe, you will experience an error in the US.

E.g., in european excel-version 0,5 will perform well with CDbl(), but in US-version it will result in 5. So I recommend to use the following alternative:

Public Function CastLong(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")        

    Dim l As Long
    On Error Resume Next
    l = Round(Val(var))

    ' if error occurs, l will be 0
    CastLong = l

End Function

' similar function for cast-int, you can add minimum and maximum value if you like
' to prevent that value is too high or too low.
Public Function CastInt(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")

    Dim i As Integer
    On Error Resume Next
    i = Round(Val(var))

    ' if error occurs, i will be 0
    CastInt = i

End Function

Of course you can also think of cases where people use commas and dots, e.g., three-thousand as 3,000.00. If you require functionality for these kind of cases, then you have to check for another solution.

How to use protractor to check if an element is visible?

 element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
if (isVisible) {
    // element is visible
} else {
    // element is not visible
console.log("Element is not found");

Delete all data in SQL Server database

As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.

How to debug in Django, the good way?

As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.

To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.

Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.

As mentioned already django-debug-toolbar is essential -

And while not explicitly a debug or analysis tool - one of my favorites is SQL Printing Middleware available from Django Snippets at

This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).

I find it invaluable for keeping an eye on query performance while developing and debugging my application.

Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.

Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.

How to increment an iterator by 2?

We can use both std::advance as well as std::next, but there's a difference between the two.

advance modifies its argument and returns nothing. So it can be used as:

vector<int> v;
auto itr = v.begin();
advance(itr, 1);          //modifies the itr
cout << *itr<<endl        //prints 2

next returns a modified copy of the iterator:

vector<int> v;
cout << *next(v.begin(), 1) << endl;    //prints 2

System.Security.SecurityException when writing to Event Log

I'm not working on IIS, but I do have an application that throws the same error on a 2K8 box. It works just fine on a 2K3 box, go figure.

My resolution was to "Run as administrator" to give the application elevated rights and everything works happily. I hope this helps lead you in the right direction.

Windows 2008 is rights/permissions/elevation is really different from Windows 2003, gar.

Apply CSS style attribute dynamically in Angular JS

Directly from ngStyle docs:

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.

<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>

So you could do this:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Hope this helps!

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

How to get thread id of a pthread in linux c program?

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3... to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2) function should be used.

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");

How to use RecyclerView inside NestedScrollView?

Replace your recyclerView with,

    android:layout_height="wrap_content" />



will manage the rest of things.

One more thing, no need to put your recyclerView inside NestedScrollView

How to do this in Laravel, subquery where in

Please try this online tool sql2builder

    ->whereIn('',function($query) {

Prevent line-break of span element

Put this in your CSS:


Get more information here:


The white-space property declares how white space inside the element is handled.


normal This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.

nowrap This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

pre-line This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

inherit Takes the same specified value as the property for the element's parent.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

please check the mysql.ini file in your xampp mysql installation... its found on xampp/mysql/bin directory

check the line 43

> log_error="mysql_error.log"
> #bind-address=""

uncomment the line 43 if its still commented

Initialize static variables in C++ class?

Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.

// MyClass.cpp

#include "MyClass.h"

// anonymous namespace
    string RE_ANY = "([^\\n]*)";
    string RE_ANY_RELUCTANT = "([^\\n]*?)";

// member function (static or not)
bool MyClass::foo()
    // logic that uses constants
    return RE_ANY_RELUCTANT.size() > 0;

What is the difference between Serialization and Marshaling?

Basics First

Byte Stream - Stream is sequence of data. Input stream - reads data from source. Output stream - writes data to desitnation. Java Byte Streams are used to perform input/output byte by byte(8bits at a time). A byte stream is suitable for processing raw data like binary files. Java Character Streams are used to perform input/output 2 bytes at a time, because Characters are stored using Unicode conventions in Java with 2 bytes for each character. Character stream is useful when we process(read/write) text files.

RMI(Remote Method Invocation) - an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.

Both Serialization and Marshalling are loosely used as synonyms. Here are few differences.

Serialization - Data members of an object is written to binary form or Byte Stream(and then can be written in file/memory/database etc). No information about data-types can be retained once object data members are written to binary form.

enter image description here

Marshalling - Object is serialized(to byte stream in binary format) with data-type + Codebase attached and then passed Remote Object(RMI). Marshalling will transform the data-type into a predetermined naming convention so that it can be reconstructed with respect to the initial data-type. enter image description here

So Serialization is part of Marshalling.

CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location. (Copied from @Nasir answer)

Serialization is almost like a stupid memory-dump of the memory used by the object(s), while Marshalling stores information about custom data-types.

In a way, Serialization performs marshalling with implematation of pass-by-value because no information of data-type is passed, just the primitive form is passed to byte stream.

Serialization may have some issues related to big-endian, small-endian if the stream is going from one OS to another if the different OS have different means of representing the same data. On the other hand, marshalling is perfectly fine to migrate between OS because the result is a higher-level representation.

What does O(log n) mean exactly?

The logarithm

Ok let's try and fully understand what a logarithm actually is.

Imagine we have a rope and we have tied it to a horse. If the rope is directly tied to the horse, the force the horse would need to pull away (say, from a man) is directly 1.

Now imagine the rope is looped round a pole. The horse to get away will now have to pull many times harder. The amount of times will depend on the roughness of the rope and the size of the pole, but let's assume it will multiply one's strength by 10 (when the rope makes a complete turn).

Now if the rope is looped once, the horse will need to pull 10 times harder. If the human decides to make it really difficult for the horse, he may loop the rope again round a pole, increasing it's strength by an additional 10 times. A third loop will again increase the strength by a further 10 times.

enter image description here

We can see that for each loop, the value increases by 10. The number of turns required to get any number is called the logarithm of the number i.e. we need 3 posts to multiple your strength by 1000 times, 6 posts to multiply your strength by 1,000,000.

3 is the logarithm of 1,000, and 6 is the logarithm of 1,000,000 (base 10).

So what does O(log n) actually mean?

In our example above, our 'growth rate' is O(log n). For every additional loop, the force our rope can handle is 10 times more:

Turns | Max Force
  0   |   1
  1   |   10
  2   |   100
  3   |   1000
  4   |   10000
  n   |   10^n

Now the example above did use base 10, but fortunately the base of the log is insignificant when we talk about big o notation.

Now let's imagine you are trying to guess a number between 1-100.

Your Friend: Guess my number between 1-100! 
Your Guess: 50
Your Friend: Lower!
Your Guess: 25
Your Friend: Lower!
Your Guess: 13
Your Friend: Higher!
Your Guess: 19
Your Friend: Higher!
Your Friend: 22
Your Guess: Lower!
Your Guess: 20
Your Friend: Higher!
Your Guess: 21
Your Friend: YOU GOT IT!  

Now it took you 7 guesses to get this right. But what is the relationship here? What is the most amount of items that you can guess from each additional guess?

Guesses | Items
  1     |   2
  2     |   4
  3     |   8
  4     |   16
  5     |   32
  6     |   64
  7     |   128
  10    |   1024

Using the graph, we can see that if we use a binary search to guess a number between 1-100 it will take us at most 7 attempts. If we had 128 numbers, we could also guess the number in 7 attemps but 129 numbers will takes us at most 8 attempts (in relations to logarithms, here we would need 7 guesses for a 128 value range, 10 guesses for a 1024 value range. 7 is the logarithm of 128, 10 is the logarithm of 1024 (base 2)).

Notice that I have bolded 'at most'. Big-O notation always refers to the worse case. If you're lucky, you could guess the number in one attempt and so the best case is O(1), but that's another story.

We can see that for every guess our data set is shrinking. A good rule of thumb to identify if an algorithm has a logarithmtic time is to see if the data set shrinks by a certain order after each iteration

What about O(n log n)?

You will eventually come across a linearithmic time O(n log(n)) algorithm. The rule of thumb above applies again, but this time the logarithmic function has to run n times e.g. reducing the size of a list n times, which occurs in algorithms like a mergesort.

You can easily identify if the algorithmic time is n log n. Look for an outer loop which iterates through a list (O(n)). Then look to see if there is an inner loop. If the inner loop is cutting/reducing the data set on each iteration, that loop is (O(log n)), and so the overall algorithm is = O(n log n).

Disclaimer: The rope-logarithm example was grabbed from the excellent Mathematician's Delight book by W.Sawyer.

JavaScript: IIF like statement

'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';

Why does modern Perl avoid UTF-8 by default?

There are two stages to processing Unicode text. The first is "how can I input it and output it without losing information". The second is "how do I treat text according to local language conventions".

tchrist's post covers both, but the second part is where 99% of the text in his post comes from. Most programs don't even handle I/O correctly, so it's important to understand that before you even begin to worry about normalization and collation.

This post aims to solve that first problem

When you read data into Perl, it doesn't care what encoding it is. It allocates some memory and stashes the bytes away there. If you say print $str, it just blits those bytes out to your terminal, which is probably set to assume everything that is written to it is UTF-8, and your text shows up.


Except, it's not. If you try to treat the data as text, you'll see that Something Bad is happening. You need go no further than length to see that what Perl thinks about your string and what you think about your string disagree. Write a one-liner like: perl -E 'while(<>){ chomp; say length }' and type in ???? and you get 12... not the correct answer, 4.

That's because Perl assumes your string is not text. You have to tell it that it's text before it will give you the right answer.

That's easy enough; the Encode module has the functions to do that. The generic entry point is Encode::decode (or use Encode qw(decode), of course). That function takes some string from the outside world (what we'll call "octets", a fancy of way of saying "8-bit bytes"), and turns it into some text that Perl will understand. The first argument is a character encoding name, like "UTF-8" or "ASCII" or "EUC-JP". The second argument is the string. The return value is the Perl scalar containing the text.

(There is also Encode::decode_utf8, which assumes UTF-8 for the encoding.)

If we rewrite our one-liner:

perl -MEncode=decode -E 'while(<>){ chomp; say length decode("UTF-8", $_) }'

We type in ???? and get "4" as the result. Success.

That, right there, is the solution to 99% of Unicode problems in Perl.

The key is, whenever any text comes into your program, you must decode it. The Internet cannot transmit characters. Files cannot store characters. There are no characters in your database. There are only octets, and you can't treat octets as characters in Perl. You must decode the encoded octets into Perl characters with the Encode module.

The other half of the problem is getting data out of your program. That's easy to; you just say use Encode qw(encode), decide what the encoding your data will be in (UTF-8 to terminals that understand UTF-8, UTF-16 for files on Windows, etc.), and then output the result of encode($encoding, $data) instead of just outputting $data.

This operation converts Perl's characters, which is what your program operates on, to octets that can be used by the outside world. It would be a lot easier if we could just send characters over the Internet or to our terminals, but we can't: octets only. So we have to convert characters to octets, otherwise the results are undefined.

To summarize: encode all outputs and decode all inputs.

Now we'll talk about three issues that make this a little challenging. The first is libraries. Do they handle text correctly? The answer is... they try. If you download a web page, LWP will give you your result back as text. If you call the right method on the result, that is (and that happens to be decoded_content, not content, which is just the octet stream that it got from the server.) Database drivers can be flaky; if you use DBD::SQLite with just Perl, it will work out, but if some other tool has put text stored as some encoding other than UTF-8 in your database... well... it's not going to be handled correctly until you write code to handle it correctly.

Outputting data is usually easier, but if you see "wide character in print", then you know you're messing up the encoding somewhere. That warning means "hey, you're trying to leak Perl characters to the outside world and that doesn't make any sense". Your program appears to work (because the other end usually handles the raw Perl characters correctly), but it is very broken and could stop working at any moment. Fix it with an explicit Encode::encode!

The second problem is UTF-8 encoded source code. Unless you say use utf8 at the top of each file, Perl will not assume that your source code is UTF-8. This means that each time you say something like my $var = '??', you're injecting garbage into your program that will totally break everything horribly. You don't have to "use utf8", but if you don't, you must not use any non-ASCII characters in your program.

The third problem is how Perl handles The Past. A long time ago, there was no such thing as Unicode, and Perl assumed that everything was Latin-1 text or binary. So when data comes into your program and you start treating it as text, Perl treats each octet as a Latin-1 character. That's why, when we asked for the length of "????", we got 12. Perl assumed that we were operating on the Latin-1 string "æå­åã" (which is 12 characters, some of which are non-printing).

This is called an "implicit upgrade", and it's a perfectly reasonable thing to do, but it's not what you want if your text is not Latin-1. That's why it's critical to explicitly decode input: if you don't do it, Perl will, and it might do it wrong.

People run into trouble where half their data is a proper character string, and some is still binary. Perl will interpret the part that's still binary as though it's Latin-1 text and then combine it with the correct character data. This will make it look like handling your characters correctly broke your program, but in reality, you just haven't fixed it enough.

Here's an example: you have a program that reads a UTF-8-encoded text file, you tack on a Unicode PILE OF POO to each line, and you print it out. You write it like:

    say "$_ ";

And then run on some UTF-8 encoded data, like:

perl input-data.txt

It prints the UTF-8 data with a poo at the end of each line. Perfect, my program works!

But nope, you're just doing binary concatenation. You're reading octets from the file, removing a \n with chomp, and then tacking on the bytes in the UTF-8 representation of the PILE OF POO character. When you revise your program to decode the data from the file and encode the output, you'll notice that you get garbage ("ð©") instead of the poo. This will lead you to believe that decoding the input file is the wrong thing to do. It's not.

The problem is that the poo is being implicitly upgraded as latin-1. If you use utf8 to make the literal text instead of binary, then it will work again!

(That's the number one problem I see when helping people with Unicode. They did part right and that broke their program. That's what's sad about undefined results: you can have a working program for a long time, but when you start to repair it, it breaks. Don't worry; if you are adding encode/decode statements to your program and it breaks, it just means you have more work to do. Next time, when you design with Unicode in mind from the beginning, it will be much easier!)

That's really all you need to know about Perl and Unicode. If you tell Perl what your data is, it has the best Unicode support among all popular programming languages. If you assume it will magically know what sort of text you are feeding it, though, then you're going to trash your data irrevocably. Just because your program works today on your UTF-8 terminal doesn't mean it will work tomorrow on a UTF-16 encoded file. So make it safe now, and save yourself the headache of trashing your users' data!

The easy part of handling Unicode is encoding output and decoding input. The hard part is finding all your input and output, and determining which encoding it is. But that's why you get the big bucks :)

Which loop is faster, while or for?

In C#, the For loop is slightly faster.

For loop average about 2.95 to 3.02 ms.

The While loop averaged about 3.05 to 3.37 ms.

Quick little console app to prove:

 class Program
        static void Main(string[] args)
            int max = 1000000000;
            Stopwatch stopWatch = new Stopwatch();

            if (args.Length == 1 && args[0].ToString() == "While")
                Console.WriteLine("While Loop: ");
                Console.WriteLine("For Loop: ");

        private static void WhileLoop(int max)
            int i = 0;
            while (i <= max)

        private static void ForLoop(int max)
            for (int i = 0; i <= max; i++)

        private static void DisplayElapsedTime(TimeSpan ts)
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");

Angular 2: 404 error occur when I refresh through the browser

For people (like me) who really want PathLocationStrategy (i.e. html5Mode) instead of HashLocationStrategy, see How to: Configure your server to work with html5Mode from a third-party wiki:

When you have html5Mode enabled, the # character will no longer be used in your URLs. The # symbol is useful because it requires no server side configuration. Without #, the URL looks much nicer, but it also requires server side rewrites.

Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).


<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow HTML5 state links
        RewriteRule ^ index.html [L]

Documentation for rewrite module


server {
    server_name my-app;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;

Documentation for try_files


      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <action type="Rewrite" url="/" />

Use placeholders in yaml

I suppose would be an acceptable solution to your problem

How to use SVG markers in Google Maps API v3

Yes you can use an .svg file for the icon just like you can .png or another image file format. Just set the url of the icon to the directory where the .svg file is located. For example:

var icon = {
        url: 'path/to/images/car.svg',
        size: new google.maps.Size(sizeX, sizeY),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(sizeX/2, sizeY/2)

var marker = new google.maps.Marker({
        position: event.latLng,
        map: map,
        draggable: false,
        icon: icon

MongoDB via Mongoose JS - What is findByID?

findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.


// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

UserModel.findOne({_id: id}, function (err, user) { ... });

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

CALL command vs. START with /WAIT option

This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.

In the end, piping the command through more did the trick.

setup.exe {arguments} | more

how to toggle (hide/show) a table onClick of <a> tag in java script

Simple using jquery

$(document).ready(function() {
    $('#loginLink').click(function() {

What are the differences between a HashMap and a Hashtable in Java?

In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.

Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.

Extreme wait-time when taking a SQL Server database offline

For me, I just had to go into the Job Activity Monitor and stop two things that were processing. Then it went offline immediately. In my case though I knew what those 2 processes were and that it was ok to stop them.

The name 'controlname' does not exist in the current context

I fixed this in my project by backing up the current files (so I still had my code), deleting the current aspx (and child pages), making a new one, and copying the contents of the backup files into the new files.

How to finish Activity when starting other activity in Android?

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

Using filesystem in node.js with async / await

As of v10.0, you can use fs.Promises

Example using readdir

const { promises: fs } = require("fs");

async function myF() {
    let names;
    try {
        names = await fs.readdir("path/to/dir");
    } catch (e) {
        console.log("e", e);
    if (names === undefined) {
    } else {
        console.log("First Name", names[0]);


Example using readFile

const { promises: fs } = require("fs");

async function getContent(filePath, encoding = "utf-8") {
    if (!filePath) {
        throw new Error("filePath required");

    return fs.readFile(filePath, { encoding });

(async () => {
    const content = await getContent("./package.json");


How do I resolve a HTTP 414 "Request URI too long" error?

Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:

jQuery Ajax POST example with PHP (Note the sanitize posted data remark) and

Basically, the difference is that the GET request has the url and parameters in one string and then sends null:"GET", url+"?"+params, true);

whereas the POST request sends the url and the parameters in separate commands:"POST", url, true);

Here is a working example:


<script type="text/javascript">
    function ajaxPOSTTest() {
        try {
            // Opera 8.0+, Firefox, Safari
            ajaxPOSTTestRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;

        ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
        var url = "ajaxPOST.php";
        var params = "lorem=ipsum&name=binny";"POST", url, true);
        ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    //Create a function that will receive data sent from the server
    function ajaxCalled_POSTTest() {
        if (ajaxPOSTTestRequest.readyState == 4) {
            document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;

    <button onclick="ajaxPOSTTest()">ajax POST Test</button>
    <div id="output"></div>



print $lorem.'<br>';


I just sent over 12,000 characters without any problems.

Setting POST variable without using form

You can do it using jQuery. Example:

<script src=""></script>

        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
            //data - response from server

How to override the path of PHP to use the MAMP path?

Everytime you save MAMP config (PHP section), it saves the current version of PHP on ~/.profile file and creates the alias for php, pear and pecl, to point to the current configured version. (Note: you need to check "Make this version available on the command line" option in MAMP)

However, you need to refresh your terminal (open another session) to get this file refreshed. You can also type source ~/.profile to refesh the aliases manually.

If you want to extract this curerent version in a PHP_VERSION variable - as commented above - for further use, you can do:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`

And then you'll have $PHP_VERSION available with the current version of MAMP.

Finally, if you want to run your php using the current configured version on mamp, you just need to add to your ~/.bash_profile the following:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`
export PHPRC="/Library/Application Support/appsolute/MAMP PRO/conf/" #point to your php.ini folder to use the same php settings
export PATH=/Applications/MAMP/bin/php/php$PHP_VERSION/bin:$PATH

Now, even script that relies on /usr/bin/env php will read the correct version from Mamp config.

Changing background color of ListView items on Android

No one seemed to provide any examples of doing this solely using an adapter, so I thought I would post my code snippet for displaying ListViews where the "curSelected" item has a different background:

final ListView lv = (ListView)findViewById(;
lv.setAdapter(new BaseAdapter()
    public View getView(int position, View convertView, ViewGroup parent)
        if (convertView == null)
            convertView = new TextView(ListHighlightTestActivity.this);
            convertView.setPadding(10, 10, 10, 10);

        convertView.setBackgroundColor((position == curSelected) ? 
            Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));

        return convertView;

    public long getItemId(int position)
        return position;

    public Object getItem(int position)
        return "item " + position;

    public int getCount()
        return 20;

This has always been a helpful approach for me for when appearance of list items needs to change dynamically.

Disable Copy or Paste action for text box?

Check this fiddle.

 $('#email').bind("cut copy paste",function(e) {

You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.

You can find a detailed explanation here.

How to create a inset box-shadow only on one side?

Inset Box Shadow only on Top side?

#box {
            background: #CCC;
            -webkit-box-shadow: inset 0 20px 20px -20px rgba(0,0,0,0.8);
            -moz-box-shadow: inset 0 20px 20px -20px rgba(0,0,0,0.8);
            box-shadow: inset 0 20px 20px -20px rgba(0,0,0,0.8);
            font: bold 18px/1.2em sans-serif;
            height: auto;
            margin: 15px auto;
            padding: 75px 15px 25px;
            text-align: center;
            width: 80%;

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Let's go in reverse order:

  • Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statement. You know that an error has occurred and therefore you're logging an error.

  • Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."

  • Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.

  • Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.

  • Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.

And as a bonus...

  • Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yeah, if you wanna log them use

How do I resolve "Run-time error '429': ActiveX component can't create object"?

I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version

How to use Git for Unity3D source control?

I suggest that you make a .gitignore file that includes everything other than the assets folder (all the other files that are originally inside a unity project). Next, you should place all your game projects in one folder. Next, duplicate the .gitignore in every single project folder for your games. This will exclude the libraries and unnecessary folders inside your projects other than the assets. If you have any projects you don't want, then put them in a new .gitignore inside where your game projects are stored. Note: You can have multiple .gitignore's and .gitignore is based on relative paths. I hope that helped!

How to hide iOS status bar

In iOS10 all I needed to do is override the prefersStatusBarHidden var in my RootViewController (Swift):

override var prefersStatusBarHidden: Bool {
    return true

How to define the css :hover state in a jQuery selector?

Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.

If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.

Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:

$('head').append('<style>.myclass:hover div {background-color : red;}</style>')

If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.

Python interpreter error, x takes no arguments (1 given)

Make sure, that all of your class methods (updateVelocity, updatePosition, ...) take at least one positional argument, which is canonically named self and refers to the current instance of the class.

When you call particle.updateVelocity(), the called method implicitly gets an argument: the instance, here particle as first parameter.

Currently running queries in SQL Server

There's this, from SQL Server DMV's In Action book:

The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).

The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.

USE master
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain

FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid

How to create dictionary and add key–value pairs dynamically?

I happened to walk across this question looking for something similar. It gave me enough info to run a test to get the answer I wanted. So if anyone else wants to know how to dynamically add to or lookup a {key: 'value'} pair in a JavaScript object, this test should tell you all you might need to know.

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';


dictionary[key] =value;
dictionary[key2] = value2;


{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }

How to wait for all threads to finish, using ExecutorService?

I've just written a sample program that solves your problem. There was no concise implementation given, so I'll add one. While you can use executor.shutdown() and executor.awaitTermination(), it is not the best practice as the time taken by different threads would be unpredictable.

ExecutorService es = Executors.newCachedThreadPool();
    List<Callable<Integer>> tasks = new ArrayList<>();

    for (int j = 1; j <= 10; j++) {
        tasks.add(new Callable<Integer>() {

            public Integer call() throws Exception {
                int sum = 0;
                System.out.println("Starting Thread "
                        + Thread.currentThread().getId());

                for (int i = 0; i < 1000000; i++) {
                    sum += i;

                System.out.println("Stopping Thread "
                        + Thread.currentThread().getId());
                return sum;


    try {
        List<Future<Integer>> futures = es.invokeAll(tasks);
        int flag = 0;

        for (Future<Integer> f : futures) {
            Integer res = f.get();
            System.out.println("Sum: " + res);
            if (!f.isDone()) 
                flag = 1;

        if (flag == 0)

    } catch (InterruptedException | ExecutionException e) {

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

You should use this example with AUTHID CURRENT_USER :

   SEQ_NAME       VARCHAR2 (100);
   cur_id         NUMBER;



      -- ELSE
        FROM DUAL;

      cur_id := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
      DBMS_SQL.CLOSE_CURSOR (cur_id);

   END IF;


How to render an ASP.NET MVC view as a string?

I saw an implementation for MVC 3 and Razor from another website, it worked for me:

    public static string RazorRender(Controller context, string DefaultAction)
        string Cache = string.Empty;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.TextWriter tw = new System.IO.StringWriter(sb); 

        RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
        view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);

        Cache = sb.ToString(); 

        return Cache;


    public static string RenderRazorViewToString(string viewName, object model)

        ViewData.Model = model;
        using (var sw = new StringWriter())
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();

    public static class HtmlHelperExtensions
        public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
            ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

            if (result.View != null)
                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                    using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                        result.View.Render(viewContext, output);
                return sb.ToString();

            return String.Empty;



More on Razor render- MVC3 View Render to String

Mockito, JUnit and Spring

You don't really need the MockitoAnnotations.initMocks(this); if you're using mockito 1.9 ( or newer ) - all you need is this:

private MyTestObject testObject;

private MyDependentObject mockedObject;

The @InjectMocks annotation will inject all your mocks to the MyTestObject object.

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Why would someone use WHERE 1=1 AND <proper conditions>

I've seen homespun frameworks do stuff like this (blush), as this allows lazy parsing practices to be applied to both the WHERE and AND Sql keywords.

For example (I'm using C# as an example here), consider the conditional parsing of the following predicates in a Sql query string builder:

var sqlQuery = "SELECT * FROM FOOS WHERE 1 = 1"
if (shouldFilterForBars)
    sqlQuery = sqlQuery + " AND Bars > 3";
if (shouldFilterForBaz)
    sqlQuery = sqlQuery + " AND Baz < 12";

The "benefit" of WHERE 1 = 1 means that no special code is needed:

  • For AND - whether zero, one or both predicates (Bars and Baz's) should be applied, which would determine whether the first AND is required. Since we already have at least one predicate with the 1 = 1, it means AND is always OK.
  • For no predicates at all - In the case where there are ZERO predicates, then the WHERE must be dropped. But again, we can be lazy, because we are again guarantee of at least one predicate.

This is obviously a bad idea and would recommend using an established data access framework or ORM for parsing optional and conditional predicates in this way.

How does the ARM architecture differ from x86?

The ARM is like an Italian sports car:

  • Well balanced, well tuned, engine. Gives good acceleration, and top speed.
  • Excellent chases, brakes and suspension. Can stop quickly, can corner without slowing down.

The x86 is like an American muscle car:

  • Big engine, big fuel pump. Gives excellent top speed, and acceleration, but uses a lot of fuel.
  • Dreadful brakes, you need to put an appointment in your diary, if you want to slowdown.
  • Terrible steering, you have to slow down to corner.

In summary: the x86 is based on a design from 1974 and is good in a straight line (but uses a lot of fuel). The arm uses little fuel, does not slowdown for corners (branches).

Metaphor over, here are some real differences.

  • Arm has more registers.
  • Arm has few special purpose registers, x86 is all special purpose registers (so less moving stuff around).
  • Arm has few memory access commands, only load/store register.
  • Arm is internally Harvard architecture my design.
  • Arm is simple and fast.
  • Arm instructions are architecturally single cycle (except load/store multiple).
  • Arm instructions often do more than one thing (in a single cycle).
  • Where more that one Arm instruction is needed, such as the x86's looping store & auto-increment, the Arm still does it in less clock cycles.
  • Arm has more conditional instructions.
  • Arm's branch predictor is trivially simple (if unconditional or backwards then assume branch, else assume not-branch), and performs better that the very very very complex one in the x86 (there is not enough space here to explain it, not that I could).
  • Arm has a simple consistent instruction set (you could compile by hand, and learn the instruction set quickly).

Reset par to the default values at startup is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:

def.par = par()

Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:

par(def.par) #go back to default par settings

With this, you keep generated plots and reset par settings.

How to bind to a PasswordBox in MVVM

You can use this XAML:

        <i:EventTrigger EventName="PasswordChanged">
            <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=PasswordBox}}" CommandParameter="{Binding ElementName=PasswordBox}"/>

And this command execute method:

private void ExecutePasswordChangedCommand(PasswordBox obj)
   if (obj != null)
     Password = obj.Password;

This requires adding the System.Windows.Interactivity assembly to your project and referencing it via xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity".

How to pass data from 2nd activity to 1st activity when pressed back? - android

Start Activity2 with startActivityForResult and use setResult method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult for updating TextView with EditText data from Activity2.

For example:

In Activity1, start Activity2 as:

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);

In Activity2, use setResult for sending data back:

Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);        

And in Activity1, receive data with onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK) {
             String strEditText = data.getStringExtra("editTextValue");

If you can, also use SharedPreferences for sharing data between Activities.

file_get_contents behind a proxy?

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://',
        'request_fulluri' => true,
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("", False, $cxContext);

echo $sFile;

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

If you're getting that kind of error :

Warning: file_get_contents( [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://',
        'request_fulluri' => true,
        'header'          => "Proxy-Authorization: Basic $auth",
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("", False, $cxContext);

echo $sFile;

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)

MySQL SELECT WHERE datetime matches day (and not necessarily time)

SELECT * FROM table where Date(col) = 'date'

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        

    // ...

    this.init(); // <------------ added this

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

get string from right hand side

substr(PHONE_NUMBERS, length(PHONE_NUMBERS) - 3, 4)

How to combine results of two queries into a single dataset

This is what you can do. Assuming that your ProductName column have common values.

FROM Table1
ON Table1.ProductName= Table2.ProductName

Integer value in TextView

It might be cleaner for some people to work with an Integer object so you can just call toString() directly on the object:

Integer length = my_text_view.getText().getLength();
counter_text_view.setText( length.toString() );

How to remove an HTML element using Javascript?

Try running this code in your script.


And it will hopefully remove the element/button.

Android Studio gradle takes too long to build

In Android Studio, above Version 3.6, There is a new location to toggle Gradle's offline mode To enable or disable Gradle's offline mode.

To enable or disable Gradle's offline mode, select View > Tool Windows > Gradle from the menu. In the top bar of the Gradle window, click Toggle Offline Mode (near settings icon).

enter image description here

It's a little bit confusing on the icon, anyway offline mode is enabled when the toggle button is highlighted. :)

How to drop columns using Rails migration

remove_column in change method will help you to delete the column from the table.

class RemoveColumn < ActiveRecord::Migration
  def change
    remove_column :table_name, :column_name, :data_type

Go on this link for complete reference :

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

How do I deserialize a complex JSON object in C# .NET?

I had a scenario, and this one helped me

JObject objParserd = JObject.Parse(jsonString);

JObject arrayObject1 = (JObject)objParserd["d"];

D myOutput= JsonConvert.DeserializeObject<D>(arrayObject1.ToString());

Extract file basename without path and extension in bash

Here is another (more complex) way of getting either the filename or extension, first use the rev command to invert the file path, cut from the first . and then invert the file path again, like this:

filename=`rev <<< "$1" | cut -d"." -f2- | rev`
fileext=`rev <<< "$1" | cut -d"." -f1 | rev`

Regex in JavaScript for validating decimal numbers


will allow:

  1. 244
  2. 10.89
  3. 9.5

will disallow:

  1. 10.895
  2. 10.
  3. 10.8.9

JQuery: dynamic height() with window resize()

The cleanest solution - also purely CSS - would be using calc and vh.

The middle div's heigh will be calculated thusly:

#middle-div { 
height: calc(100vh - 46px); 

That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

Why can't DateTime.Parse parse UTC date

You need to specify the format:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 

Is there a "theirs" version of "git merge -s ours"?

I used the answer from Paul Pladijs since now. I found out, you can do a "normal" merge, conflicts occur, so you do

git checkout --theirs <file>

to resolve the conflict by using the revision from the other branch. If you do this for each file, you have the same behaviour as you would expect from

git merge <branch> -s theirs

Anyway, the effort is more than it would be with the merge-strategy! (This was tested with git version 1.8.0)

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup


SqlDataAdapter vs SqlDataReader

The answer to that can be quite broad.

Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.

Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.

WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.

Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:

Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using     

equivalent C#:

using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
    using(var rdr = cmd.ExecuteReader())

What is output buffering?

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

More Resources:

Output Buffering With PHP

How to finish current activity in Android

What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:


and not


Resize svg when window is resized in d3.js

It's kind of ugly if the resizing code is almost as long as the code for building the graph in first place. So instead of resizing every element of the existing chart, why not simply reloading it? Here is how it worked for me:

function data_display(data){
   e = document.getElementById('data-div');
   var w = e.clientWidth;
   // remove old svg if any -- otherwise resizing adds a second one'svg').remove();
   // create canvas
   var svg ='#data-div').append('svg')
                                   .attr('height', 100)
                                   .attr('width', w);
   // now add lots of beautiful elements to your graph
   // ...

data_display(my_data); // call on page load

window.addEventListener('resize', function(event){
    data_display(my_data); // just call it again...

The crucial line is'svg').remove();. Otherwise each resizing will add another SVG element below the previous one.

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

AND/OR in Python?

x and y returns true if both x and y are true.
x or y returns if either one is true.

From this we can conclude that or contains and within itself unless you mean xOR (or except if and is true)

CMake does not find Visual C++ compiler

I ran into the same issue and fixed it by relaunching the Visual Studio Install and checking the following option:

Windows and Web Development / Universal Windows App Development Tools / Windows 10 SDK

It contains the standard C++ headers used in most applications and therefore it is often necessary to install it as well.

How to make picturebox transparent?

Try using an ImageList

ImageList imgList = new ImageList;

imgList.TransparentColor = Color.White;

Load the image like this:

picturebox.Image = imgList.Images[img_index];

The property 'value' does not exist on value of type 'HTMLElement'

We could assert

const inputElement: HTMLInputElement = document.getElementById('greet')

Or with as-syntax

const inputElement = document.getElementById('greet') as HTMLInputElement


const inputValue = inputElement.value // now inferred to be string

How do I access nested HashMaps in Java?

You can get the nested value by repeating .get(), but with deeply nested maps you have to do a lot of casting into Map. An easier way is to use a generic method for getting a nested value.


public static <T> T getNestedValue(Map map, String... keys) {
    Object value = map;

    for (String key : keys) {
        value = ((Map) value).get(key);

    return (T) value;


// Map contents with string and even a list:
  "data": {
    "vehicles": {
      "list": [
          "registration": {
            "owner": {
              "id": "3643619"
List<Map> list = getNestedValue(mapContents, "data", "vehicles", "list");
Map first = list.get(0);
String id = getNestedValue(first, "registration", "owner", "id");

Word count from a txt file program

for word in
    if word not in wordcount:
        wordcount[word] = 1
        wordcount[word] += 1

for k,v in wordcount.items():
    print k,v

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

I expanded the code, because it's not told me the 'record number', and I must to refind it.

CREATE PROC SearchAllTables
@SearchStr nvarchar(100)

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site:
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)

CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))


DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    ,@TableShortName nvarchar(256)
    ,@TableKeys nvarchar(512)
    ,@SQL nvarchar(3830)

SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    SET @ColumnName = ''

    -- Scan Tables
    SET @TableName = 
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    Set @TableShortName=PARSENAME(@TableName, 1)
    -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***

        -- LOOK Key Fields, Set Key Columns
        SET @TableKeys=''
        SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
         FROM syscolumns 
         WHERE [id] IN (
            SELECT [id] 
             FROM sysobjects 
             WHERE [name] = @TableShortName)
           AND colid IN (
            SELECT SIK.colid 
             FROM sysindexkeys SIK 
             JOIN sysobjects SO ON 
                SIK.[id] = SO.[id]  
                SIK.indid = 1
                AND SO.[name] = @TableShortName)
        If @TableKeys<>''
            SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
        -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***

    -- Search in Columns
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        SET @ColumnName =
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        ) -- Set ColumnName

        IF @ColumnName IS NOT NULL
            SET @SQL='
                    ''' + @TableName + '''
                    ,''' + @ColumnName + '''
                ,LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            --Print @SQL -- *** DEBUG LINE ***
            INSERT INTO #Results
                Exec (@SQL)
        END -- IF ColumnName
    END -- While Table and Column
END --While Table

SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results

Understanding typedefs for function pointers in C

A very easy way to understand typedef of function pointer:

int add(int a, int b)
    return (a+b);

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
    add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    return 0;

CSS /JS to prevent dragging of ghost image?

You can use "Empty Img Element".
Empty Img Element - document.createElement("img")

[HTML Code]
<div id="hello" draggable="true">Drag!!!</div>
[JavaScript Code]
var block = document.querySelector('#hello');
block.addEventListener('dragstart', function(e){
    var img = document.createElement("img");
    e.dataTransfer.setDragImage(img, 0, 0);

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me worked this one:

ALTER TABLE tablename MODIFY fieldname VARCHAR(128) NOT NULL;

How to cancel a Task in await?

One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.

public async Task<Results> ProcessDataAsync(MyData data)
    var client = await GetClientAsync();
    await client.UploadDataAsync(data);
    await client.CalculateAsync();
    return await client.GetResultsAsync();

If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.

public static class TaskExtensions
    public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
        await Task.WhenAny(task, token.WhenCanceled());

        return await task;

    public static Task WhenCanceled(this CancellationToken cancellationToken)
        var tcs = new TaskCompletionSource<bool>();
        cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
        return tcs.Task;

So to use it then just add .WaitOrCancel(token) to any async call:

public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
    Client client;
        client = await GetClientAsync().WaitOrCancel(token);
        await client.UploadDataAsync(data).WaitOrCancel(token);
        await client.CalculateAsync().WaitOrCancel(token);
        return await client.GetResultsAsync().WaitOrCancel(token);
    catch (OperationCanceledException)
        if (client != null)
            await client.CancelAsync();

Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync call in the example, or better yet pass in the same CancellationToken to the Task so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.

ssh: Could not resolve hostname Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver nameserver

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up

I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

Is there a way to break a list into columns?

If you can support it CSS Grid is probably the cleanest way for making a one-dimensional list into a two column layout with responsive interiors.

ul {_x000D_
  max-width: 400px;_x000D_
  display: grid;_x000D_
  grid-template-columns: 50% 50%;_x000D_
  padding-left: 0;_x000D_
  border: 1px solid blue;_x000D_
li {_x000D_
  list-style: inside;_x000D_
  border: 1px dashed red;_x000D_
  padding: 10px;_x000D_

These are the two key lines which will give you your 2 column layout

display: grid;
grid-template-columns: 50% 50%;

How do browser cookie domains work?

Will be able to set cookie for .com?

No, but may be able to set a cookie for Firefox protects against this by maintaining a list of TLDs:

Apparently Internet Explorer doesn't allow two-letter domains to set cookies, which I suppose explains why simply redirects to I'd often wondered that.

How to solve "The specified service has been marked for deletion" error

Most probably deleting service fails because

protected override void OnStop()

throw error when stopping a service. wrapping things inside a try catch will prevent mark for deletion error

protected override void OnStop()
                //things to do
            catch (Exception)


How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file


echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I can also confirm this error.

Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.

That is done in three steps:

1 Install maven on local machine (the test-machine was Ubuntu 10.10)

mvn --version

Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"

2 Run maven externally link how to run maven from console

> cd path-to-pom.xml
> mvn test
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Simple
    [INFO]    task-segment: [test]
    [INFO] ------------------------------------------------------------------------
    [INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
     T E S T S
    Running net.tverrbjelke.experiment.MainAppTest
    Hello World
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
    Results :
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    [INFO] ------------------------------------------------------------------------
    [INFO] ------------------------------------------------------------------------

3 inside m2eclipse: switch from embedded maven to local maven

  • find out where local maven home installation dir is (mvn --version, or google for your MAVEN_HOME, for me this helped me that is /usr/share/maven2 )
  • in eclipse Menu->Window->Preferences->Maven->Installation-> enter that string. Then you should have switched to your new external maven.
  • then run your Project as e.g. "maven test".

The error-message should be gone.

Facebook share link without JavaScript

It is possible to include JavaScript in your code and still support non-JavaScript users.

If a user clicks any of the following links without JavaScript enabled, it will simply open a new tab:

<!-- Remember to change URL_HERE, TITLE_HERE and TWITTER_HANDLE_HERE -->
<a href="" target="_blank" class="share-popup">Share on Facebook</a>
<a href="" target="_blank" class="share-popup">Share on Twitter</a>
<a href="" target="_blank" class="share-popup">Share on Googleplus</a>

Because they contain the share-popup class, we can easily reference these in jQuery, and change the window size to suit the domain we are sharing from:

    var window_size = "width=585,height=511";
    var url = this.href;
    var domain = url.split("/")[2];
    switch(domain) {
        case "":
            window_size = "width=585,height=368";
        case "":
            window_size = "width=585,height=261";
        case "":
            window_size = "width=517,height=511";
    }, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' + window_size);
    return false;

No more ugly inline JavaScript, or countless window sizing alterations. And it still supports non-JavaScript users.

SSIS Connection not found in package

This seems to also happen when you use the new SSIS 2012 "Shared Connection Manager" concept where the connection managers are not defined within your package but the Visual Studio project and just get referenced in the package. Executing it via SQL Agent or DTEXEC yields the same error message.

I haven't found a solution for that yet but would love to get some feedback if anybody experienced it before.

JPA : How to convert a native query result set to POJO class collection

The easiest way is to use so projections. It can map query results directly to interfaces and is easier to implement than using SqlResultSetMapping.

An example is shown below:

public interface PeopleRepository extends JpaRepository<People, Long> {

    @Query(value = "SELECT AS name, COUNT(dp.people_id) AS count " +
        "FROM people p INNER JOIN dream_people dp " +
        "ON = dp.people_id " +
        "WHERE p.user_id = :userId " +
        "GROUP BY dp.people_id " +
        "ORDER BY", nativeQuery = true)
    List<PeopleDTO> findByPeopleAndCountByUserId(@Param("userId") Long userId);

    @Query(value = "SELECT AS name, COUNT(dp.people_id) AS count " +
        "FROM people p INNER JOIN dream_people dp " +
        "ON = dp.people_id " +
        "WHERE p.user_id = :userId " +
        "GROUP BY dp.people_id " +
        "ORDER BY", nativeQuery = true)
    Page<PeopleDTO> findByPeopleAndCountByUserId(@Param("userId") Long userId, Pageable pageable);


// Interface to which result is projected
public interface PeopleDTO {

    String getName();

    Long getCount();


The fields from projected interface must match fields in this entity. Otherwise field mapping might break.

Also if you use SELECT table.column notation always define aliases matching names from entity as shown in example.